First of all, find where the main apache’s config file httpd.conf is located. If you use Debian, it should be here: /etc/apache/httpd.conf
. Using some file editor like Vim or Nano open this file and find the line that looks as follows:
Options Includes Indexes FollowSymLinks MultiViews
then remove word Indexes and save the file. The line should look like this one:
Options Includes FollowSymLinks MultiViews
After it is done, restart apache (e.g. /etc/init.d/apache restart in Debian). That’s it!
After setting the gems directory to the user directory that runs the gem install
, using export GEM_HOME=/home/<user>/gems
, the issue has been solved.
netstat -pln
EDIT: linux only, on other UNIXes netstat may not support all these options.
I was getting the same problem on Spring Tool Suite 3.2 and changed the version of jstl to 1.2 (from 1.1.2) manually when adding it to the dependency list, and the error got disappeared.
import android.graphics.Matrix
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
EDIT: as suggested by by @aveschini, I have added bm.recycle();
for memory leaks. Please note that in case if you are using the previous object for some other purposes, then handle accordingly.
I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :
cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or
#cat release_vars.yml >> vars.yml
mvn ....
Update to the answer
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(st.FrameCount-1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
I encountered the following message repeatedly when trying to start SQL Developer from my installation of Oracle Database 11g Enterprise: Enter the full pathname for java.exe.
No matter how many times I browsed to the correct path, I kept being presented with the exact same dialog box. This was in Windows 7, and the solution was to right-click on the SQL Developer icon and select "Run as administrator". I then used this path: C:\app\shellperson\product\11.1.0\db_1\jdk\jre\bin\java.exe
Loop over Application.Current.Windows[]
and find the one with IsActive == true
.
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/[email protected]">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
Please check if you are were passing method as POST
instead as GET
.
if so you will get same error as a you posted above.
$http({
method: 'GET',
The request entity's media type 'text/plain' is not supported for this resource.
I have the same problem, but I think its worth sharing with you guys. If you have to findViewById in custom layout, for example:
public class MiniPlayerControllBar extends LinearLayout {
//code
}
you cannot get the view in constructor.
You should call findViewById after view has inflated.
Their is a method you can override onFinishInflate
As detailed in this answer, mayur & user3869623's answer's are now relating to a deprecated router. You can now pass multiple parameters as follows:
To call router:
this.router.navigate(['/myUrlPath', "someId", "another ID"]);
In routes.ts:
{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},
Try doing SHIFT + G
and you will be at the end of the page, but you can't edit yet. Go to the top by doing G + G
Unfortunately, All the above answers are only half right.. Took a long time to figure this out..
Mongoose bson install via npm throws warning and causes the error...
npm install -g node-gyp
git clone https://github.com/mongodb/js-bson.git
cd js-bson
npm install
node-gyp rebuild
This works like magic!!
function getTodaysTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const startOfDay = currentTimeStamp - (currentTimeStamp % 86400);_x000D_
return { startOfDay, endOfDay: startOfDay + 86400 - 1 };_x000D_
}_x000D_
_x000D_
// starts from sunday_x000D_
function getThisWeeksTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const currentDay = new Date(currentTimeStamp * 1000);_x000D_
const startOfWeek = currentTimeStamp - (currentDay.getDay() * 86400) - (currentTimeStamp % 86400);_x000D_
return { startOfWeek, endOfWeek: startOfWeek + 7 * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
function getThisMonthsTimeStamp() {_x000D_
const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
const currentDay = new Date(currentTimeStamp * 1000);_x000D_
const startOfMonth = currentTimeStamp - ((currentDay.getDate() - 1) * 86400) - (currentTimeStamp % 86400);_x000D_
const currentMonth = currentDay.getMonth() + 1;_x000D_
let daysInMonth = 0;_x000D_
if (currentMonth === 2) daysInMonth = 28;_x000D_
else if ([1, 3, 5, 7, 8, 10, 12].includes(currentMonth)) daysInMonth = 31;_x000D_
else daysInMonth = 30;_x000D_
return { startOfMonth, endOfMonth: startOfMonth + daysInMonth * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
console.log(getTodaysTimeStamp());_x000D_
console.log(getThisWeeksTimeStamp());_x000D_
console.log(getThisMonthsTimeStamp());
_x000D_
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, MainActivity2.class);
MainActivity.this.startActivity(myIntent);
}
});
The answer for the complete noob from a complete noob:
MainActivity
is the name of the first activity.
MainActivity2
is the name of the second activity.
button1
is the I.D of the button in xml for MainActivity
Activity.
if you edit your php.ini file, remember to restart your service (apache2, etc) for the edits to php.ini to take effect
For the correct solution after many hours:
<add name="umbracoDbDSN" connectionString="data source=YOUR_SERVER_NAME;database=nrc;Integrated Security=SSPI;persist security info=True;" providerName="System.Data.SqlClient" />
Hope this will help.
You can do it. That is what big guys do as well.
First query:
» host google.com
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
Next query:
» host google.com
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
As you see, the list of IPs rotated around, but the relative order between two IPs stayed the same.
Update: I see several comments bragging about how DNS round-robin is not convenient for fail-over, so here is the summary: DNS is not for fail-over. So it is obviously not good for fail-over. It was never designed to be a solution for fail-over.
For me, the emulator could not have Google Play Services enabled. It could have Google APIs or be x86 or x64 but not google play store.
As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.
As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.
Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851
In Oracle, (+) denotes the "optional" table in the JOIN. So in your query,
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id(+)
it's a LEFT OUTER JOIN of table 'b' to table 'a'. It will return all data of table 'a' without losing its data when the other side (optional table 'b') has no data.
The modern standard syntax for the same query would be
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b ON a.id=b.id
or with a shorthand for a.id=b.id
(not supported by all databases):
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b USING(id)
Older syntax, in both Oracle and other databases:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id
More modern syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
INNER JOIN b ON a.id=b.id
Or simply:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
JOIN b ON a.id=b.id
It will only return all data where both 'a' & 'b' tables 'id' value is same, means common part.
This is just the same as a LEFT JOIN, but switches which table is optional.
Old Oracle syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id(+)=b.id
Modern standard syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
RIGHT JOIN b ON a.id=b.id
https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:6585774577187
Android OFFICIALLY supports Java 8 as of Android N.
Feature announcements are here, the Java 8 language announcement is:
Improved Java 8 language support - We’re excited to bring Java 8 language features to Android. With Android's Jack compiler, you can now use many popular Java 8 language features, including lambdas and more, on Android versions as far back as Gingerbread. The new features help reduce boilerplate code. For example, lambdas can replace anonymous inner classes when providing event listeners. Some Java 8 language features --like default and static methods, streams, and functional interfaces -- are also now available on N and above. With Jack, we’re looking forward to tracking the Java language more closely while maintaining backward compatibility.
You cant style the alt attribute directly in css. However the alt will inherit the styles of the item the alt is on or what is inherited by its parent:
<div style="background-color:black; height: 50px; width: 50px; color:white;">_x000D_
<img src="ouch" alt="here i am"/>_x000D_
<div>
_x000D_
In the above example, the alt text will be black. However with the color:white the alt text is white.
You should to use: ConfigurableApplicationContext instead of for ApplicationContext
Teocci solution is as simple as it can be, thus, no need to add any CSS, just add class="fas" for Font Awesome 5, since it adds proper CSS font declaration to the element.
Here's an example for search box within Bootstrap navbar, with search icon added to the both input-group and placeholder (for the sake of demontration, of course, no one would use both at the same time). Image: https://i.imgur.com/v4kQJ77.png "> Code:
<form class="form-inline my-2 my-lg-0">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-search"></i></span>
</div>
<input type="text" class="form-control fas text-right" placeholder="" aria-label="Search string">
<div class="input-group-append">
<button class="btn btn-success input-group-text bg-success text-white border-0">Search</button>
</div>
</div>
</form>
You might find this library helpful! http://code.google.com/p/google-diff-match-patch/
It is currently available in Java, JavaScript, Dart, C++, C#, Objective C, Lua and Python
It works pretty well too. I use it in a couple of my Lua projects.
And I don't think it would be too difficult to port it to other languages!
Since not all versions of jQuery are created equal, you may run into the same issue I did which means calling $("#item").removeClass(); does not actually remove the class. (Probably a bug)
A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.
document.getElementById("item").removeAttribute("class");
If you don't want to remove all the button theme set up.
ButtonTheme.fromButtonThemeData(
data: Theme.of(context).buttonTheme.copyWith(
minWidth: 200.0,
height: 100.0,,
)
child: RaisedButton(
onPressed: () {},
child: Text("test"),
),
);
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
Code
PL_CONNECT_STRING="$DB_USERNAME/$DB_PASSWORD@$DB_SERVICE"
OUTPUT=$(sqlplus -s $PL_CONNECT_STRING <<-END-OF-SQL
select count(*) from table;
exit;
END-OF-SQL)
echo "COMPLETED GATHER STATS $OUTPUT";
Explanation:
PL_CONNECT_STRING
carry database username, password and it service name
sqlplus is used to connect the Database with PL_CONNECT_STRING
details
END-OF-SQL
tag contain the query which you want to execute
echo
is used to print the output of the query
NOTE: You can give multiple Query inside the END-OF-SQL
tag, so its useful for batch execution as well
catch function in your api should either return some data which could be handled by Api call in React class or throw new error which should be caught using a catch function in your React class code. Latter approach should be something like:
return fetch(url)
.then(function(response){
return response.json();
})
.then(function(json){
return {
city: json.name,
temperature: kelvinToF(json.main.temp),
description: _.capitalize(json.weather[0].description)
}
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
// ADD THIS THROW error
throw error;
});
Then in your React Class:
Api(region.latitude, region.longitude)
.then((data) => {
console.log(data);
this.setState(data);
}).catch((error)=>{
console.log("Api call error");
alert(error.message);
});
You are trying to use the string as a function:
"Your new price is: $"(float(price) * 0.1)
Because there is nothing between the string literal and the (..)
parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:
>>> "Hello World!"(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Seems you forgot to concatenate (and call str()
):
easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))
The next line needs fixing as well:
easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))
Alternatively, use string formatting with str.format()
:
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))
where {:02.2f}
will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.
I would use list comprehension :
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
cart_prod = [(a,b,c) for a in somelists[0] for b in somelists[1] for c in somelists[2]]
The below code provides the results which replaces NULL to zero in the output.
Table creation and data insertion:
create table test_table
(
date nvarchar(10),
category char(3),
amount money
)
insert into test_table values ('1/1/2012','ABC',1000.00)
insert into test_table values ('2/1/2012','DEF',500.00)
insert into test_table values ('2/1/2012','GHI',800.00)
insert into test_table values ('2/10/2012','DEF',700.00)
insert into test_table values ('3/1/2012','ABC',1100.00)
Query to generate the exact results which also replaces NULL with zeros:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat
--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
OUTPUT :
I use the below code in my apps. This shows exactly email client apps, such as Gmail.
Intent contactIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.email_to), null));
contactIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject));
startActivity(Intent.createChooser(contactIntent, getString(R.string.email_chooser)));
The show method does what you're looking for.
For example, given the following dataframe of 3 rows, I can print just the first two rows like this:
df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("baz", 3)], ('k', 'v'))
df.show(n=2)
which yields:
+---+---+
| k| v|
+---+---+
|foo| 1|
|bar| 2|
+---+---+
only showing top 2 rows
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
Here are 2 simple ways to calculate running total:
Approach 1: It can be written this way if your DBMS supports Analytical Functions
SELECT id
,somedate
,somevalue
,runningtotal = SUM(somevalue) OVER (ORDER BY somedate ASC)
FROM TestTable
Approach 2: You can make use of OUTER APPLY if your database version / DBMS itself does not support Analytical Functions
SELECT T.id
,T.somedate
,T.somevalue
,runningtotal = OA.runningtotal
FROM TestTable T
OUTER APPLY (
SELECT runningtotal = SUM(TI.somevalue)
FROM TestTable TI
WHERE TI.somedate <= S.somedate
) OA;
Note:- If you have to calculate the running total for different partitions separately, it can be done as posted here: Calculating Running totals across rows and grouping by ID
I know this is an old question, but beginners have been copypasting this around as if this was good practice in any code. Most of the time, having to parse a function's string representation to use its parameter names just hides a flaw in the code's logic.
Parameters of a function are actually stored in an array-like object called arguments
, where the first argument is arguments[0]
, the second is arguments[1]
and so on. Writing parameter names in the parentheses can be seen as a shorthand syntax. This:
function doSomething(foo, bar) {
console.log("does something");
}
...is the same as:
function doSomething() {
var foo = arguments[0];
var bar = arguments[1];
console.log("does something");
}
The variables themselves are stored in the function's scope, not as properties in an object. There is no way to retrieve the parameter name through code as it is merely a symbol representing the variable in human-language.
I always considered the string representation of a function as a tool for debugging purposes, especially because of this arguments
array-like object. You are not required to give names to the arguments in the first place. If you try parsing a stringified function, it doesn't actually tell you about extra unnamed parameters it might take.
Here's an even worse and more common situation. If a function has more than 3 or 4 arguments, it might be logical to pass it an object instead, which is easier to work with.
function saySomething(obj) {
if(obj.message) console.log((obj.sender || "Anon") + ": " + obj.message);
}
saySomething({sender: "user123", message: "Hello world"});
In this case, the function itself will be able to read through the object it receives and look for its properties and get both their names and values, but trying to parse the string representation of the function would only give you "obj" for parameters, which isn't useful at all.
I notice others have given the non-lambda syntax so just to have this complete I'll put in the lambda syntax equivalent:
Non-lambda (as per James's post):
var name = from i in DataContext.MyTable
where i.ID == 0
select i.Name
Equivalent lambda syntax:
var name = DataContext.MyTable.Where(i => i.ID == 0)
.Select(i => new { Name = i.Name });
There's not really much practical difference, just personal opinion on which you prefer.
the height of the status bar is 24dp in android 6.0
<!-- Height of the status bar -->
<dimen name="status_bar_height">24dp</dimen>
<!-- Height of the bottom navigation / system bar. -->
<dimen name="navigation_bar_height">48dp</dimen>
you can find the answer in the source code: frameworks\base\core\res\res\values\dimens.xml
This happens when a python extension (written in C) tries to access a memory beyond reach.
You can trace it in following ways.
sys.settrace
at the very first line of the code.Use gdb
as described by Mark in this answer.. At the command prompt
gdb python
(gdb) run /path/to/script.py
## wait for segfault ##
(gdb) backtrace
## stack trace of the c code
You can use regular expression like this.
/^[(]+\ ++\d{2}[)]+[^0]+\d{9}/
If you know that the switch statement will only ever have a strict defined set of labels or values, just do this to cover the bases, that way you will always get valid outcome.. Just put the default over the label that would programmatically/logically be the best handler for other values.
switch(ResponseValue)
{
default:
case No:
return false;
case Yes;
return true;
}
If you want to delete any commit then you might need to use git rebase command
git rebase -i HEAD~2
it will show you last 2 commit messages, if you delete the commit message and save that file deleted commit will automatically disappear...
You don't really need to install or use any third party tools.
The drivers located in ...\Android\Sdk\extras\google\usb_driver
work just fine.
Step 1: In Device Manager
, Right click on the malfunctioning Android ADB Interface
driver
Step 2: Select Update Driver Software
Step 3: Select Browse my computer for driver software
Step 4: Select Let me pick from a list of device drivers on my computer
Step 5: Select Have Disk
This window pops up:
Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver)
or browse to it.
Step 7: Click Ok
This window pops up:
Step 8: Select Android ADB Interface
and click Next
The window below pops up with a warning:
That's it. You driver installation will start and in a few seconds, you should be able to see your device
Briefly, Abstraction
happens at class level by hiding implementation and implementing an interface to be able to interact with the instance of the class. Whereas, Encapsulation
is used to hide information; for instance, making the member variables private to ban the direct access and providing getters and setters for them for indicrect access.
Another simple way would be:
Integer i = new Integer("10");
if (i != null)
int ip = Integer.parseInt(i.toString());
about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.
Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.
So i found the solution!
If you want something done right, do it yourself.
I present to you Shinobi! Shinobi : The Open Source CCTV Platform
sys.argv
represents the command line options you execute a script with.
sys.argv[0]
is the name of the script you are running. All additional options are contained in sys.argv[1:]
.
You are attempting to open a file that uses sys.argv[1]
(the first argument) as what looks to be the directory.
Try running something like this:
python ConcatenateFiles.py /tmp
As martijn-courteaux said, create a custom component it's the better option. In C# exists a component called PictureBox and I tried to create this component for Java, here is the code:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
public class JPictureBox extends JComponent {
private Icon icon = null;
private final Dimension dimension = new Dimension(100, 100);
private Image image = null;
private ImageIcon ii = null;
private SizeMode sizeMode = SizeMode.STRETCH;
private int newHeight, newWidth, originalHeight, originalWidth;
public JPictureBox() {
JPictureBox.this.setPreferredSize(dimension);
JPictureBox.this.setOpaque(false);
JPictureBox.this.setSizeMode(SizeMode.STRETCH);
}
@Override
public void paintComponent(Graphics g) {
if (ii != null) {
switch (getSizeMode()) {
case NORMAL:
g.drawImage(image, 0, 0, ii.getIconWidth(), ii.getIconHeight(), null);
break;
case ZOOM:
aspectRatio();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
break;
case STRETCH:
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
break;
case CENTER:
g.drawImage(image, (int) (this.getWidth() / 2) - (int) (ii.getIconWidth() / 2), (int) (this.getHeight() / 2) - (int) (ii.getIconHeight() / 2), ii.getIconWidth(), ii.getIconHeight(), null);
break;
default:
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
}
public Icon getIcon() {
return icon;
}
public void setIcon(Icon icon) {
this.icon = icon;
ii = (ImageIcon) icon;
image = ii.getImage();
originalHeight = ii.getIconHeight();
originalWidth = ii.getIconWidth();
}
public SizeMode getSizeMode() {
return sizeMode;
}
public void setSizeMode(SizeMode sizeMode) {
this.sizeMode = sizeMode;
}
public enum SizeMode {
NORMAL,
STRETCH,
CENTER,
ZOOM
}
private void aspectRatio() {
if (ii != null) {
newHeight = this.getHeight();
newWidth = (originalWidth * newHeight) / originalHeight;
}
}
}
If you want to add an image, choose the JPictureBox, after that go to Properties and find "icon" property and select an image. If you want to change the sizeMode property then choose the JPictureBox, after that go to Properties and find "sizeMode" property, you can choose some values:
If you want to learn more about this topic, you can check this video.
This work for me in bootstrap 4:
<div class="alert alert-info">
<a href="#" class="alert-link">Summary:Its some description.......testtesttest</a>
<button type="button" class="btn btn-primary btn-lg float-right">Large button</button>
</div>
Format price with grouping, rounding, and no unnecessary zeroes (in double).
Rules:
2.0000 = 2; 1.0100000 = 1.01
)2.010 = 2.01; 0.20 = 0.2
)1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0
)0
(null/-0 = 0
)$
(= $56/-$56
)101101.02 = $101,101.02
)More examples:
-99.985 = -$99.99
10 = $10
10.00 = $10
20.01000089 = $20.01
It is written in Kotlin as a fun extension of Double (because it is used in Android), but it can be converted to Java easily, because Java classes were used.
/**
* 23.0 -> $23
*
* 23.1 -> $23.1
*
* 23.01 -> $23.01
*
* 23.99 -> $23.99
*
* 23.999 -> $24
*
* -0.0 -> $0
*
* -5.00 -> -$5
*
* -5.019 -> -$5.02
*/
fun Double?.formatUserAsSum(): String {
return when {
this == null || this == 0.0 -> "$0"
this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
}
}
How to use:
var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20
yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0
About DecimalFormat: https://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
So here is the scenario that I faced, and how I solved it.
[branch-a]
[Hundreds of commits] -> [R] -> [I]
here R
is the commit that I needed to be removed, and I
is a single commit that comes after R
I made a revert commit and squashed them together
git revert [commit id of R]
git rebase -i HEAD~3
During the interactive rebase squash the last 2 commits.
Just throwing in a simple two-line C# implementation using recursion, because all the answers here seem far more complicated than necessary.
/// <summary>
/// Gets the column letter(s) corresponding to the given column number.
/// </summary>
/// <param name="column">The one-based column index. Must be greater than zero.</param>
/// <returns>The desired column letter, or an empty string if the column number was invalid.</returns>
public static string GetColumnLetter(int column) {
if (column < 1) return String.Empty;
return GetColumnLetter((column - 1) / 26) + (char)('A' + (column - 1) % 26);
}
EDIT: The current best practices regarding Open Graph image sizes are officially outlined here: https://developers.facebook.com/docs/sharing/best-practices#images
There was a post in the Facebook developers group today, where one of the FB guys uploaded a PDF containing their new rules about image sizes – since that seems to be available only if you’re a member of the group, I uploaded it here: http://www.sendspace.com/file/ghqwhr
And they also said they will post about it in the developer blog in the coming days, so keep checking there as well
To summarize the linked document:
The main
function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).
The name main
is not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main
, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.
You can declare a function named main
as a member function or in a namespace, but such a function would not be the main
function that designates where the program starts.
The main
function cannot be declared as static
or inline
. It also cannot be overloaded; there can be only one function named main
in the global namespace.
The main
function cannot be used in your program: you are not allowed to call the main
function from anywhere in your code, nor are you allowed to take its address.
The return type of main
must be int
. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare main
with a return type of void
; this is probably the most frequently violated rule concerning the main
function).
There are two declarations of main
that must be allowed:
int main() // (1)
int main(int, char*[]) // (2)
In (1), there are no parameters.
In (2), there are two parameters and they are conventionally named argc
and argv
, respectively. argv
is a pointer to an array of C strings representing the arguments to the program. argc
is the number of arguments in the argv
array.
Usually, argv[0]
contains the name of the program, but this is not always the case. argv[argc]
is guaranteed to be a null pointer.
Note that since an array type argument (like char*[]
) is really just a pointer type argument in disguise, the following two are both valid ways to write (2) and they both mean exactly the same thing:
int main(int argc, char* argv[])
int main(int argc, char** argv)
Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.
main()
is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a return
statement in main()
: if you let main()
return without an explicit return
statement, it's the same as if you had written return 0;
. The following two main()
functions have the same behavior:
int main() { }
int main() { return 0; }
There are two macros, EXIT_SUCCESS
and EXIT_FAILURE
, defined in <cstdlib>
that can also be returned from main()
to indicate success and failure, respectively.
The value returned by main()
is passed to the exit()
function, which terminates the program.
Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main()
function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.
Gavin,
The issue you are having is a misunderstanding of positioning. If you want it to be "fixed" relative to the parent, then you really want your #fixed
to be position:absolute
which will update its position relative to the parent.
This question fully describes positioning types and how to use them effectively.
In summary, your CSS should be
#wrap{
position:relative;
}
#fixed{
position:absolute;
top:30px;
left:40px;
}
you can achive it with group join
var result = (from c in Customers
join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
Select new { customer = c, orderItems = g});
c is Customer and g is the customers order items.
Since the latest versions you can simply add a margin
to your slides:
.slick-slide {
margin: 0 20px;
}
There's no need for any kind of negative margins, since slick's calculation is based on the elements outerHeight
.
You can use bootstrap tooltip, and don't forget to set the html option to true.
<div id="tool"> tooltip</div>
$('#tool').tooltip({
title: 'line one' +'<br />'+ 'line two',
html: true
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.
This is the relevant part of the server code that helped:
if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "@$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
curl_exec($ch);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if ($info['http_code'] == 200)
$errmsg = "File uploaded successfully";
}
else
{
$errmsg = curl_error($ch);
}
curl_close($ch);
}
else
{
$errmsg = "Please select the file";
}
}
html form should look something like:
<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
<td>Upload</td>
<td align="center">:</td>
<td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
<td> </td>
<td align="center"> </td>
<td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>
I'm using tsql on a Linux/UNIX infrastructure to access MSSQL databases. Here's a simple shell script to dump a table to a file:
#!/usr/bin/ksh
#
#.....
(
tsql -S {database} -U {user} -P {password} <<EOF
select * from {table}
go
quit
EOF
) >{output_file.dump}
No there isn't. See https://jira.mongodb.org/browse/SERVER-701
Unfortunately, this is not an simple feature for us to implement due to the way that database metadata is stored in the original (default) storage engine. In MMAPv1 files, the namespace (e.g.: dbName.collection) that describes every single collection and index includes the database name, so to rename a set of database files, every single namespace string would have to be rewritten. This impacts:
- the .ns file
- every single numbered file for the collection
- the namespace for every index
- internal unique names of each collection and index
- contents of system.namespaces and system.indexes (or their equivalents in the future)
- other locations I may be missing
This is just to accomplish a rename of a single database in a standalone mongod instance. For replica sets the above would need to be done on every replica node, plus on each node every single oplog entry that refers this database would have to be somehow invalidated or rewritten, and then if it's a sharded cluster, one also needs to add these changes to every shard if the DB is sharded, plus the config servers have all the shard metadata in terms of namespaces with their full names.
There would be absolutely no way to do this on a live system.
To do it offline, it would require re-writing every single database file to accommodate the new name, and at that point it would be as slow as the current "copydb" command...
replace {userid} and {password} with your id and password in your organization or login to your machine.
npm config set proxy http://{userid}:{password}@proxyip:8080/
npm config set https-proxy http://{userid}:{password}@proxyip:8080/
npm config set http-proxy http://{userid}:{password}@proxyip:8080/
strict-ssl=false
This works for me
var dataTable = $('#HelpdeskOverview').dataTable();
var oSettings = dataTable.fnSettings();
dataTable.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
dataTable.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
dataTable.fnDraw();
If you don't have DBA rights then you can use user_segments table:
select bytes/1024/1024 MB from user_segments where segment_name='Table_name'
Suggested way is StopIteration. Please see Fibonacci example from tutorialspoint
#!usr/bin/python3
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
WHERE filters before data is grouped, and HAVING filters after data is grouped. This is an important distinction; rows that are eliminated by a WHERE clause will not be included in the group. This could change the calculated values which, in turn(=as a result) could affect which groups are filtered based on the use of those values in the HAVING clause.
And continues,
HAVING is so similar to WHERE that most DBMSs treat them as the same thing if no GROUP BY is specified. Nevertheless, you should make that distinction yourself. Use HAVING only in conjunction with GROUP BY clauses. Use WHERE for standard row-level filtering.
Excerpt From: Forta, Ben. “Sams Teach Yourself SQL in 10 Minutes (5th Edition) (Sams Teach Yourself...).”.
You may try it like this:
DECLARE @i int = 0
WHILE @i < 300
BEGIN
SET @i = @i + 1
/* your code*/
END
You can omit tel number for letting user just choose from contacts, but inserting your sms text in the body. Code is for Xamarin Android:
var uri = Uri.Parse("smsto:"); //append your number here for explicit nb
var intent = new Intent(Intent.ActionSendto, uri);
intent.PutExtra("sms_body", text);
Context.StartActivity(intent);
where
Context is Xamarin.Essentials.Platform.CurrentActivity ?? Application.Context
I was able to solve this issue by adding a file extension '.js'. I was using Intellij and created a js file, but it did not have the file extension. When I did a refractor rename and changed my component from 'List' to 'List.js' react native then knew how to resolve it.
Basically you are doing it the right way. However, you should use an instance of the DataContext
for querying (it's not obvious that DataContext
is an instance or the type name from your query):
var result = (from a in new DataContext().Persons
where a.Age > 18
select new Person { Name = a.Name, Age = a.Age }).ToList();
Apparently, the Person
class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:
class PersonInformation {
public string Name {get;set;}
public int Age {get;set;}
}
var result = (from a in new DataContext().Persons
where a.Age > 18
select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();
You can freely swap var
with List<PersonInformation>
here without affecting anything (as this is what the compiler does).
Otherwise, if you are working locally with the query, I suggest considering an anonymous type:
var result = (from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age }).ToList();
Note that in all of these cases, the result
is statically typed (it's type is known at compile time). The latter type is a List
of a compiler generated anonymous class similar to the PersonInformation
class I wrote above. As of C# 3.0, there's no dynamic typing in the language.
If you really want to return a List<Person>
(which might or might not be the best thing to do), you can do this:
var result = from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age };
List<Person> list = result.AsEnumerable()
.Select(o => new Person {
Name = o.Name,
Age = o.Age
}).ToList();
You can merge the above statements too, but I separated them for clarity.
import java.util.*;
class Charfrequency
{
public static void main(String a[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Your String :");
String s1=sc.nextLine();
int count,j=1;
char var='a';
char ch[]=s1.toCharArray();
while(j<=26)
{
count=0;
for(int i=0; i<s1.length(); i++)
{
if(ch[i]==var || ch[i]==var-32)
{
count++;
}
}
if(count>0){
System.out.println("Frequency of "+var+" is "+count);
}
var++;
j++;
}
}
}
If you get this error:
Cannot load 32-bit plugin, XMLTools.dll is not compatible with the current version of Notepad++
Here you can find a working version for Windows 10 x64: Xml Tools 2.4.9.2 Unicode
Note: It's the only version I've found working on Windows 10 Professional x64.
In addition to the answers above you can pass in command line parameters to the mysqld process for logging options instead of manually editing your conf file. For example, to enable general logging and specifiy a file:
mysqld --general-log --general-log-file=/var/log/mysql.general.log
Confirming other answers above, mysqld --help --verbose
gives you the values from the conf file (so running with command line options general-log is FALSE); whereas mysql -se "SHOW VARIABLES" | grep -e log_error -e general_log
gives:
general_log ON
general_log_file /var/log/mysql.general.log
Use slightly more compact syntax for the error log:
mysqld --general-log --general-log-file=/var/log/mysql.general.log --log-error=/var/log/mysql.error.log
I always have a primary key, even if in the beginning I don't have a purpose in mind yet for it. There have been a few times when I eventually need a PK in a table that doesn't have one and it's always more trouble to put it in later. I think there is more of an upside to always including one.
I had this same problem and stumbled upon the following simple solution. Just add a bit of padding to the image and it resizes itself to fit within the div.
<div class="col-sm-3">
<img src="xxx.png" class="img-responsive" style="padding-top: 5px">
</div>
If you are trying to simply return a string to a View, try this:
public string Test()
{
return "test";
}
This will return a view with the word test in it. You can insert some html in the string.
You can also try this:
public ActionResult Index()
{
return Content("<html><b>test</b></html>");
}
You need Ajax to make it happen. Something like this:
$(document).ready(function(){
$("#myform").on('submit', function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if(name=='' || email=='' || password=='' || contact=='')
{
alert("Please fill in all fields");
}
else
{
// Ajax code to submit form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
This code snippet returns all the numbers in a numpy array between two values:
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56] )
a[(a>6)*(a<10)]
It works as following: (a>6) returns a numpy array with True (1) and False (0), so does (a<10). By multiplying these two together you get an array with either a True, if both statements are True (because 1x1 = 1) or False (because 0x0 = 0 and 1x0 = 0).
The part a[...] returns all values of array a where the array between brackets returns a True statement.
Of course you can make this more complicated by saying for instance
...*(1-a<10)
which is similar to an "and Not" statement.
It's padding. From http://en.wikipedia.org/wiki/Base64:
In theory, the padding character is not needed for decoding, since the number of missing bytes can be calculated from the number of Base64 digits. In some implementations, the padding character is mandatory, while for others it is not used. One case in which padding characters are required is concatenating multiple Base64 encoded files.
Finally, this is what I did:
private File getFileFromURL() {
URL url = this.getClass().getClassLoader().getResource("/sql");
File file = null;
try {
file = new File(url.toURI());
} catch (URISyntaxException e) {
file = new File(url.getPath());
} finally {
return file;
}
}
...
File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();
Yes they do.
You shouldn't really be overriding the constructor anyway. You should have a newInstance()
static method defined and pass any parameters via arguments (bundle)
For example:
public static final MyFragment newInstance(int title, String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(2);
bdl.putInt(EXTRA_TITLE, title);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
And of course grabbing the args this way:
@Override
public void onCreate(Bundle savedInstanceState) {
title = getArguments().getInt(EXTRA_TITLE);
message = getArguments().getString(EXTRA_MESSAGE);
//...
//etc
//...
}
Then you would instantiate from your fragment manager like so:
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, MyFragment.newInstance(
R.string.alert_title,
"Oh no, an error occurred!")
)
.commit();
}
}
This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.
Reason - Extra reading
I thought I would explain why for people wondering why.
If you check: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java
You will see the instantiate(..)
method in the Fragment
class calls the newInstance
method:
public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
try {
Class<?> clazz = sClassMap.get(fname);
if (clazz == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = context.getClassLoader().loadClass(fname);
if (!Fragment.class.isAssignableFrom(clazz)) {
throw new InstantiationException("Trying to instantiate a class " + fname
+ " that is not a Fragment", new ClassCastException());
}
sClassMap.put(fname, clazz);
}
Fragment f = (Fragment) clazz.getConstructor().newInstance();
if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.setArguments(args);
}
return f;
} catch (ClassNotFoundException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (java.lang.InstantiationException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (IllegalAccessException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (NoSuchMethodException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": could not find Fragment constructor", e);
} catch (InvocationTargetException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": calling Fragment constructor caused an exception", e);
}
}
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() Explains why, upon instantiation it checks that the accessor is public
and that that class loader allows access to it.
It's a pretty nasty method all in all, but it allows the FragmentManger
to kill and recreate Fragments
with states. (The Android subsystem does similar things with Activities
).
Example Class
I get asked a lot about calling newInstance
. Do not confuse this with the class method. This whole class example should show the usage.
/**
* Created by chris on 21/11/2013
*/
public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener {
public static final StationInfoAccessibilityFragment newInstance(String crsCode) {
StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment();
final Bundle args = new Bundle(1);
args.putString(EXTRA_CRS_CODE, crsCode);
fragment.setArguments(args);
return fragment;
}
// Views
LinearLayout mLinearLayout;
/**
* Layout Inflater
*/
private LayoutInflater mInflater;
/**
* Station Crs Code
*/
private String mCrsCode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrsCode = getArguments().getString(EXTRA_CRS_CODE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mInflater = inflater;
return inflater.inflate(R.layout.fragment_station_accessibility, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLinearLayout = (LinearLayout)view.findViewBy(R.id.station_info_accessibility_linear);
//Do stuff
}
@Override
public void onResume() {
super.onResume();
getActivity().getSupportActionBar().setTitle(R.string.station_info_access_mobility_title);
}
// Other methods etc...
}
In Android Studio you don't need the plug in. On A Mac just open Android Studio -> click Android Studio in the top bar -> click Prefrences -> find File and Code Templates in the list -> select includes -> build it and will be persistent in all your project
return
returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:
lst = defineAList()
useTheList(lst)
Returning list
from inside defineAList
doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []
. Inside defineAList
, you create a new list and return it; this list has no relationship to the one you defined with list = []
at the beginning.
Incidentally, I changed your variable name from list
to lst
. It's not a good idea to use list
as a variable name because that is already the name of a built-in Python type. If you make your own variable called list
, you won't be able to access the builtin one anymore.
If you don't have to use any specific SVN and you are using GitHub you can use their SVN connector.
More information is here: Collaborating on GitHub with Subversion
Here's another code example for a single paged view. Implementation for viewControllerAtIndex is omitted here, it should return the correct view controller for the given index.
- (void)changePage:(UIPageViewControllerNavigationDirection)direction {
NSUInteger pageIndex = ((FooViewController *) [_pageViewController.viewControllers objectAtIndex:0]).pageIndex;
if (direction == UIPageViewControllerNavigationDirectionForward) {
pageIndex++;
}
else {
pageIndex--;
}
FooViewController *viewController = [self viewControllerAtIndex:pageIndex];
if (viewController == nil) {
return;
}
[_pageViewController setViewControllers:@[viewController]
direction:direction
animated:YES
completion:nil];
}
Pages can be changed by calling
[self changePage:UIPageViewControllerNavigationDirectionReverse];
[self changePage:UIPageViewControllerNavigationDirectionForward];
If you want to keep your GitHub forks up to date with the respective upstreams, there also exists this probot program for GitHub specifically: https://probot.github.io/apps/pull/ which does the job. You would need to allow installation in your account and it will keep your forks up to date.
let imageView = UIImageView(frame: (CGRect(x: 0, y: 0, width: 40, height:
40)))
imageView.contentMode = .scaleAspectFit
let image = UIImage (named: "logo") // logo is your NPG asset
imageView.image = image
self.navigationItem.titleView = imageView
Since this answer is tagged with r-faq, I felt it would be useful to share another alternative from base R: stack
.
Note, however, that stack
does not work with factor
s--it only works if is.vector
is TRUE
, and from the documentation for is.vector
, we find that:
is.vector
returnsTRUE
if x is a vector of the specified mode having no attributes other than names. It returnsFALSE
otherwise.
I'm using the sample data from @Jaap's answer, where the values in the year columns are factor
s.
Here's the stack
approach:
cbind(wide[1:2], stack(lapply(wide[-c(1, 2)], as.character)))
## Code Country values ind
## 1 AFG Afghanistan 20,249 1950
## 2 ALB Albania 8,097 1950
## 3 AFG Afghanistan 21,352 1951
## 4 ALB Albania 8,986 1951
## 5 AFG Afghanistan 22,532 1952
## 6 ALB Albania 10,058 1952
## 7 AFG Afghanistan 23,557 1953
## 8 ALB Albania 11,123 1953
## 9 AFG Afghanistan 24,555 1954
## 10 ALB Albania 12,246 1954
I had the same error. It turns out that the cause was that the back end method was expecting different json data. In my Ajax call i had something like this:
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"url":"test"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
Now in my WebMethod, inside my C# backend code i had declared my endpoint like this:
public static string PostAjax(AjaxSettings settings)
Where AjaxSettings was declared:
public class AjaxSettings
{
public string url { get; set; }
}
The problem then was that the mapping between my ajax call and my back-end endpoint was not the same. As soon as i changed my ajax call to the following, it all worked well!
var data ='{"url":"test"}';
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"settings":'+data+'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
I had to change the data variable inside the Ajax call in order to match the method signature exactly.
Private Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
String.prototype.interpole = function () {
var c=0, txt=this;
while (txt.search(/{var}/g) > 0){
txt = txt.replace(/{var}/, arguments[c]);
c++;
}
return txt;
}
Uso:
var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"
It's nice that Go has a Duration
type -- having explicitly defined units can prevent real-world problems.
And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.
/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
return time.Duration(factor) * d // method 1 -- multiply in 'Duration'
// return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}
The official documentation demonstrates using method #1:
To convert an integer number of units to a Duration, multiply:
seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s
. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).
By the way, the int64
representation of Duration
in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration
, like int64
, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292
, and that's exactly how it is implemented:
// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64
So, because we know that the underlying representation of Duration
is an int64
, performing the cast between int64
and Duration
is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.
If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.
You can always use Sharepoint Solution Generator to create a project and edit in VS2008.
You can find the Generator along with Sharepoint Developer tools.
This should work ...
var tst = "12345\n\n\r\n\r\r";
var res = tst.TrimEnd( '\r', '\n' );
Ask yourself the opposite question: How can I determine if two rectangles do not intersect at all? Obviously, a rectangle A completely to the left of rectangle B does not intersect. Also if A is completely to the right. And similarly if A is completely above B or completely below B. In any other case A and B intersect.
What follows may have bugs, but I am pretty confident about the algorithm:
struct Rectangle { int x; int y; int width; int height; };
bool is_left_of(Rectangle const & a, Rectangle const & b) {
if (a.x + a.width <= b.x) return true;
return false;
}
bool is_right_of(Rectangle const & a, Rectangle const & b) {
return is_left_of(b, a);
}
bool not_intersect( Rectangle const & a, Rectangle const & b) {
if (is_left_of(a, b)) return true;
if (is_right_of(a, b)) return true;
// Do the same for top/bottom...
}
bool intersect(Rectangle const & a, Rectangle const & b) {
return !not_intersect(a, b);
}
Above mentioned answers are correct but what if you are doing a heavy process after losing the focus from the relevant component. For that, I came with a solution with two flags where the focus out event process will only take place when losing the focus from relevant component only.
isFocusInsideComponent = false;
isComponentClicked = false;
@HostListener('click')
clickInside() {
this.isFocusInsideComponent = true;
this.isComponentClicked = true;
}
@HostListener('document:click')
clickout() {
if (!this.isFocusInsideComponent && this.isComponentClicked) {
// do the heavy process
this.isComponentClicked = false;
}
this.isFocusInsideComponent = false;
}
Hope this will help you. Correct me If have missed anything.
You are facing this problem because when you are posting your forms so after reloading your dropdown is unable to find data in viewbag. So make sure that code you are using in get method while retrieving your data from db or from static list, copy paste that code into post verb as well..
Happy Coding :)
you should install a x server such as XMing. and keep the x server is running. config your putty like this :Connection-Data-SSH-X11-Enable X11 forwarding should be checked. and X display location : localhost:0
you just need to use word boundary (\b
) instead of ^
and $
:
\bgarp\b
Use:
if (function_exists('curl_file_create')) { // php 5.5+
$cFile = curl_file_create($file_name_with_full_path);
} else { //
$cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
You can also refer:
http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/
Important hint for PHP 5.5+:
Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
Please use the following
ddlCity.Items.Clear();
HTML--
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css--
.active{
background:red;
}
button.btn:active{
background:red;
}
jQuery--
jQuery("#my_styles .btn").click(function(){
jQuery("#my_styles .btn").removeClass('active');
jQuery(this).toggleClass('active');
});
view the live demo on jsfiddle
If you don't know the number of columns ahead of time, add each column to a list and cbind
at the end.
List <- list()
for(i in 1:n)
{
normF <- #something
List[[i]] <- normF
}
Matrix = do.call(cbind, List)
You can also use border-style: double
with background-clip: padding-box
, without the use of any extra (pseudo-)elements. It's probably the most compact solution, but not as flexible as the others.
<div class="circle">Some text goes here...</div>
.circle{
width: 100px;
height: 100px;
padding: 50px;
border-radius: 200px;
border: double 15px rgba(255,255,255,0.7);
background: rgba(255,255,255,0.7);
background-clip: padding-box;
}
If you look closely you can see that the edge between the border and the background is not perfect. This seems to be an issue in current browsers. But it's not that noticeable when the border is small.
Without the main sentinel, the code would be executed even if the script were imported as a module.
Converting VARCHAR2 to CLOB
In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).
For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.
declare
v_small_clob clob := lpad('0', 1000, '0');
v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
v_varchar2 varchar2(32767);
begin
v_varchar2 := v_small_clob;
v_varchar2 := substr(v_large_clob, 1, 32767);
end;
LONG?
The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.
For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2
and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ...
next to the text but it does not display the contents.
C#?
I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.
Use a HashSet<T>
. For example:
var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
Console.WriteLine(s);
prints
A B D C
The library PCAmixdata has functon splitmix that splits quantitative(Numerical data) and qualitative (Categorical data) of a given dataframe "YourDataframe" as shown below:
install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset)
X2 <- split$X.quali (Gives categorical columns in the dataset)
I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:
import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk
class UI:
def __init__(self):
self.root = tk.Tk()
self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
self.button = tk.Button(text="Do Task", command=self.do_task).pack()
def do_task(self):
rx.empty().subscribe(
on_completed=self.long_running_task,
scheduler=self.pool_scheduler
)
def long_running_task(self):
# your long running task here... eg:
time.sleep(3)
# if you want a callback on the main thread:
self.root.after(5, self.on_task_complete)
def on_task_complete(self):
pass # runs on main thread
if __name__ == "__main__":
ui = UI()
ui.root.mainloop()
Another way to use this construct which might be cleaner (depending on preference):
tk.Button(text="Do Task", command=self.button_clicked).pack()
...
def button_clicked(self):
def do_task(_):
time.sleep(3) # runs on background thread
def on_task_done():
pass # runs on main thread
rx.just(1).subscribe(
on_next=do_task,
on_completed=lambda: self.root.after(5, on_task_done),
scheduler=self.pool_scheduler
)
In Swift 3.0
Type 1: Convert NSString to String
let stringNumb:NSString = "1357"
let someNumb = Int(stringNumb as String) // 1357 as integer
Type 2: If the String has Integer only
let stringNumb = "1357"
let someNumb = Int(stringNumb) // 1357 as integer
Type 3: If the String has Float value
let stringNumb = "13.57"
if let stringToFloat = Float(stringNumb){
let someNumb = Int(stringToFloat)// 13 as Integer
}else{
//do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"
}
I had this error coming up between 2 Linux boxes. Easily solved by installing RSYNC on the remote box as well as the local one.
if you are using a variable name in the shell command, you must concatenate it with +
sign.
for example :
if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y
then ('shell command within quotes' + x > + y)
it will work this way especially if you are using this inside a python program with os.system command probably
Building on Kilhoffer's solution...
With C# 3.0 you can create an extension method as follows:
public static class ExtensionMethods
{
// Deep clone
public static T DeepClone<T>(this T a)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, a);
stream.Position = 0;
return (T) formatter.Deserialize(stream);
}
}
}
which extends any class that's been marked as [Serializable] with a DeepClone method
MyClass copy = obj.DeepClone();
You can also use a text editor:
If you hate numpy, get out RPy and your local copy of R, and use it instead.
(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)
if
takes a command and checks its return value. [
is just a command.
if grep -q ...
then
....
else
....
fi
Mat image1;
IplImage* image2=cvCloneImage(&(IplImage)image1);
Guess this will do the job.
Edit: If you face compilation errors, try this way:
cv::Mat image1;
IplImage* image2;
image2 = cvCreateImage(cvSize(image1.cols,image1.rows),8,3);
IplImage ipltemp=image1;
cvCopy(&ipltemp,image2);
What I did to add to get the files within a symlink into Git (I didn't use a symlink but):
sudo mount --bind SOURCEDIRECTORY TARGETDIRECTORY
Do this command in the Git-managed directory. TARGETDIRECTORY
has to be created before the SOURCEDIRECTORY
is mounted into it.
It works fine on Linux, but not on OS X! That trick helped me with Subversion too. I use it to include files from an Dropbox account, where a webdesigner does his/her stuff.
Containment :- Here to access inner object we have to use outer object. We can reuse the contained object. Aggregation :- Here we can access inner object again and again without using outer object.
Since version 4.14 of Linux kernel, vfs_read
and vfs_write
functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:
# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);
# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
loff_t *pos);
Also, filp_open
no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs
).
Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex
on the row container and at least making sure your middle container on the row has a flex-grow
value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow
properties applied, middle container only needs 1 for flex-grow
).
Here's a pic of what I was trying to do and sample code for how I solved it.
.row {
background: lightgray;
height: 30px;
width: 100%;
display: flex;
align-items:flex-end;
margin-top:5px;
}
.left {
background:lightblue;
}
.separator{
flex-grow:1;
border-bottom:dotted 2px black;
}
.right {
background:coral;
}
_x000D_
<div class="row">
<div class="left">Left</div>
<div class="separator"></div>
<div class="right">Right With Text</div>
</div>
<div class="row">
<div class="left">Left With More Text</div>
<div class="separator"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">Left With Text</div>
<div class="separator"></div>
<div class="right">Right With More Text</div>
</div>
_x000D_
Disabling and Enabling the Developer options and debug mode on the Android phone settings fixed the issue.
Short answer: no. (It is now possible with CSS transform. See the edit below)
Long answer: The problem with using "fixed" positioning is that it takes the element out of flow. thus it can't be re-positioned relative to its parent because it's as if it didn't have one. If, however, the container is of a fixed, known width, you can use something like:
#fixedContainer {
position: fixed;
width: 600px;
height: 200px;
left: 50%;
top: 0%;
margin-left: -300px; /*half the width*/
}
This is outdated information. It is now possible to center content of an dynamic size (horizontally and vertically) with the help of the magic of CSS3 transform. The same principle applies, but instead of using margin to offset your container, you can use translateX(-50%)
. This doesn't work with the above margin trick because you don't know how much to offset it unless the width is fixed and you can't use relative values (like 50%
) because it will be relative to the parent and not the element it's applied to. transform
behaves differently. Its values are relative to the element they are applied to. Thus, 50%
for transform
means half the width of the element, while 50%
for margin is half of the parent's width. This is an IE9+ solution
Using similar code to the above example, I recreated the same scenario using completely dynamic width and height:
.fixedContainer {
background-color:#ddd;
position: fixed;
padding: 2em;
left: 50%;
top: 0%;
transform: translateX(-50%);
}
If you want it to be centered, you can do that too:
.fixedContainer {
background-color:#ddd;
position: fixed;
padding: 2em;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
jsFiddle: Centered horizontally only
jsFiddle: Centered both horizontally and vertically
Original credit goes to user aaronk6 for pointing it out to me in this answer
This post helped me. Thanks a lot.
On Linux (Ubuntu 12.10) I needed to run
sudo apt-get install ruby
sudo apt-get install rubygems
sudo apt-get install ruby-dev
before I could succesfully run
sudo gem install jekyll
Try
expect(new ThrowableMessageMatcher(new StringContains(message)))
instead of
expectMessage(message)
You may write a custom ExpectedException
or utility method to wrap up the code.
Quicker - no. More effective - yes, if you will use the StringBuilder
class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.
If you expect this method to be actively called on multiple Strings
of significant length, it might be better to "migrate" its implementation onto the StringBuilder
class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.
public static class StringExtention
{
public static string clean(this string s)
{
StringBuilder sb = new StringBuilder (s);
sb.Replace("&", "and");
sb.Replace(",", "");
sb.Replace(" ", " ");
sb.Replace(" ", "-");
sb.Replace("'", "");
sb.Replace(".", "");
sb.Replace("eacute;", "é");
return sb.ToString().ToLower();
}
}
There's a difference between an empty string ""
and an undefined variable. You should be checking whether or not theHref contains a defined string, rather than its lenght:
if(theHref){
// ---
}
If you still want to check for the length, then do this:
if(theHref && theHref.length){
// ...
}
these are the commands:
git fetch origin
git merge origin/somebranch somebranch
if you do this on the second line:
git merge origin somebranch
it will try to merge the local master into your current branch.
The question, as I've understood it, was you fetched already locally and want to now merge your branch to the latest of the same branch.
You can try like this. It works for me
$("#MISSION_ID").select2();
On hide/show or ajax request, we have to reinitialize the select2 plugin
For example:
$("#offialNumberArea").show();
$("#eventNameArea").hide();
$('.selectCriteria').change(function(){
var thisVal = $(this).val();
if(thisVal == 'sailor'){
$("#offialNumberArea").show();
$("#eventNameArea").hide();
}
else
{
$("#offialNumberArea").hide();
$("#eventNameArea").show();
$("#MISSION_ID").select2();
}
});
In windows this scenario happens when Eclipse crashes without a clean shutdown it will have the local Jetty or Tomcat server keep running. When you reopen Eclipse and try to start server again this will lead to the "Address already in use: JVM_Bind"
You can solve this by opening Task Manager and find the javaw.exe process and ending it.
Then you can restart the server on Eclipse.
It should be like:
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
Explanation:
TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e, day*24. You now got remaining hours. Same for minute and second. You need to minus the already got hour and minutes respectively.
If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.
Rails 4
an alternative to @corban-brook 's 'Array gotcha: blank?' for checking if an arrays only holds empty values and can be regarded as blank? true:
[ nil, '' ].all? &:blank? == true
one could also do:
[nil, '', "", " ",' '].reject(&:blank?).blank? == true
Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.
location / {
root /path/to/root/of/static/files;
try_files $uri $uri/ @apachesite;
expires max;
access_log off;
}
location @apachesite {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files
. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.
I want to add something.
Actually, Task.Delay
is a timer based wait mechanism. If you look at the source you would find a reference to a Timer
class which is responsible for the delay. On the other hand Thread.Sleep
actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay()
if you want something(continuation) happen after some delay.
Use continue;
instead of break;
to enter the next iteration of the loop without executing any more of the contained code.
foreach (Item item in myItemsList)
{
if (item.Name == string.Empty)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
if (item.Weight > 100)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
}
Official docs are here, but they don't add very much color.
Actually, this is a duplicate of Encrypt Password in Configuration Files?.
The best solution I found so far is in this answert: https://stackoverflow.com/a/1133815/1549977
Pros: Password is saved a a char array, not as a string. It's still not good, but better than anything else.
here is the best way:
on this way you have only one css with all shared code and an html page. by the way (and i know that this is not the right topic) you can also encode your images in base64 (but you can also do it with your js and css files). in this way you reduce even more http requests to 1.
I had the same issue when "downgrading" a project from Java 8 to Java 6. The reason was that it was not changed at all places in IntelliJ.
In IntelliJ 13.1.4 I had to change Java and SDK version on the following places not to get this error:
The last bullet was the one that was not updated in my case. Once I changed this, the error disappeared.
You can't run PHP
in an html page ending with .html
. Unless the page is actually PHP and the extension was changed with .htaccess
from .php
to .html
What you mean is:
index.html
<html>
...
<?php echo "Hello world";?> //This is impossible
index.php //The file extension can be changed using htaccess, ex: its type stays php but will be visible to visitors as index.html
<?php echo "Hello world";?>
How about the following one? Should allow you to use either raw_input or input in both Python2 and Python3 with the semantics of Python2's raw_input (aka the semantics of Python3's input)
# raw_input isn't defined in Python3.x, whereas input wasn't behaving like raw_input in Python 2.x
# this should make both input and raw_input work in Python 2.x/3.x like the raw_input from Python 2.x
try: input = raw_input
except NameError: raw_input = input
Here's an example:
char myChar = '|';
string myString = "||";
Chars are delimited by single quotes, and strings by double quotes.
The good news is C# switch statements work with strings!
switch (mytoken)
{
case "==":
//Something here.
break;
default:
//Handle when no token is found.
break;
}
Every instance of View calls getViewTreeObserver()
. Now when holding an instance of ViewTreeObserver
, you can add an OnScrollChangedListener()
to it using the method addOnScrollChangedListener()
.
You can see more information about this class here.
It lets you be aware of every scrolling event - but without the coordinates. You can get them by using getScrollY()
or getScrollX()
from within the listener though.
scrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int scrollY = rootScrollView.getScrollY(); // For ScrollView
int scrollX = rootScrollView.getScrollX(); // For HorizontalScrollView
// DO SOMETHING WITH THE SCROLL COORDINATES
}
});
public static void main(String[] args) {
char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
char[][] countArr = new char[array.length][2];
int lastIndex = 0;
for (char c : array) {
int foundIndex = -1;
for (int i = 0; i < lastIndex; i++) {
if (countArr[i][0] == c) {
foundIndex = i;
break;
}
}
if (foundIndex >= 0) {
int a = countArr[foundIndex][1];
countArr[foundIndex][1] = (char) ++a;
} else {
countArr[lastIndex][0] = c;
countArr[lastIndex][1] = '1';
lastIndex++;
}
}
for (int i = 0; i < lastIndex; i++) {
System.out.println(countArr[i][0] + " " + countArr[i][1]);
}
}
I had this error, I looked into a log file C:\...\mysql\data\VM-IIS-Server.err and found this
2016-06-07 17:56:07 160c InnoDB: Error: unable to create temporary file; errno: 2
2016-06-07 17:56:07 3392 [ERROR] Plugin 'InnoDB' init function returned error.
2016-06-07 17:56:07 3392 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2016-06-07 17:56:07 3392 [ERROR] Unknown/unsupported storage engine: InnoDB
2016-06-07 17:56:07 3392 [ERROR] Aborting
The first line says "unable to create temporary file", it sounds like "insufficient privileges", first I tried to give access to mysql folder for my current user - no effect, then after some wandering around I came up to control panel->Administration->Services->Right Clicked MysqlService->Properties->Log On, switched to "This account", entered my username/password, clicked OK, and it woked!
Pretty Diff tool was created with XML in mind. Just ensure you click the option for "markup".
You can close the current window just by using the following code:
Application.Current.Windows[0].Close();
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: It combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
WE can take each first four joins in Details :
We have two tables with the following values.
TableA
id firstName lastName
.......................................
1 arun prasanth
2 ann antony
3 sruthy abc
6 new abc
TableB
id2 age Place
................
1 24 kerala
2 24 usa
3 25 ekm
5 24 chennai
....................................................................
INNER JOIN
Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB
Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
INNER JOIN TableB
ON TableA.id = TableB.id2;
Result Will Be
firstName lastName age Place
..............................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
LEFT JOIN
Note : will give all selected rows in TableA, plus any common selected rows in TableB.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
LEFT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
RIGHT JOIN
Note : will give all selected rows in TableB, plus any common selected rows in TableA.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
RIGHT JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
NULL NULL 24 chennai
FULL JOIN
Note :It will return all selected values from both tables.
Syntax
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Apply it in our sample table :
SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
FROM TableA
FULL JOIN TableB
ON TableA.id = TableB.id2;
Result
firstName lastName age Place
...............................................................................
arun prasanth 24 kerala
ann antony 24 usa
sruthy abc 25 ekm
new abc NULL NULL
NULL NULL 24 chennai
Interesting Fact
For INNER joins the order doesn't matter
For (LEFT, RIGHT or FULL) OUTER joins,the order matter
Better to go check this Link it will give you interesting details about join order
You can tag your DOM element using #someTag
, then get it with @ViewChild('someTag')
.
See complete example:
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'app',
template: `
<div #myDiv>Some text</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.innerHTML);
}
}
console.log
will print Some text.
Setting the active menu, they have the many ways to do that. Now, I share you a way to set active menu by CSS.
<a href="index.php?id=home">Home</a>
<a href="index.php?id=news">News</a>
<a href="index.php?id=about">About</a>
Now, you only set $_request["id"] == "home"
thì echo "class='active'"
, then we can do same with others.
<a href="index.php?id=home" <?php if($_REQUEST["id"]=="home"){echo "class='active'";}?>>Home</a>
<a href="index.php?id=news" <?php if($_REQUEST["id"]=="news"){echo "class='active'";}?>>News</a>
<a href="index.php?id=about" <?php if($_REQUEST["id"]=="about"){echo "class='active'";}?>>About</a>
I think it is useful with you.
CSS isn't going to be able to call other elements like that, you'll need to use JavaScript to reach beyond a child or sibling selector.
You could try something like this:
<a>Some Link
<div><img src="/you/image" /></div>
</a>
then...
a>div { display: none; }
a:hover>div { display: block; }
If the registration
field is indeed of type TIMESTAMP
you should be able to just do:
$sql = "SELECT user.email,
info.name,
DATE(user.registration),
info.news
FROM user,
info
WHERE user.id = info.id ";
and the registration should be showing as yyyy-mm-dd
You can use boost like this:
std::sort(a.begin(), a.end(),
boost::bind(&std::pair<int, int>::second, _1) <
boost::bind(&std::pair<int, int>::second, _2));
I don't know a standard way to do this equally short and concise, but you can grab boost::bind
it's all consisting of headers.
newTitle
is a local variable where you create the fields. So when that functions ends, the variable newTitle
, does not exist anymore. (The JTextField that was referenced by newTitle
does still exist however.)
Thus, increase the scope of the variable, so that you can access it another method.
public SomeFrame extends JFrame {
JTextField myTitle;//can be used anywhere in this class
creationOfTheFields()
{
//other code
myTitle = new JTextField("spam");
myTitle.setBounds(80, 40, 225, 20);
options.add(myTitle);
//blabla other code
}
private void New_Name()
{
this.setTitle(myTitle.getText());
}
}
When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
. so easy way to do this job is replacing all the "\n" with "
". so the code should be
str_replace("\n","<br/>",$str);
after adding this code you wont have to use pre tag for all the output oparation.
Pass by const
reference, it's faster. If you need to store it, say in some container, the ref. count will be auto-magically incremented by the copy operation.
In Place of using this
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
You can also use
MsgBox(json.SelectToken("Venue.ID"))
In windows the difference is as below. MUTEX: process which successfully executes wait has to execute a signal and vice versa. BINARY SEMAPHORES: Different processes can execute wait or signal operation on a semaphore.
@Simple-Solution
I use a simple Python HTTP server. When in the directory of the Angular app in question (using a MBP with Mavericks 10.9 and Python 2.x) I simply run
python -m SimpleHTTPServer 8080
And that sets up the simple server on port 8080 letting you visit localhost:8080
on your browser to view the app in development.
Hope that helped!
This error arises when you don't use brackets with pop
operation. Write the code in this manner.
listb.pop(0)
This is a valid python expression.
You can also do this:
var x = new object[] {
new { firstName = "john", lastName = "walter" },
new { brand = "BMW" }
};
And if they are the same anonymous type (firstName and lastName), you won't need to cast as object
.
var y = new [] {
new { firstName = "john", lastName = "walter" },
new { firstName = "jill", lastName = "white" }
};
You want to init an array of ints in your constructor? Point it to a static array.
class C
{
public:
int *cArray;
};
C::C {
static int c_init[]{1,2,3};
cArray = c_init;
}
To summarize a bit from what people have been saying:
f=open('data.txt', 'w') # will make a new file or erase a file of that name if it is present
f=open('data.txt', 'r') # will open a file as read-only
f=open('data.txt', 'a') # will open a file for appending (appended data goes to the end of the file)
If you wish have something in place similar to a try/catch
with open('data.txt') as f:
for line in f:
print line
I think @movieyoda code is probably what you should use however
The answer from ast1 is very simple and useful. It works for me, thank you so much. I just want to poin it out here, so people who need this answer can find it easily. So, here is my code from registering local and remote (push) notification.
//1. In Appdelegate: didFinishLaunchingWithOptions add these line of codes
let mynotif = UNUserNotificationCenter.current()
mynotif.requestAuthorization(options: [.alert, .sound, .badge]) {(granted, error) in }//register and ask user's permission for local notification
//2. Add these functions at the bottom of your AppDelegate before the last "}"
func application(_ application: UIApplication, didRegister notificationSettings: UNNotificationSettings) {
application.registerForRemoteNotifications()//register for push notif after users granted their permission for showing notification
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device Token: \(tokenString)")//print device token in debugger console
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")//print error in debugger console
}
Since SHA-1 maps several byte sequences to one, you can't "decrypt" a hash, but in theory you can find collisions: strings that have the same hash.
It seems that breaking a single hash would cost about 2.7 million dollars worth of computer time currently, so your efforts are probably better spent somewhere else.
The advantage of a wordier approach comes when your code is inside a 300,000 line project.
Using the action, as you have, there is no way to tell me what bool, int, and Blah are. If your action passed an object that defined the parameters then ok.
Using an EventHandler that wanted an EventArgs and if you would complete your DiagnosticsArgs example with getters for the properties that commented their purpose then you application would be more understandable. Also, please comment or fully name the arguments in the DiagnosticsArgs constructor.
To add the ; secure
suffix to the Set-Cookie
http header I simply used the <httpCookies>
element in the web.config:
<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>
IMHO much more handy than writing code as in the article of Anubhav Goyal.
See: http://msdn.microsoft.com/en-us/library/ms228262(v=vs.100).aspx
Going to your config/database.php
and change the charset and collation from utf8mb4 to utf8
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
My problem solved using this method, good luck dude!
My issue was inside of my app.gradle. I ran into this issue when I moved
apply plugin: "com.android.application"
from the top line to below a line with
apply from:
I switched the plugin back to the top and violá
My exact error was
Could not find method android() for arguments [dotenv_wke4apph61tdae6bfodqe7sj$_run_closure1@5d9d91a5] on project ':app' of type org.gradle.api.Project.
The top of my app.gradle now looks like this
project.ext.envConfigFiles = [
debug: ".env",
release: ".env",
anothercustombuild: ".env",
]
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.android.application"
I believe you need to .f
file as a parameter, not as a command-single-string. same with the "--domain "+i
, which i would split in two elements of the list.
Assuming that:
FORTRAN
executable, ~/
is indeed the correct way for the FORTRAN
executableI would change this line:
subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])
to
subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])
If that doesn't work, you should do a os.path.exists()
for the .f
file, and check that you can launch the FORTRAN
executable without any path, and set the path or system path variable accordingly
[EDIT 6-Mar-2017]
As the exception, detailed in the original post, is a python exception from subprocess
; it is likely that the WinError 2
is because it cannot find FORTRAN
I highly suggest that you specify full path for your executable:
for i in input:
exe = r'c:\somedir\fortrandir\fortran.exe'
fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
subprocess.Popen([exe, fortran_script, "--domain", i])
if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:
for i in input:
exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[EDIT 7-Mar-2017]
The following line is incorrect:
exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'
I am not sure why you have ~/
as a prefix for every path, don't do that.
for i in input:
exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[2nd EDIT 7-Mar-2017]
I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:
subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)
You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess
command.
You can also use this trick: replace
$("#topbar").click(function(){
by
$(document).on("click", "#topbar", function(){
This will bind an event on a not loaded yet object... ;)
I solved this error with clearing cache and restarting chrome. Hope they will fix it in ver 40.
Not this exact problem, but this is the top result when googling for almost the exact same error:
If you see this problem calling a WCF Service hosted on the same machine, you may need to populate the BackConnectionHostNames
registry key
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
MSV1_0
, point to New, and then click Multi-String Value
.BackConnectionHostNames
, and then press ENTER.BackConnectionHostNames
, and then click Modify.
In the Value data box, type the CNAME or the DNS alias, that is used for the local shares on the computer, and then click OK.
See Calling WCF service hosted in IIS on the same machine as client throws authentication error for details.
Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:
Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable
Due to a class with an attribute IEnumerable<int>
eg:
[Serializable]
class MySessionData{
public int ID;
public IEnumerable<int> RelatedIDs; //This can be an issue
}
Originally the problem instance of MySessionData
was set from a non-serializable list:
MySessionData instance = new MySessionData(){
ID = 123,
RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};
The cause here is the concrete class that the Select<int>(...)
returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int>
to resolve it.
RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();
Difference is static variables are those variables: which allows a value to be retained from one call of the function to another. But in case of local variables the scope is till the block/ function lifetime.
For Example:
#include <stdio.h>
void func() {
static int x = 0; // x is initialized only once across three calls of func()
printf("%d\n", x); // outputs the value of x
x = x + 1;
}
int main(int argc, char * const argv[]) {
func(); // prints 0
func(); // prints 1
func(); // prints 2
return 0;
}
The first thing you should try is:
sudo pip uninstall pip
On many environments that doesn't work. So given the lack of info on that problem, I ended up removing pip manually from /usr/local/bin.
Just use window.open()
:
window.open('Prosjektplan.pdf')
Anyway, what guys are saying on comments is true. You better use <a target="_blank">
instead of click events.
jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.
Try grep -E for extended regular expression support
Also take a look at:
Java ships in 2 versions: JRE & SDK (used to be called JDK)
The JRE in addition to not containing the compiler, also doesn't contain all of the libraries available in the JDK (tools.jar is one of them)
When you download Java at: http://java.sun.com/javase/downloads/index.jsp, make sure to select the JDK version and install it. If you have both a JDK & JRE, make sure that ANT is using the JDK, you can check JAVA_HOME (environment variable), and on the commandline if you do "javac -version" you should get a version description.
In Visual Studio 2013 & 2015 :
Tools -> Options -> Text Editor -> All Languages -> check Line Numbers
Take a look at the Maven dependency plugin, specifically, the dependency:copy-dependencies goal. Take a look at the example under the heading The dependency:copy-dependencies mojo. Set the outputDirectory configuration property to ${basedir}/target/lib (I believe, you'll have to test).
Hope this helps.
Here's my solution (requires no jQuery... just JavaScript):
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx = initArgs.shift();
var tObj = initArgs.shift();
var args = initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 4)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
Put this in a script block at the end of <body>
and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).
Here, I'll even give you a test page (paste it into a file and try it):
<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx = initArgs.shift();
var tObj = initArgs.shift();
var args = initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 3)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
</script></body></html>
I've been using Bitvise SSH Server for a number of years. It is a wonderful product and it is easy to setup and maintain. It gives you great control over how users connect to the server with support for security groups.
You need to include inttypes.h
if you want all those nifty new format specifiers for the intN_t
types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d
or %u
in case the sizes are different to what you think.
It includes stdint.h
and extends it with quite a few other things, such as the macros that can be used for the printf/scanf
family of calls. This is covered in section 7.8 of the ISO C99 standard.
For example, the following program:
#include <stdio.h>
#include <inttypes.h>
int main (void) {
uint32_t a=1234;
uint16_t b=5678;
printf("%" PRIu32 "\n",a);
printf("%" PRIu16 "\n",b);
return 0;
}
outputs:
1234
5678
As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.
In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".
Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.
If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)
However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.
Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.
Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:
=VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)
Another simple way, using strchr() or strstr():
$str = '233718_This_is_a_string';
echo ltrim(strstr($str, '_'), '_'); // This_is_a_string
This also works with maven by defining the resources tag. You can name your src folder names whatever you like.
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/generated</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
The answer is no. Keep in mind that in both cases, mdDate.Kind = DateTimeKind.Unspecified
.
Therefore it may be better to do the following:
DateTime myDate = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
The myDate.Kind
property is readonly, so it cannot be changed after the constructor is called.
The else
case is unncecessary, when you create a string
object it is empty by default.
throw
will terminate the further execution & expose message string on catch the error.
try {
throw "I'm Evil"
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e); // I'm Evil
}
_x000D_
Console after throw will never be reached cause of termination.
throw new Error
exposes an error event with two params name & message. It also terminate further execution
try {
throw new Error("I'm Evil")
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e.name, e.message); // Error I'm Evil
}
_x000D_
And just for completeness, this works also, though is not technically the correct way to do it -
try {
throw Error("I'm Evil")
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e.name, e.message); // Error I'm Evil
}
console.log(typeof(new Error("hello"))) // object
console.log(typeof(Error)) // function
_x000D_
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
Someone linked me this: What is the best way to move an element that's on the top to the bottom in Responsive design.
The solution in that worked perfectly. Though it doesn’t support old IE, that doesn’t matter for me, since I’m using responsive design for mobile. And it works for most mobile browsers.
Basically, I had this:
@media (max-width: 30em) {
.container {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-orient: vertical;
-moz-box-orient: vertical;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
/* optional */
-webkit-box-align: start;
-moz-box-align: start;
-ms-flex-align: start;
-webkit-align-items: flex-start;
align-items: flex-start;
}
.container .first_div {
-webkit-box-ordinal-group: 2;
-moz-box-ordinal-group: 2;
-ms-flex-order: 2;
-webkit-order: 2;
order: 2;
}
.container .second_div {
-webkit-box-ordinal-group: 1;
-moz-box-ordinal-group: 1;
-ms-flex-order: 1;
-webkit-order: 1;
order: 1;
}
}
This worked better than floats for me, because I needed them stacked on top of each other and I had about five different divs that I had to swap around the position of.
Using newInstance
public static MyDialogFragment newInstance(int num) {
MyDialogFragment f = new MyDialogFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
And get the Args like this
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments().getInt("num");
...
}
See the full example here
http://developer.android.com/reference/android/app/DialogFragment.html