When working with 4 large Db2 tables I have not only found the limit but it caused me to look really bad to a boss who thought that I could append all four tables (each with over 900,000 rows) to one large table. the real life result was that regardless of how many times I tried the Table (which had exactly 34 columns - 30 text and 3 integer) would spit out some cryptic message "Cannot open database unrecognized format or the file may be corrupted". Bottom Line is Less than 1,500,000 records and just a bit more than 1,252,000 with 34 rows.
I have the same problem
Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine
I applied the answer by neo but it did not work until I change the provider to “Provider=Microsoft.ACE.OLEDB.12.0;” in connection string.
Hope this will help if some one face the same issue.
This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.
Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"
Dim rsTable As DAO.recordSet
Dim recordId as long
Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now() ' Store your data
rsTable .Update
recordSet.Close
LeCygne
Both are valid. It's your choice.
I prefer border:0
because it's shorter; I find that easier to read. You may find none
more legible. We live in a world of very capable CSS post-processors so I'd recommend you use whatever you prefer and then run it through a "compressor". There's no holy war worth fighting here but Webpack?LESS?PostCSS?PurgeCSS is a good 2020 stack.
That all said, if you're hand-writing all your production CSS, I maintain —despite the grumbling in the comments— it does not hurt to be bandwidth conscious. Using border:0
will save an infinitesimal amount of bandwidth on its own, but if you make every byte count, you will make your website faster.
The CSS2 specs are here. These are extended in CSS3 but not in any way relevant to this.
'border'
Value: [ <border-width> || <border-style> || <'border-top-color'> ] | inherit
Initial: see individual properties
Applies to: all elements
Inherited: no
Percentages: N/A
Media: visual
Computed value: see individual properties
You can use any combination of width, style and colour.
Here, 0
sets the width, none
the style. They have the same rendering result: nothing is shown.
I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.
png("figure_%d.png")
set.seed(2014)
library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100),
x = rnorm(500, mean = rep(1:5, 100)),
y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))
ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()
Here it is the first figure:
and the second figure:
As we can see the colors do not stay fixed, for example E switches from magenta to blu.
As suggested by malcook in his comment and by hadley in his comment the code which uses limits
works properly:
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +
geom_point() +
scale_colour_discrete(drop=TRUE,
limits = levels(dataset$fCategory))
gives the following figure, which is correct:
This is the output from sessionInfo()
:
R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] methods stats graphics grDevices utils datasets base
other attached packages:
[1] ggplot2_0.9.3.1
loaded via a namespace (and not attached):
[1] colorspace_1.2-4 dichromat_2.0-0 digest_0.6.4 grid_3.0.2
[5] gtable_0.1.2 labeling_0.2 MASS_7.3-29 munsell_0.4.2
[9] plyr_1.8 proto_0.3-10 RColorBrewer_1.0-5 reshape2_1.2.2
[13] scales_0.2.3 stringr_0.6.2
You're setting the global git options, but the local checkout possibly has overrides set. Try setting them again with git config --local <setting> <value>
. You can look at the .git/config
file in your local checkout to see what local settings the checkout has defined.
Setting the image using picture.ImageLocation()
works fine, but you are using a relative path. Check your path against the location of the .exe
after it is built.
For example, if your .exe
is located at:
<project folder>/bin/Debug/app.exe
The image would have to be at:
<project folder>/bin/Image/1.jpg
Of course, you could just set the image at design-time (the Image
property on the PictureBox
property sheet).
If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image
. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory
to Copy if newer
.
At this point the image file will be copied when you build the application and you can use
picture.ImageLocation = @"Image\1.jpg";
This did the trick for me:Just remove all the libraries and then compile and run. It would prompt their are errors in your project confirm. Rerun the project after applying the libraries.
They display fine here. Are you using the 64-bit version of Windows 7 along with the 32-bit version of TortoiseSVN? If so, then they will only show up in the 32-bit Explorer (or in the CFDs of 32-bit applications). You can install both 32-bit and 64-bit versions side-by-side, though.
You set the size on initialization:
fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # in inches!
Edit:
If the problem is with x-axis ticks - You can set them "manually":
fig2.add_subplot(111).set_xticks(arange(1,3,0.5)) # You can actually compute the interval You need - and substitute here
And so on with other aspects of Your plot. You can configure it all. Here's an example:
from numpy import arange
import matplotlib
# import matplotlib as mpl
import matplotlib.pyplot
# import matplotlib.pyplot as plt
x1 = [1,2,3]
y1 = [4,5,6]
x2 = [1,2,3]
y2 = [5,5,5]
# initialization
fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # The size of the figure is specified as (width, height) in inches
# lines:
l1 = fig2.add_subplot(111).plot(x1,y1, label=r"Text $formula$", "r-", lw=2)
l2 = fig2.add_subplot(111).plot(x2,y2, label=r"$legend2$" ,"g--", lw=3)
fig2.add_subplot(111).legend((l1,l2), loc=0)
# axes:
fig2.add_subplot(111).grid(True)
fig2.add_subplot(111).set_xticks(arange(1,3,0.5))
fig2.add_subplot(111).axis(xmin=3, xmax=6) # there're also ymin, ymax
fig2.add_subplot(111).axis([0,4,3,6]) # all!
fig2.add_subplot(111).set_xlim([0,4])
fig2.add_subplot(111).set_ylim([3,6])
# labels:
fig2.add_subplot(111).set_xlabel(r"x $2^2$", fontsize=15, color = "r")
fig2.add_subplot(111).set_ylabel(r"y $2^2$")
fig2.add_subplot(111).set_title(r"title $6^4$")
fig2.add_subplot(111).text(2, 5.5, r"an equation: $E=mc^2$", fontsize=15, color = "y")
fig2.add_subplot(111).text(3, 2, unicode('f\374r', 'latin-1'))
# saving:
fig2.savefig("fig2.png")
So - what exactly do You want to be configured?
json.dumps()
is used to decode JSON dataimport json
# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
'int': int_data,
'str': str_data,
'float': float_data,
'list': list_data,
'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4)) # the json data will be indented
output:
String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
1,
1.5,
[
"normal string",
1,
1.5
]
]
Dictionary : {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
json.loads()
is used to convert JSON data into Python data.import json
# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'
# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)
print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])
print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])
output:
arrayJson to list_data :
[1, 1.5, ['normal string', 1, 1.5]]
Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]
objectJson to dictionary :
{'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}
Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
| JSON | Python |
|:-------------:|:------:|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
you can put div tags inside a td tag, but not directly inside a table or tr tag. examples:
this works:
<table>_x000D_
<tr>_x000D_
<td> _x000D_
<div>This will work.</div> _x000D_
</td>_x000D_
</tr>_x000D_
<table>
_x000D_
this does not work:
<table>_x000D_
<tr>_x000D_
<div> this does not work. </div> _x000D_
</tr>_x000D_
</table>
_x000D_
nor does this work:
<table>_x000D_
<div> this does not work. </div>_x000D_
</table>
_x000D_
For Symfony projects, be sure to check files in the project'es app/logs
More details available on this post :
How to debug 500 Error in Symfony 2
Btw, other frameworks or CMS share this kind of behaviour.
You can't get latitude/longitude from autocomplete API since the data generated by google from that API doesn't contain latitude and logitude field. Example:-
{
"predictions" : [
{
"description" : "IIT Mumbai, Mumbai, Maharashtra, India",
"id" : "ac3235cda973818a89b5fe21ad0f5261ac9b6723",
"matched_substrings" : [
{
"length" : 10,
"offset" : 0
}
],
"reference" : "CkQ0AAAAHWg-RSngiYHHdz_yqyFKmfSoBwT-_PW0k8qQDhsbiVrk7BlPHCyJb58OthledMUTGYS5Vhec1Zj2L7w9Rq0zDxIQrbn05RX1QgWHkSXsmTk1TRoU45APW2BBRIUsA3t6XBy_8s0BPPA",
"terms" : [
{
"offset" : 0,
"value" : "IIT Mumbai"
},
{
"offset" : 12,
"value" : "Mumbai"
},
{
"offset" : 20,
"value" : "Maharashtra"
},
{
"offset" : 33,
"value" : "India"
}
],
"types" : [ "establishment", "geocode" ]
}
],
"status" : "OK"
}
You can use the Google API to get the Longitude and Latitude from your address. As you already said, you should implement a hidden field where the result should be inserted. Then you can save the location together with the coordinates.
I recently implemented this function in one of my projects:
function getLatLngFromAddress(city, country){
var address = city +", "+ country;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#latitude').val(results[0].geometry.location.Pa);
$('#longitude').val(results[0].geometry.location.Qa);
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
as stated in the other comments, as php does not support overloading, usually the "type checking tricks" in constructor are avoided and the factory pattern is used intead
ie.
$myObj = MyClass::factory('fromInteger', $params);
$myObj = MyClass::factory('fromRow', $params);
Try using dynamic SQL:
create procedure sp_First @columnname varchar
AS
begin
declare @sql nvarchar(4000);
set @sql='select ['+@columnname+'] from Table_1';
exec sp_executesql @sql
end
go
exec sp_First 'sname'
go
This code help me in Attachment sending....
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);
Replace your AddAttachment(...) Code with above code
The React docs says:
Treat this.state as if it were immutable.
Your push
will mutate the state directly and that could potentially lead to error prone code, even if you are "resetting" the state again afterwards. F.ex, it could lead to that some lifecycle methods like componentDidUpdate
won’t trigger.
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
this.setState(prevState => ({
arrayvar: [...prevState.arrayvar, newelement]
}))
The memory "waste" is not an issue compared to the errors you might face using non-standard state modifications.
Alternative syntax for earlier React versions
You can use concat
to get a clean syntax since it returns a new array:
this.setState({
arrayvar: this.state.arrayvar.concat([newelement])
})
In ES6 you can use the Spread Operator:
this.setState({
arrayvar: [...this.state.arrayvar, newelement]
})
shared_ptr isn't large enough, nor do its constructor\destructor do enough work for there to be enough overhead from the copy to care about pass by reference vs pass by copy performance.
You have to mock the module and set the spy by yourself:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
doSomething: jest.fn()
}))
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
If you just have included a layout file at the beginning of onCreate()
inside setContentView
and want to get this layout to add new elements programmatically try this:
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
then you can create a new Button
for example and just add it:
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
There are cases where you don't want to use v-model
. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.
In these cases, it's not a good idea to use either watchers or computed properties.
Instead, take your v-model
and split it as above answer indicates
<input
:value="something"
@input="something = $event.target.value"
>
In practice, if you are decoupling your logic this way, you'll probably be calling a method.
This is what it would look like in a real world scenario:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
<input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
<p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
var app = new Vue({_x000D_
el: "#app",_x000D_
data: function(){_x000D_
return {_x000D_
extendedCost: 0,_x000D_
}_x000D_
},_x000D_
methods: {_x000D_
_onInputExtendedCost: function($event) {_x000D_
this.extendedCost = parseInt($event.target.value);_x000D_
// Go update other inputs here_x000D_
}_x000D_
}_x000D_
});_x000D_
</script>
_x000D_
I know this post is old, but I found that this really works well:
window.onunload = function() {
window.opener.location.href = window.opener.location.href;
};
The window.onunload
part was the hint I found googling this page. Thanks, @jerjer!
background: url(../images/backgroundImage.jpg) no-repeat center center fixed;
this should help
The original question on this post was: How to get Keras and Tensorflow to run with an AMD GPU.
The answer to this question is as followed:
1.) Keras will work if you can make Tensorflow work correctly (optionally within your virtual/conda environment).
2.) To get Tensorflow to work on an AMD GPU, as others have stated, one way this could work is to compile Tensorflow to use OpenCl. To do so read the link below. But for brevity I will summarize the required steps here:
You will need AMDs proprietary drivers. These are currently only available on Ubuntu 14.04 (the version before Ubuntu decided to change the way the UI is rendered). Support for Ubuntu 16.04 is at the writing of this post limited to a few GPUs through AMDProDrivers. Readers who want to do deep learning on AMD GPUs should be aware of this!
Compiling Tensorflow with OpenCl support also requires you to obtain and install the following prerequisites: OpenCl headers, ComputeCpp.
After the prerequisites are fulfilled, configure your build. Note that there are 3 options for compiling Tensorflow: Std Tensorflow (stable), Benoits Steiner's Tensorflow-opencl (developmental), and Luke Iwanski's Tensorflow-opencl (highly experimental) which you can pull from github. Also note that if you decide to build from any of the opencl versions, the question to use opencl will be missing because it is assumed that you are using it. Conversely, this means that if you configure from the standard tensorflow, you will need to select "Yes" when the configure script asks you to use opencl and "NO" for CUDA.
Then run tests like so:
$ bazel test --config=sycl -k --test_timeout 1600 -- //tensorflow/... -//tensorflow/contrib/... -//tensorflow/java/... -//tensorflow /compiler/...
Update: Doing this on my setup takes exceedingly long on my setup. The part that takes long are all the tests running. I am not sure what this means but a lot of my tests are timeing out at 1600 seconds. The duration can probably be shortened at the expense of more tests timeing out. Alternatively, you can just build tensor flow without tests. At the time of this writing, running the tests has taken 2 days already.
Or just build the pip package like so:
bazel build --local_resources 2048,.5,1.0 -c opt --config=sycl //tensorflow/tools/pip_package:build_pip_package
Please actually read the blog post over at Codeplay: Lukas Iwansky posted a comprehensive tutorial post on how to get Tensorflow to work with OpenCl just on March 30th 2017. So this is a very recent post. There are also some details which I did not write about here.
As indicated in the many posts above, little bits of information are spread throughout the interwebs. What Lukas' post adds in terms of value is that all the information was put together into one place which should make setting up Tensforflow and OpenCl a bit less daunting. I will only provide a link here:
https://www.codeplay.com/portal/03-30-17-setting-up-tensorflow-with-opencl-using-sycl
A slightly more complete walk-through has been posted here:
http://deep-beta.co.uk/setting-up-tensorflow-with-opencl-using-sycl/
It differs mainly by explicitly telling the user that he/she needs to:
Note an alternative approach was mentioned above using tensorflow-cl:
https://github.com/hughperkins/tensorflow-cl
I am unable to discern which approach is better at this time though it appears that this approach is less active. Fewer issues are posted, and fewer conversations to resolve those issues are happening. There was a major push last year. Additional pushes have ebbed off since November 2016 although Hugh seems to have pushed some updates a few days ago as of the writing of this post. (Update: If you read some of the documentation readme, this version of tensorflowo now only relies on community support as the main developer is busy with life.)
UPDATE (2017-04-25): I have some notes based on testing tensorflow-opencl below.
Following are some numbers for calculating 1 epoch using the CIFAR10 data set for MY SETUP (A10-7850 with iGPU). Your mileage will almost certainly vary!
You can see that in this particular case performance is worse. I attribute this to the following factors:
If you are using an AMD GPU with more VRAM and more stream processors, you are certain to get much better performance numbers. I would be interested to read what numbers people are achieving to know what's possible.
I will continue to maintain this answer if/when updates get pushed.
3.) An alternative way is currently being hinted at which is using AMD's RocM initiative, and miOpen (cuDNN equivalent) library. These are/will be open-source libraries that enable deep learning. The caveat is that RocM support currently only exists for Linux, and that miOpen has not been released to the wild yet, but Raja (AMD GPU head) has said in an AMA that using the above, it should be possible to do deep learning on AMD GPUs. In fact, support is planned for not only Tensorflow, but also Cafe2, Cafe, Torch7 and MxNet.
In Python, everything is passed by value, but if you want to modify some state, you can change the value of an integer inside a list or object that's passed to a method.
For the above code to function; you need to make sure the following directories exist (mine didn't). Just add the following to a bat and run it:
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Shutdown
It's just that GP needs those directories to exist for:
Group Policy\Local Computer Policy\Windows Settings\Scripts (Startup/Shutdown)
to function properly.
For me, the issue was that I mistakenly placed test cases in an internal class
[TestClass]
internal class TestLib {
}
That was causing test cases not being identified.
Hi we can use default method "first" in jQuery
Here some examples:
When you want to add class for first div
$('.alldivs div').first().addClass('active');
When you want to change the remove the "onediv" class and add only to first child
$('.alldivs div').removeClass('onediv').first().addClass('onediv');
This alternative approach uses SQL Server's OUTER APPLY
clause. This way, it
The OUTER APPLY
clause can be imagined as a LEFT JOIN
, but with the advantage that you can use values of the main query as parameters in the subquery (here: game).
SELECT colMinPointID
FROM (
SELECT game
FROM table
GROUP BY game
) As rstOuter
OUTER APPLY (
SELECT TOP 1 id As colMinPointID
FROM table As rstInner
WHERE rstInner.game = rstOuter.game
ORDER BY points
) AS rstMinPoints
Since this question has been reopened anyway, I might just as well propose an enum
solution.
enum ValidValues {
VAL1, VAL2, VAL3;
public static boolean isValid(String input) {
return Stream.of(ValidValues.values())
.map(ValidValues::name)
.anyMatch(s -> s.equalsIgnoreCase(input));
}
}
Or you can just use the stream statement with
Stream.of("val1", "val2", "val3")
.anyMatch(s -> s.equalsIgnoreCase(str))
if you only use it in one place.
The original frameset model (Frameset and Frame-elements) were very bad from a usability standpoint. IFrame vas a later invention which didn't have as many problems as the original frameset model, but it does have its drawback.
If you allow the user to navigate inside the IFrame, then links and bookmarks will not work as expected (because you bookmark the URL of the outer page, but not the URL of the iframe).
You can get rid of the first line. You don't need import java.lang.*;
Just change your 5th line to:
public static void main(String [] args) throws Exception
Since swift 3.0 there is more convenient way: #imageLiterals here is text example. And below animated example from here:
Sure there is. You can for example use the conditional expressions. For example:
<span th:text="${someObject.someProperty != null} ? ${someObject.someProperty} : 'null value!'">someValue</span>
You can even omit the "else" expression:
<span th:text="${someObject.someProperty != null} ? ${someObject.someProperty}">someValue</span>
You can also take a look at the Elvis operator to display default values.
Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.
See here for the groupid/artifactid.
Laravel 5 promotes the use of namespaces for things like Models and Controllers. Your Model is under the App
namespace, so your code needs to call it like this:
Route::get('/posts', function(){
$results = \App\Post::all();
return $results;
});
As mentioned in the comments you can also use
or import a namespace in to a file so you don't need to quote the full path, like this:
use App\Post;
Route::get('/posts', function(){
$results = Post::all();
return $results;
});
While I'm doing a short primer on namespaces I might as well mention the ability to alias a class as well. Doing this means you can essentially rename your class just in the scope of one file, like this:
use App\Post as PostModel;
Route::get('/posts', function(){
$results = PostModel::all();
return $results;
});
More info on importing and aliasing namespaces here: http://php.net/manual/en/language.namespaces.importing.php
or just (if you have LYNX):
lynx 'http://localhost/index.php?a=1&b=2&c=3'
In 2010 it is ctrl +k +d for indentation
Here is a simple helper method for starting a new activity as the new top activity which works from API level 4 up until the current version 17:
static void startNewMainActivity(Activity currentActivity, Class<? extends Activity> newTopActivityClass) {
Intent intent = new Intent(currentActivity, newTopActivityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
intent.addFlags(0x8000); // equal to Intent.FLAG_ACTIVITY_CLEAR_TASK which is only available from API level 11
currentActivity.startActivity(intent);
}
call it like this from your current activity:
startNewMainActivity(this, MainActivity.class);
for (Iterator<String> itr = someList.iterator(); itr.hasNext(); ) {
String item = itr.next();
System.out.println(item);
}
I found a solution while tinkering around.
People who directly wanna see the results:
With click: https://jsfiddle.net/dt52jazg/
With Hover: https://jsfiddle.net/7gkufLsh/1/
Below is the code:
HTML
<ul class="list">
<li>Hey</li>
<li>This</li>
<li>is</li>
<li>just</li>
<li>a</li>
<li>test</li>
</ul>
<button class="click-me">
Click me
</button>
CSS
.list li {
min-height: 0;
max-height: 0;
opacity: 0;
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.active li {
min-height: 20px;
opacity: 1;
}
JS
(function() {
$('.click-me').on('click', function() {
$('.list').toggleClass('active');
});
})();
Please let me know whether there is any problem with this solution 'coz I feel there would be no restriction of max-height with this solution.
this will subtract ten days of the current date (before Java 8):
int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();
If you're using Java 8 you can make use of the new Date & Time API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html):
LocalDate tenDaysAgo = LocalDate.now().minusDays(10);
For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date
inplace
, contrary to what the name implies, often does not prevent copies from being created, and (almost) never offers any performance benefitsinplace
does not work with method chaininginplace
can lead to SettingWithCopyWarning
if used on a DataFrame column, and may prevent the operation from going though, leading to hard-to-debug errors in codeThe pain points above are common pitfalls for beginners, so removing this option will simplify the API.
I don't advise setting this parameter as it serves little purpose. See this GitHub issue which proposes the inplace
argument be deprecated api-wide.
It is a common misconception that using inplace=True
will lead to more efficient or optimized code. In reality, there are absolutely no performance benefits to using inplace=True
. Both the in-place and out-of-place versions create a copy of the data anyway, with the in-place version automatically assigning the copy back.
inplace=True
is a common pitfall for beginners. For example, it can trigger the SettingWithCopyWarning
:
df = pd.DataFrame({'a': [3, 2, 1], 'b': ['x', 'y', 'z']})
df2 = df[df['a'] > 1]
df2['b'].replace({'x': 'abc'}, inplace=True)
# SettingWithCopyWarning:
# A value is trying to be set on a copy of a slice from a DataFrame
Calling a function on a DataFrame column with inplace=True
may or may not work. This is especially true when chained indexing is involved.
As if the problems described above aren't enough, inplace=True
also hinders method chaining. Contrast the working of
result = df.some_function1().reset_index().some_function2()
As opposed to
temp = df.some_function1()
temp.reset_index(inplace=True)
result = temp.some_function2()
The former lends itself to better code organization and readability.
Another supporting claim is that the API for set_axis
was recently changed such that inplace
default value was switched from True to False. See GH27600. Great job devs!
Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)
Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:
Range("B5") = "=SUM(B10:B100)"
or
X = "=SUM(B10:B100)
There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.
It will not matter if some cells are empty, it will simply see them as containing zeros!
This should do it for you!
Comparable defines a natural ordering. What this means is that you're defining it when one object should be considered "less than" or "greater than".
Suppose you have a bunch of integers and you want to sort them. That's pretty easy, just put them in a sorted collection, right?
TreeSet<Integer> m = new TreeSet<Integer>();
m.add(1);
m.add(3);
m.add(2);
for (Integer i : m)
... // values will be sorted
But now suppose I have some custom object, where sorting makes sense to me, but is undefined. Let's say, I have data representing districts by zipcode with population density, and I want to sort them by density:
public class District {
String zipcode;
Double populationDensity;
}
Now the easiest way to sort them is to define them with a natural ordering by implementing Comparable, which means there's a standard way these objects are defined to be ordered.:
public class District implements Comparable<District>{
String zipcode;
Double populationDensity;
public int compareTo(District other)
{
return populationDensity.compareTo(other.populationDensity);
}
}
Note that you can do the equivalent thing by defining a comparator. The difference is that the comparator defines the ordering logic outside the object. Maybe in a separate process I need to order the same objects by zipcode - in that case the ordering isn't necessarily a property of the object, or differs from the objects natural ordering. You could use an external comparator to define a custom ordering on integers, for example by sorting them by their alphabetical value.
Basically the ordering logic has to exist somewhere. That can be -
in the object itself, if it's naturally comparable (extends Comparable -e.g. integers)
supplied in an external comparator, as in the example above.
Just a thought but what if you worked this problem from the opposite direction? Rather than determining which browsers are mobile why not determine which browsers are not? Then code your site to default to the mobile version and redirect to the standard version. There are two basic possibilities when looking at a mobile browser. Either it has javascript support or it doesn't. So if the browser does not have javascript support it will default to the mobile version. If it does have JavaScript support, check the screen size. Anything below a certain size will likely also be a mobile browser. Anything larger will get redirected to your standard layout. Then all you need to do is determine if the user with JavaScript disabled is mobile or not.
According to the W3C the number of users with JavaScript disabled was about 5% and of those users most have turned it off which implies that they actually know what they are doing with a browser. Are they a large part of your audience? If not then don't worry about them. If so, whats the worst case scenario? You have those users browsing the mobile version of your site, and that's a good thing.
org.apache.http.impl.client.DefaultHttpClient
comes in the Android SDK by default. That'll get you connected to the WSDL.
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.example.com/" + URL);
HttpResponse response = httpClient.execute(httpGet, localContext);
Same problem here, for me solution was in editing server.js
file line 161
var server = app.listen(argv.port, '**<server.ip.adress.here>**', function() {
console.log('Cesium development server running publicly. Connect to localhost:%d/', server.address().port);
});
replace localhost>
with <server.ip.adress.here>
As previously answered here, since PHP 5.2.0 you can use the DateTime
class and specify the UTC timezone with an instance of DateTimeZone
.
The DateTime __construct() documentation suggests passing "now" as the first parameter when creating a DateTime instance and specifying a timezone to get the current time.
$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));
echo $date_utc->format(\DateTime::RFC850); # Saturday, 18-Apr-15 03:23:46 UTC
Bash has a feature called parameter expansion, which, among other things, allows string replacement based on so-called patterns (patterns resemble regular expressions, but there are fundamental differences and limitations). [flussence's original line: Bash has regular expressions, but they're well-hidden:]
The following demonstrates how to remove all white space (even from the interior) from a variable value.
$ var='abc def'
$ echo "$var"
abc def
# Note: flussence's original expression was "${var/ /}", which only replaced the *first* space char., wherever it appeared.
$ echo -n "${var//[[:space:]]/}"
abcdef
in laravel 5 first we need to create migration and then run the migration
Step 1.
php artisan make:migration create_users_table --create=users
Step 2.
php artisan migrate
const int* ptr;
is a pointer to constant (content). You are allowed to modify the pointer. e.g. ptr = NULL
, ptr++
, but modification of the content is not possible.
int * const ptr;
Is a constant pointer. The opposite is possible. You are not allowed to modify the pointer, but you are allowed to modify what it points to e.g. *ptr += 5
.
This suffices :
parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);
since if the refnode
(second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore
Actually I doubt that the || null
is required, try it and see.
The simple solution i found was to move the authorized_keys
file away from the hidden .ssh directory and put it in the system ssh directory:
/etc/ssh/keys/authorized_keys
As soon as I did this it worked with no problems.
Install Oracle's MySql.Data
NuGet package.
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Data
{
public class DBConnection
{
private DBConnection()
{
}
public string Server { get; set; }
public string DatabaseName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private MySqlConnection Connection { get; set;}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
public bool IsConnect()
{
if (Connection == null)
{
if (String.IsNullOrEmpty(databaseName))
return false;
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
Connection = new MySqlConnection(connstring);
Connection.Open();
}
return true;
}
public void Close()
{
Connection.Close();
}
}
}
Example:
var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}
You have to use show()
methode when you done all initialisations in your code in order to see the complet version of plot:
import matplotlib.pyplot as plt
plt.plot(x, y)
................
................
plot.show()
This worked better for me:
$.fn.textWidth = function(){
var html_org = $(this).html();
var html_calc = '<span>' + html_org + '</span>';
$(this).html(html_calc);
var width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
list(set(df[['Col1', 'Col2']].as_matrix().reshape((1,-1)).tolist()[0]))
The output will be ['Mary', 'Joe', 'Steve', 'Bob', 'Bill']
Try to use ScaleType centerInside.
ScaleTypes are not properly rendered in Eclipse Layout designer, so test in your running app.
<input inputmode='none'>
The
inputmode
global attribute is an enumerated attribute that hints at the type of data that might be entered by the user while editing the element or its contents. It can have the following values:
none
- No virtual keyboard. For when the page implements its own keyboard input control.
I am using this successfully (Tested on Chrome/Android)
CSS-Tricks: Everything You Ever Wanted to Know About inputmode
If you have an arraylist of String called 'foo', you can easily append (add) it to another ArrayList, 'list', using the following method:
ArrayList<String> list = new ArrayList<String>();
list.addAll(foo);
that way you don't even need to loop through anything.
For references you can call
rails generate migration AddUserIdColumnToTable user:references
If in the future you need to add a general index you can launch this
rails g migration AddOrdinationNumberToTable ordination_number:integer:index
Generate code:
class AddOrdinationNumberToTable < ActiveRecord::Migration
def change
add_column :tables, :ordination_number, :integer
add_index :tables, :ordination_number, unique: true
end
end
Solution #1: Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range
to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards")
prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn)
(e.g.) gives you a Range
, that would be ok, and that is why you often see Cells
used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet
. Thus, your code attempts using .Range(rng1, rng2)
, where .Range
is a method of one Worksheet
object and rng1
and rng2
are in a different Worksheet
.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards")
prior to executing your Sub
and it will start working (now you have well-formed references to Range
s). For the code you posted, adding .Activate
right after With...
would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range
in another Worksheet
.
With a sheet other than Worksheets("Cable Cards")
active, set a breakpoint at the line throwing the error, start your Sub
, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells
or Range
without a specified object (e.g., Worksheet
, or Range
) might be dangerous, especially when working with more than one Sheet
, unless one is quite sure about what Sheet
is active.
Object destructuring the parameter object is what many of the answers above are aiming for and Typescript now has the methods in place to make it much easier to read and intuitively understand.
Destructuring Basics: By destructuring an object, you can choose properties from an object by key name. You can define as few or as many of the properties you like, and default values are set by a basic syntax of let {key = default} = object
.
let {firstName, lastName = 'Smith'} = myParamsObject;
//Compiles to:
var firstName = myParamsObject.firstName,
_a = myParamsObject.lastName,
lastName = _a === void 0 ? 'Smith' : _a;
Writing an interface, type or class for the parameter object improves legibility.
type FullName = {_x000D_
firstName: string;_x000D_
_x000D_
/** @default 'Smith' */_x000D_
lastName ? : string;_x000D_
}_x000D_
_x000D_
function sayName(params: FullName) {_x000D_
_x000D_
// Set defaults for parameter object_x000D_
var { firstName, lastName = 'Smith'} = params;_x000D_
_x000D_
// Do Stuff_x000D_
var name = firstName + " " + lastName;_x000D_
alert(name);_x000D_
}_x000D_
_x000D_
// Use it_x000D_
sayName({_x000D_
firstName: 'Bob'_x000D_
});
_x000D_
You need to change parameter "a" => "a+". Follow this code bellows:
def storescores():
hs = open("hst.txt","a+")
If you know that you will only have that one querystring variable you can simply do:
var dest = location.search.replace(/^.*?\=/, '');
One thing PDO has that MySQLi doesn't that I really like is PDO's ability to return a result as an object of a specified class type (e.g. $pdo->fetchObject('MyClass')
). MySQLi's fetch_object()
will only return an stdClass
object.
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
Attempt http://challenge.greplin.com/ using Python
for those who are having trouble with similar problems in Numpy, a very simple solution would be:
defining dtype=object
when defining an array for assigning values to it. for instance:
out = np.empty_like(lil_img, dtype=object)
this is a generic method, you can use everywhere
const isBetween = (num1,num2,value) => value > num1 && value < num2
File uploads can not be done this way, no matter how you break it down. If you want to do an ajax/async upload, I would suggest looking into something like Uploadify, or Valums
Suggested method gave me error on Ubuntu 16.04: E: Unable to locate package mingw32
===========================================================================
To install this package on Ubuntu please use following:
sudo apt-get install mingw-w64
After install you can use it:
x86_64-w64-mingw32-g++
Please note!
For 64-bit use: x86_64-w64-mingw32-g++
For 32-bit use: i686-w64-mingw32-g++
This code works for me:
class ViewController: UIViewController {
var audioFilePathURL : NSURL!
var soundSystemServicesId : SystemSoundID = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
audioFilePathURL = NSBundle.mainBundle().URLForResource("MetalBell", withExtension: "wav")
AudioServicesCreateSystemSoundID( audioFilePathURL, &soundSystemServicesId)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func PlayAlertSound(sender: UIButton) {
AudioServicesPlayAlertSound(soundSystemServicesId)
}
}
The function call still should be a valid SQL statement:
SELECT "saveUser"(3, 'asd','asd','asd','asd','asd');
First I created each file: echo 'information' > file1.txt for each file[123].txt.
Then I printed each file to makes sure information was correct: tail file?.txt
Then I did this: tail file?.txt >> Mainfile.txt. This created the Mainfile.txt to store the information in each file into a main file.
cat Mainfile.txt confirmed it was okay.
==> file1.txt <== bluemoongoodbeer
==> file2.txt <== awesomepossum
==> file3.txt <== hownowbrowncow
Could use CASE WHEN
to leave those with no ';' alone.
SELECT
CASE WHEN CHARINDEX(';', MyText) > 0 THEN
LEFT(MyText, CHARINDEX(';', MyText)-1) ELSE
MyText END
FROM MyTable
You can refer to this blog for printing formatted coloured text on console
https://javaforqa.wordpress.com/java-print-coloured-table-on-console/
public class ColourConsoleDemo {
/**
*
* @param args
*
* "\033[0m BLACK" will colour the whole line
*
* "\033[37m WHITE\033[0m" will colour only WHITE.
* For colour while Opening --> "\033[37m" and closing --> "\033[0m"
*
*
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("\033[0m BLACK");
System.out.println("\033[31m RED");
System.out.println("\033[32m GREEN");
System.out.println("\033[33m YELLOW");
System.out.println("\033[34m BLUE");
System.out.println("\033[35m MAGENTA");
System.out.println("\033[36m CYAN");
System.out.println("\033[37m WHITE\033[0m");
//printing the results
String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.format("|---------Test Cases with Steps Summary -------------|%n");
System.out.format("+----------------------+---------+---------+---------+%n");
System.out.format("| Test Cases |Passed |Failed |Skipped |%n");
System.out.format("+----------------------+---------+---------+---------+%n");
String formattedMessage = "TEST_01".trim();
leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.print("\033[31m"); // Open print red
System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0);
System.out.print("\033[0m"); // Close print red
System.out.format("+----------------------+---------+---------+---------+%n");
}
Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like
Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.
Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.
Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.
HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.
If we go into more detail, then answer to this question go longer. We can understand more from following posts:
I have used following command to connect MySQL Server 8.0 in Windows command prompt.
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p my_db
Enter password: ****
or
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p my_db -h localhost
Enter password: ****
Here my_db is schema name.
None of the previously given examples were meeting my needs completely, so I wrote my own queue that allows following functionality: iteration, index access, indexOf, lastIndexOf, get first, get last, offer, remaining capacity, expand capacity, dequeue last, dequeue first, enqueue / add element, dequeue / remove element, subQueueCopy, subArrayCopy, toArray, snapshot, basics like size, remove or contains.
MainActivity.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button button1;
TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
textView1=(TextView)findViewById(R.id.textView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView1.setText("TextView displayed Successfully");
}
});
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
FROM
Here is an interesting library: https://github.com/Flipboard/FLAnimatedImage
I tested the demo example and it's working great. It's a child of UIImageView. So I think you can use it in your Storyboard directly as well.
Cheers
I just had the situation that I wanted this only for lines exceeding \linewidth
, that is: Squeezing long lines slightly.
Since it took me hours to figure this out, I would like to add it here.
I want to emphasize that scaling fonts in LaTeX is a deadly sin! In nearly every situation, there is a better way (e.g.
multline
of themathtools
package). So use it conscious.
In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.
\usepackage{environ} % provides \BODY
\usepackage{etoolbox} % provides \ifdimcomp
\usepackage{graphicx} % provides \resizebox
\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation
\RenewEnviron{equation}{
\settowidth{\myl}{$\BODY$} % calculate width and save as \myl
\origequation
\ifdimcomp{\the\linewidth}{>}{\the\myl}
{\ensuremath{\BODY}} % True
{\resizebox{\linewidth}{!}{\ensuremath{\BODY}}} % False
\origendequation
}
SELECT
u . *
FROM
room u
JOIN
facilities_r fu ON fu.id_uc = u.id_uc
AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc
You must use OR here, not AND.
Since id_fu cannot be equal to 4 and 3, both at once.
select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time
Output:
| TIME | COUNT |
-----------------
| 13:00 | 2 |
| 13:15 | 2 |
| 13:30 | 0 |
| 13:45 | 1 |
If you want to count all the activities in one query, you can do:
select time,
coalesce(count(case when activities = 1 then 1 end), 0) as count1,
coalesce(count(case when activities = 2 then 1 end), 0) as count2,
coalesce(count(case when activities = 3 then 1 end), 0) as count3,
coalesce(count(case when activities = 4 then 1 end), 0) as count4,
coalesce(count(case when activities = 5 then 1 end), 0) as count5
from MyTable
group by time
The advantage of this over grouping by activities, is that it will return a count of 0 even if there are no activites of that type for that time segment.
Of course, this will not return rows for time segments with no activities of any type. If you need that, you'll need to use a left join with table that lists all the possible time segments.
getExternalStoragePublicDirectory()
is deprecated.
To get the download folder from a Fragment
,
val downloadFolder = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
From an Activity
,
val downloadFolder = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
downloadFolder.listFiles()
will list the File
s.
downloadFolder?.path
will give you the String path of the download folder.
@interface MySingleton : NSObject
{
}
+ (MySingleton *)sharedSingleton;
@end
@implementation MySingleton
+ (MySingleton *)sharedSingleton
{
static MySingleton *sharedSingleton;
@synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[MySingleton alloc] init];
return sharedSingleton;
}
}
@end
import csv first and use csv.DictReader its easy to process...
Regarding the error itself, let
is used to declare local variables that exist in block scopes instead of function scopes. It's also more strict than var
, so you can't do stuff like this:
if (condition) {
let a = 1;
...
let a = 2;
}
Also note that case
clauses inside switch
blocks don't create their own block scopes, so you can't redeclare the same local variable across multiple case
s without using {}
to create a block each.
As for the import, you are probably getting this error because TypeScript doesn't recognize your files as actual modules, and seemingly model-level definitions end up being global definitions for it.
Try importing an external module the standard ES6 way, which contains no explicit assignment, and should make TypeScript recognize your files correctly as modules:
import * as co from "./co"
This will still result in a compile error if you have something named co
already, as expected. For example, this is going to be an error:
import * as co from "./co"; // Error: import definition conflicts with local definition
let co = 1;
If you are getting an error "cannot find module co"...
TypeScript is running full type-checking against modules, so if you don't have TS definitions for the module you are trying to import (e.g. because it's a JS module without definition files), you can declare your module in a .d.ts
definition file that doesn't contain module-level exports:
declare module "co" {
declare var co: any;
export = co;
}
If you are using Spring, you can force validation by annotating the class with @Validated
:
import org.springframework.validation.annotation.Validated;
More info available here: Javax validation @NotNull annotation usage
If you want to see whole history of a file with code changes :
svn log --diff [path_to_file] > log.txt
Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).
This is correct if you plan on using the string later as a query string:
> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'
If you don't want ASCII characters like /
, :
and ?
to be escaped, use encodeURI
instead:
> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
However, for other use-cases, you might need uri-js instead:
> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
Your question is similar to below:
What is the difference between application server and web server?
In Java: Web Container or Servlet Container or Servlet Engine : is used to manage the components like Servlets, JSP. It is a part of the web server.
Web Server or HTTP Server: A server which is capable of handling HTTP requests, sent by a client and respond back with a HTTP response.
Application Server or App Server: can handle all application operations between users and an organization's back end business applications or databases.It is frequently viewed as part of a three-tier application with: Presentation tier, logic tier,Data tier
What about a little trickery like NgModel does with NgForm? You have to register your parent as a provider, then load your parent in the constructor of the child.
That way, you don't have to put [sharedList]
on all your children.
// Parent.ts
export var parentProvider = {
provide: Parent,
useExisting: forwardRef(function () { return Parent; })
};
@Component({
moduleId: module.id,
selector: 'parent',
template: '<div><ng-content></ng-content></div>',
providers: [parentProvider]
})
export class Parent {
@Input()
public sharedList = [];
}
// Child.ts
@Component({
moduleId: module.id,
selector: 'child',
template: '<div>child</div>'
})
export class Child {
constructor(private parent: Parent) {
parent.sharedList.push('Me.');
}
}
Then your HTML
<parent [sharedList]="myArray">
<child></child>
<child></child>
</parent>
You can find more information on the subject in the Angular documentation: https://angular.io/guide/dependency-injection-in-action#find-a-parent-component-by-injection
I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0
I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps
I had this exact problem with HTML5s email input, using Alwin Keslers answer above I added the regex to the HTML5 email input so the user must have .something at the end.
<input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" />
If you need to handle error messages using jQuery.AJAX you will need to modify the xhr
function so the responseType
is not being modified when an error happens.
So you will have to modify the responseType
to "blob" only if it is a successful call:
$.ajax({
...
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
...
error: function(xhr, textStatus, errorThrown) {
// Here you are able now to access to the property "responseText"
// as you have the type set to "text" instead of "blob".
console.error(xhr.responseText);
},
success: function(data) {
console.log(data); // Here is "blob" type
}
});
If you debug and place a breakpoint at the point right after setting the xhr.responseType
to "blob" you can note that if you try to get the value for responseText
you will get the following message:
The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
I'm not quite sure what your problem is, but you need to specify the parameter name like so.
-(void) changeCellText:(NSIndexPath *) nowIndex{
UILabel *content = (UILabel *)[[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex] contentView] viewWithTag:contentTag];
content.text = [formatter stringFromDate:checkInDate.date];
}
public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
return file.Id;
}
Use a ArrayAdapter backed by an ArrayList. To change the data, just update the data in the list and call adapter.notifyDataSetChanged().
If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:
WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value¶m2=value");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
Replacing "username"
and "password"
with the correct values, of course.
You can use innerHTML
to just concat the extra field string;
document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'
However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.
I haven't looked at the API in years, but you could also use document.write
, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.
Try this:
string searchValue = textBox3.Text;
int rowIndex = -1;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["peseneli"].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells[0];
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
Use unshift
. It's like push
, except it adds elements to the beginning of the array instead of the end.
unshift
/push
- add an element to the beginning/end of an arrayshift
/pop
- remove and return the first/last element of an arrayA simple diagram...
unshift -> array <- push
shift <- array -> pop
and chart:
add remove start end
push X X
pop X X
unshift X X
shift X X
Check out the MDN Array documentation. Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called push_front
/pop_front
) elements, you should never have to implement these yourself.
As pointed out in the comments, if you want to avoid mutating your original array, you can use concat
, which concatenates two or more arrays together. You can use this to functionally push a single element onto the front or back of an existing array; to do so, you need to turn the new element into a single element array:
const array = [3, 2, 1]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
console.log(newArray);
_x000D_
concat
can also append items. The arguments to concat
can be of any type; they are implicitly wrapped in a single-element array, if they are not already an array:
const array = [3, 2, 1]
const newLastElement = 0
// Both of these lines are equivalent:
const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ]
const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ]
console.log(newArray1);
console.log(newArray2);
_x000D_
Laravel 5
The other answers are great for Laravel 4 but Laravel 5 is here! We now have the ability to generate all kinds of stuff by default. Run php artisan help
to view all artisan commands. Here are all of the make
commands:
make
make:command Create a new command class
make:console Create a new Artisan command
make:controller Create a new resource controller class
make:event Create a new event class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:provider Create a new service provider class
make:request Create a new form request class
Note: we no longer use item:make. Instead we now have make:item.
Run php artisan help make:item
to see what you can pass it. For instance php artisan help make:migration
shows that we need to pass it the migration name but we can also pass it --create=""
or --table=""
to specify the table name to create or modify respectively. Run php artisan make:migration create_articles_table --create="articles"
to generate the articles table. Moreover, generating models takes care of generating the migration for that model. Follow the naming conventions and it will be pluralized it for the migration.
I managed to get it working by following Option 2 on the Windows installation instructions on the following page: https://github.com/nodejs/node-gyp.
I had to close the current command line interface and reopen it after doing the installation on another one logged in as Administrator.
ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??
if i am then please try this,
import csv
with open(r"C:\\test.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
writer.writerow(["a","b"])
you have to set the delimiter = ","
The only way of having a variable which hasn't been assigned a value in C# is for it to be a local variable - in which case at compile-time you can tell that it isn't definitely assigned by trying to read from it :)
I suspect you really want Nullable<DateTime>
(or DateTime?
with the C# syntactic sugar) - make it null
to start with and then assign a normal DateTime
value (which will be converted appropriately). Then you can just compare with null
(or use the HasValue
property) to see whether a "real" value has been set.
The OO solution for this is to create a ratio class. It wouldn't take any extra code (would save some), would be significantly cleaner/clearer, and would give you some extra refactorings letting you clean up code outside this class as well.
Actually I think someone recommended returning a structure, which is close enough but hides the intent that this needs to be a fully thought-out class with constructor and a few methods, in fact, the "method" that you originally mentioned (as returning the pair) should most likely be a member of this class returning an instance of itself.
I know your example was just an "Example", but the fact is that unless your function is doing way more than any function should be doing, if you want it to return multiple values you are almost certainly missing an object.
Don't be afraid to create these tiny classes to do little pieces of work--that's the magic of OO--you end up breaking it down until every method is very small and simple and every class small and understandable.
Another thing that should have been an indicator that something was wrong: in OO you have essentially no data--OO isn't about passing around data, a class needs to manage and manipulate it's own data internally, any data passing (including accessors) is a sign that you may need to rethink something..
Other people have already answered you how to rollback, but you also asked how you could identify the version number of a migration.
rake db:migrate:status
gives a list of your migrations version, name and status (up or down)/db/migrate
Stopwatch is fine, but loop the work 10^6 times, then divide by 10^6. You'll get a lot more precision.
Good article here: Cross-domain communication with iframes
Also you can directly set document.domain the same in both frames (even
document.domain = document.domain;
code has sense because resets port to null), but this trick is not general-purpose.
you can use this command
mysql> UPDATE mysql.user SET Password=PASSWORD('Your new Password') WHERE User='root';
check the links http://www.kirupa.com/forum/showthread.php?279644-How-to-reset-password-in-WAMP-server http://www.phpmytutor.com/blogs/2012/08/27/change-mysql-root-password-in-wamp-server/
Find your config.inc.php file under the phpMyAdmin installation directory and update the line that looks like
this:
$cfg['Servers'][$i]['password'] = 'password';
... to this:
$cfg['Servers'][$i]['password'] = 'newpassword';
import withRouter
import { withRouter } from 'react-router-dom';
Export your component as:
export withRouter(nameofcomponent)
Example, on button click, call goBack
:
<button onClick={this.props.history.goBack}>Back</button>
Tested on react-router-dom
v4.3
-The tag is Empty and it contains Attribute only. -The tag does not have 'Closing' tag.
So,
<img src='stackoverflow.png'>
<img src='stackoverflow.png' />
both are correct in HTML5 also.
Well, file_exists
does not say if a file exists, it says if a path exists. ???????
So, to check if it is a file then you should use is_file
together with file_exists
to know if there is really a file behind the path, otherwise file_exists
will return true
for any existing path.
Here is the function i use :
function fileExists($filePath)
{
return is_file($filePath) && file_exists($filePath);
}
The new :is()
CSS pseudo-class can do it in one selector:
:is(h1, h2, h3, h4, h5, h6) {
color: red;
}
to create the profile1.psl file, type in the following command:
new-item $PROFILE.CurrentUserAllHosts -ItemType file -Force
to access the file, type in the next command:
ise $PROFILE.CurrentUserAllHosts
note if you haven't done this before, you will see that you will not be able to run the script because of your execution policy, which you need to change to Unrestricted from Restricted (default).
to do that close the script and then type this command:
Set-ExecutionPolicy -Scope CurrentUser
then:
RemoteSigned
then this command again:
ise $PROFILE.CurrentUserAllHosts
then finally type your aliases in the script, save it, and they should run every time you run powershell, even after restarting your computer.
If you want to allow the user to browse for a file, you need to have an input type="file"
The closest you could get to your requirement would be to place the input type="file"
on the page and hide it. Then, trigger the click event of the input when the button is clicked:
#myFileInput {
display:none;
}
<input type="file" id="myFileInput" />
<input type="button"
onclick="document.getElementById('myFileInput').click()"
value="Select a File" />
Here's a working fiddle.
Note: I would not recommend this approach. The input type="file"
is the mechanism that users are accustomed to using for uploading a file.
You can't create a method swap, so that after calling swap(x,y)
the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.
You can however write a method that swaps two items in an array or list if that's what you want.
¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.
You can do it with a dynamic query.
declare @cadena varchar(max) = ''
select @cadena = @cadena + 'exec spAPI ' + ltrim(id) + ';'
from sysobjects;
exec(@cadena);
I know this is an old thread, but if anyone is looking for an answer of why their procedures doesn't work in the workbench and think the only result is "Query canceled" or anything like that without clues:
the output with errors or problems is hiddenl. I do not know why, I do understand it's annoying, but it is there. just move your cursor above the line above the message, it will turn in an double arrow (up and down) you can then click and drag that line up, then you will see a console with the message you missed!
Changing 'java.library.path' variable at runtime is not enough because it is read only once by JVM. You have to reset it like:
System.setProperty("java.library.path", path);
//set sys_paths to null
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
Please, take a loot at: Changing Java Library Path at Runtime.
Try following
Folder structure
-application
--controller
---dashboards.php
--views
---layouts
----application.php
---dashboards
----index.php
Controller
class Dashboards extends CI_Controller
{
public function __construct()
{
parent::__construct();
$data = array();
$data['js'] = 'dashboards.js'
$data['css'] = 'dashbaord.css'
}
public function index()
{
$data = array();
$data['yield'] = 'dashboards/index';
$this->load->view('layouts/application', $data);
}
}
View
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Some Title</title>
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/app.css" />
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/<?php echo $css; ?>" />
</head>
<body>
<header></header>
<section id="container" role="main">
<?php $this->load->view($yield); ?>
</section>
<footer></footer>
<script src="<php echo base_url(); ?>assets/js/app.js"></script>
<script src="<php echo base_url(); ?>assets/js/<?php echo $js; ?>"></script>
</body>
</html>
When you need to load different js, css or whatever in the header or footer use the __construct
function to $this->load->vars
Kind of a rails like approach here
Here are the two main approaches. I prefer this one for its readability:
bar <- subset(foo, location == "there")
Note that you can string together many conditionals with &
and |
to create complex subsets.
The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there"
returns a vector of T
and F
values that is the same length as the rows of foo
. You can do this to return only rows where the condition returns true.
foo[foo$location == "there", ]
Use the pointtype
and pointsize
options, e.g.
plot "./points.dat" using 1:2 pt 7 ps 10
where pt 7
gives you a filled circle and ps 10
is the size.
See: Plotting data.
on my windows machine 8 machine running IIS 8 I can run the batch file just by putting the bats name and forgettig the path to it. Or by putting the bat in c:\windows\system32 don't ask me how it works but it does. LOL
$test=shell_exec("C:\windows\system32\cmd.exe /c $streamnumX.bat");
I once had an issue like this, when i downloadad a lib from Amazon (for Amazon webservices) and that jar file contained a log4j.properties and somehow that was used instead of my good old, self configed log4j. Worth a check.
Check this out : http://codepen.io/Rowno/pen/Afykb
.carousel-fade {
.carousel-inner {
.item {
opacity: 0;
transition-property: opacity;
}
.active {
opacity: 1;
}
.active.left,
.active.right {
left: 0;
opacity: 0;
z-index: 1;
}
.next.left,
.prev.right {
opacity: 1;
}
}
Works marvellously, I hope it works
you can clear SharedPreferences app-data with this
Editor editor =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
and for clearing app db, this answer is correct -> Clearing Application database
change it to 32-bit (true) it works
if you get this Length cannot be less than zero. Parameter name: length issue in iis server configuation do the simple thing change the connection string in web.config file like your sql server name and server name and restart iis then try to load the page it works
For MySQL Workbench 6.1: in the home window click on the server instance(connection)/ or create a new one. In the thus opened 'connection' tab click on 'server' -> 'data import'. The rest of the steps remain as in Vishy's answer.
Double click your button and use the following code :-
protected void button_click(object sender,EventArgs e)
{
int parsedValue;
if(int.TryParse(!txt.Text,out parsedValue))
{
Label.Text = "Please specify a number only !!"; //Will put a text in a label so make
//sure
//you have a label
}
else
{
// do what you want to
}
Following is the code to get the list of activities/applications installed on Android :
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);
You will get all the necessary data in the ResolveInfo
to start a application. You can check ResolveInfo
javadoc here.
Is your problem similar to this:
l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"
If so, you simply need to copy the objects when you store them:
import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"
The objects in question should implement a __copy__
method to copy objects. See the documentation for copy
. You may also be interested in copy.deepcopy
, which is there as well.
EDIT: Here's the problem:
arrayList = []
for x in allValues:
result = model(x)
arrayList.append(wM) # appends the wM object to the list
wM.reset() # clears the wM object
You need to append a copy:
import copy
arrayList = []
for x in allValues:
result = model(x)
arrayList.append(copy.copy(wM)) # appends a copy to the list
wM.reset() # clears the wM object
But I'm still confused as to where wM
is coming from. Won't you just be copying the same wM
object over and over, except clearing it after the first time so all the rest will be empty? Or does model()
modify the wM
(which sounds like a terrible design flaw to me)? And why are you throwing away result
?
Below applies to all tags with the following two classes
.abc.xyz {
width: 200px !important;
}
applies to div tags with the following two classes
div.abc.xyz {
width: 200px !important;
}
If you wanted to modify this using jQuery
$(document).ready(function() {
$("div.abc.xyz").width("200px");
});
edit (not by the author): There is a comprehensive list of IoC frameworks available at https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc:
Original answer follows.
I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI.
That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use Spring.Net and CastleWindsor a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using StructureMap for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day.
Update
I've been using Ninject on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a fantastic set of Ninject screencasts by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of StructureMap in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there.
Other IoC screencasts can also be found here on Dimecasts.
I use ES6
template literals. For example:
const error = this.state.valid ? '' : 'error'
const classes = `form-control round-lg ${error}`
And then just render it:
<input className={classes} />
One-liner version:
<input className={`form-control round-lg ${this.state.valid ? '' : 'error'}`} />
Breadth First Search is generally the best approach when the depth of the tree can vary, and you only need to search part of the tree for a solution. For example, finding the shortest path from a starting value to a final value is a good place to use BFS.
Depth First Search is commonly used when you need to search the entire tree. It's easier to implement (using recursion) than BFS, and requires less state: While BFS requires you store the entire 'frontier', DFS only requires you store the list of parent nodes of the current element.
The problem here are PHP namespaces. You need to learn how to use them. As your controller are in App\Http\Controllers
namespace, if you refer any other class, you need to add leading backslash (or proper namespace) or add use
statement at the beginning of file (before class definition).
So in your case you could use:
$headquote = \DB::table('quotation_texts')->find(176);
$headquote = \App\Quotation::find(176);
or add in your controller class use
statement so the beginning of your controller class could look like this:
<?php
namespace App\Http\Controllers;
use DB;
use App\Quotation;
For more information about namespaces you could look at How to use objects from other namespaces and how to import namespaces in PHP or namespaces in PHP manual
If you think the space before and after "=" is mandatory, try it as separate item in the list.
Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.
For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept
property to "application/json".
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
I know I'm late to the party, but you could try spacing the boxes with padding.
<div class="col-md-6 box">
<div class="inner">Hello</div>
</div>
<div class="col-md-6 box">
<div class="inner">Hello</div>
</div>
CSS:
.box {
padding: 0 5px 0 5px;
}
.box .inner {
background-color: #fff;
}
Have a go at it
Here this should help you
The below jsfiddle link will help you understand how to rotate a image.I used the same one to rotate the dial of a clock.
var rotation = function (){
$("#image").rotate({
angle:0,
animateTo:360,
callback: rotation,
easing: function (x,t,b,c,d){
return c*(t/d)+b;
}
});
}
rotation();
Where: • t: current time,
• b: begInnIng value,
• c: change In value,
• d: duration,
• x: unused
No easing (linear easing): function(x, t, b, c, d) { return b+(t/d)*c ; }
Simply use str_replace:
$text = str_replace(' ', '_', $text);
You would do this after your previous substr
and strtolower
calls, like so:
$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);
If you want to get fancy, though, you can do it in one line:
$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));
My answer is focused to a extended case derived from the one exposed at top.
Suppose you have group of elements from which you want to hide the child elements except first. As an example:
<html>
<div class='some-group'>
<div class='child child-0'>visible#1</div>
<div class='child child-1'>xx</div>
<div class='child child-2'>yy</div>
</div>
<div class='some-group'>
<div class='child child-0'>visible#2</div>
<div class='child child-1'>aa</div>
<div class='child child-2'>bb</div>
</div>
</html>
We want to hide all .child
elements on every group. So this will not help because will hide all .child
elements except visible#1
:
$('.child:not(:first)').hide();
The solution (in this extended case) will be:
$('.some-group').each(function(i,group){
$(group).find('.child:not(:first)').hide();
});
I had the same question for macOS.
But the root cause was not installing Six. My macOS shipped Python version 2.7 was being usurped by a Python2 version I inherited by installing a package via brew
.
I fixed my issue with: $ brew uninstall python@2
Some context on here: https://bugs.swift.org/browse/SR-1061
Though you certainly can build such a device out of existing sequence operators, I would in this case be inclined to write this one up as a custom sequence operator. Something like:
// Returns "other" if the list is empty.
// Returns "other" if the list is non-empty and there are two different elements.
// Returns the element of the list if it is non-empty and all elements are the same.
public static int Unanimous(this IEnumerable<int> sequence, int other)
{
int? first = null;
foreach(var item in sequence)
{
if (first == null)
first = item;
else if (first.Value != item)
return other;
}
return first ?? other;
}
That's pretty clear, short, covers all the cases, and does not unnecessarily create extra iterations of the sequence.
Making this into a generic method that works on IEnumerable<T>
is left as an exercise. :-)
A typical best practice is not using long/int/short directly. Instead, according to specification of compilers and OS, wrap them into a header file to ensure they hold exactly the amount of bits that you want. Then use int8/int16/int32 instead of long/int/short. For example, on 32bit Linux, you could define a header like this
typedef char int8;
typedef short int16;
typedef int int32;
typedef unsigned int uint32;
The pipe, |
, is a special-character in regex (meaning "or") and you'll have to escape it with a \
.
Using your current regex:
\|.*$
I've tried this in Notepad++, as you've mentioned, and it appears to work well.
You will get this error
ERROR 1410 (42000): You are not allowed to create a user with GRANT
If you are trying to run a GRANT
on a user that doesn't exist!
Therefore, first run this to make sure the user you use in your GRANT
matches exactly to what you have:
select User, Host from user;
In particular pay attention whether the user you created is at localhost
but the one you are trying to grant to is %
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
Video with fall back:
try {
video.srcObject = mediaSource;
} catch (error) {
video.src = URL.createObjectURL(mediaSource);
}
video.play();
From: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
Since HTTP Params class is immutable therefore you need to chain the set method:
const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");
That pretty works!!
I made some updates from @suneelsarraf's answer and I removed Convert.ChangeType()
because it keeps throwing Invalid Cast Exception
. Have a take a look!
#region *** Convert DT to List<Object> ***
private List<I> ConvertTo<I>(DataTable datatable) where I : class
{
List<I> lstRecord = new List<I>();
try
{
List<string> columnsNames = new List<string>();
foreach (DataColumn DataColumn in datatable.Columns)
columnsNames.Add(DataColumn.ColumnName);
lstRecord = datatable.AsEnumerable().ToList().ConvertAll<I>(row => GetObject<I>(row, columnsNames));
return lstRecord;
}
catch
{
return lstRecord;
}
}
private I GetObject<I>(DataRow row, List<string> columnsName) where I : class
{
I obj = (I)Activator.CreateInstance(typeof(I));
try
{
PropertyInfo[] Properties = typeof(I).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
string columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
object dbValue = row[columnname];
if (dbValue != DBNull.Value)
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
objProperty.SetValue(obj, Convert.ChangeType(dbValue, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
objProperty.SetValue(obj, Convert.ChangeType(dbValue, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
}
return obj;
}
catch(Exception ex)
{
return obj;
}
}
#endregion
And this is how you use in your code.
// Other Codes Here
var lstResult = ConvertTo<TEntity>(dataTableName); // Convert DT to List<TEntity>
Have Fun! Be Safe in 2020.
The line
arr[i] = temp;
is wrong. (On the first iteration of your loop it sets arr[i]
to an undefined value; further iterations set it to an incorrect value.) If you remove this line, your array should be reversed correctly.
After that, you should move the code which prints the reversed array into a new loop which iterates over the whole list. Your current code only prints the first count/2
elements.
int temp, i;
for (i = 0; i < count/2; ++i) {
temp = arr[count-i-1];
arr[count-i-1] = arr[i];
arr[i] = temp;
}
for (i = 0; i < count; ++i) {
cout << arr[i] << " ";
}
Suppose if I have GetAllEmployees.cshtml
<h2>GetAllEmployees</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
// do something ...
</thead>
<tbody>
// do something ...
</tbody>
</table>
//Added my custom scripts in the scripts sections
@section Scripts
{
<script src="~/js/customScripts.js"></script>
}
And another view "GetEmployeeDetails.cshtml" with no scripts
<h2>GetEmployeeByDetails</h2>
@Model.PageTitle
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
// do something ...
</thead>
<tbody>
// do something ...
</tbody>
</table>
And my layout page "_layout.cshtml"
@RenderSection("Scripts", required: true)
So, when I navigate to GetEmployeeDetails.cshtml. I get the error that there is no section scripts to be rendered in GetEmployeeDetails.cshtml.
If I change the flag in @RenderSection()
from required : true
to ``required : false`. It means render the scripts defined in the @section scripts of the views if present.Else, do nothing.
And the refined approach would be in _layout.cshtml
@if (IsSectionDefined("Scripts"))
{
@RenderSection("Scripts", required: true)
}
This issue vexed me for some time. I was using reactive forms and I fixed it using this method. PS. Using Angular 9 and Material 9.
In the "ngOnInit" lifecycle hook
1) Get the object you want to set as the default from your array or object literal
const countryDefault = this.countries.find(c => c.number === '826');
Here I am grabbing the United Kingdom object from my countries array.
2) Then set the formsbuilder object (the mat-select) with the default value.
this.addressForm.get('country').setValue(countryDefault.name);
3) Lastly...set the bound value property. In my case I want the name value.
<mat-select formControlName="country">
<mat-option *ngFor="let country of countries" [value]="country.name" >
{{country.name}}
</mat-option>
</mat-select>
Works like a charm. I hope it helps
Microsoft replace SWITCH, IFS and IFVALUES with CHOOSE only function.
=CHOOSE($L$1,"index_1","Index_2","Index_3")
I have come up with another solution with SingleTon class. Please tell me if any memory leakage is here.
import time,threading
class Singleton:
__instance = None
sleepTime = 1
executeThread = False
def __init__(self):
if Singleton.__instance != None:
raise Exception("This class is a singleton!")
else:
Singleton.__instance = self
@staticmethod
def getInstance():
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def startThread(self):
self.executeThread = True
self.threadNew = threading.Thread(target=self.foo_target)
self.threadNew.start()
print('doing other things...')
def stopThread(self):
print("Killing Thread ")
self.executeThread = False
self.threadNew.join()
print(self.threadNew)
def foo(self):
print("Hello in " + str(self.sleepTime) + " seconds")
def foo_target(self):
while self.executeThread:
self.foo()
print(self.threadNew)
time.sleep(self.sleepTime)
if not self.executeThread:
break
sClass = Singleton()
sClass.startThread()
time.sleep(5)
sClass.getInstance().stopThread()
sClass.getInstance().sleepTime = 2
sClass.startThread()
The solution is actually a lot easier than any of the other suggestions:
std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();
Best of all, it's platform independent.
You can try this from the console:
adb logcat --buffer=crash
More info on this option:
adb logcat --help
...
-b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',
'system', 'radio', 'events', 'crash', 'default' or 'all'.
Multiple -b parameters or comma separated list of buffers are
allowed. Buffers interleaved. Default -b main,system,crash.
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.
Add this to your gemfile:
gem 'cliver', :git => 'git://github.com/yaauie/cliver', :ref => '5617ce'
Have a look at this plunker
HTML:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="[email protected]" data-semver="1.3.0-beta.16" src="https://code.angularjs.org/1.3.0-beta.16/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="FollowsController">
<div class="row" ng:repeat="follower in myform.all_followers">
<ons-col class="views-row" size="50" ng-repeat="data in follower">
<img ng-src="http://dealsscanner.com/obaidtnc/plugmug/uploads/{{data.token}}/thumbnail/{{data.Path}}" alt="{{data.fname}}" ng-click="showDetail2(data.token)" />
<h3 class="title" ng-click="showDetail2('ss')">{{data.fname}}</h3>
</ons-col>
</div>
</body>
</html>
Javascript:
var app = angular.module('app', []);
//Follows Controller
app.controller('FollowsController', function($scope, $http) {
var ukey = window.localStorage.ukey;
//alert(dataFromServer);
$scope.showDetail = function(index) {
profileusertoken = index;
$scope.ons.navigator.pushPage('profile.html');
}
function showDetail2(index) {
alert("here");
}
$scope.showDetail2 = showDetail2;
$scope.myform ={};
$scope.myform.reports ="";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
var dataObject = "usertoken="+ukey;
//var responsePromise = $http.post("follows/", dataObject,{});
//responsePromise.success(function(dataFromServer, status, headers, config) {
$scope.myform.all_followers = [[{fname: "blah"}, {fname: "blah"}, {fname: "blah"}, {fname: "blah"}]];
});
On Ubuntu 14.04 I resolved this by using the pip installation bootstrap script, as described in the documentation
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
That's an OK solution for a development environment.
This way you always know what the size is, because a specific type is dedicated to sizes. The very own question shows that it can be an issue: is it an int
or an unsigned int
? Also, what is the magnitude (short
, int
, long
, etc.)?
Because there is a specific type assigned, you don't have to worry about the length or the signed-ness.
The actual definition can be found in the C++ Reference Library, which says:
Type:
size_t
(Unsigned integral type)Header:
<cstring>
size_t
corresponds to the integral data type returned by the language operatorsizeof
and is defined in the<cstring>
header file (among others) as an unsigned integral type.In
<cstring>
, it is used as the type of the parameternum
in the functionsmemchr
,memcmp
,memcpy
,memmove
,memset
,strncat
,strncmp
,strncpy
andstrxfrm
, which in all cases it is used to specify the maximum number of bytes or characters the function has to affect.It is also used as the return type for
strcspn
,strlen
,strspn
andstrxfrm
to return sizes and lengths.
With the reference of Biswajit Roy: Dynamic Programming firstly plans then Go. and Greedy algorithm uses greedy choice, it firstly Go then continuously Plans.
I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time
JAVASCRIPT
$(function () {
/* SET PARAMETERS */
var change_img_time = 5000;
var transition_speed = 100;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(transition_speed, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
setInterval(changeList, change_img_time);
});
.
HTML
<ul id="exampleSlider">
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
<li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>
.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO
.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX
Find if the given number is a power of 2.
#include <math.h>
int main(void)
{
int n,logval,powval;
printf("Enter a number to find whether it is s power of 2\n");
scanf("%d",&n);
logval=log(n)/log(2);
powval=pow(2,logval);
if(powval==n)
printf("The number is a power of 2");
else
printf("The number is not a power of 2");
getch();
return 0;
}
Perhaps you could try passing location into the component as a prop. Below I use ...otherProps. This is the spread operator, and is valid but unneccessary if you passed in your props explicitly it's just there as a place holder for demonstration purposes. Also, research destructuring to understand where ({ location }) came from.
import React from 'react';
import withRouter from 'react-router-dom';
const MyComponent = ({ location, ...otherProps }) => (whatever you want to render)
export withRouter(MyComponent);
Use nargs='?'
(or nargs='*'
if you need more than one dir)
parser.add_argument('dir', nargs='?', default=os.getcwd())
extended example:
>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]
positional arguments:
dir
optional arguments:
-h, --help show this help message and exit
-v
You're right that it involves a loop, but this is, at least, made simple by use of the each()
method:
$('.target').each(
function(){
// iterate through each of the `.target` elements, and do stuff in here
// `this` and `$(this)` refer to the current `.target` element
var images = $(this).find('img'),
imageWidth = images.width(); // returns the width of the _first_ image
numImages = images.length;
$(this).css('width', (imageWidth*numImages));
});
References:
I tried it by recursively appending each script
Note If your scripts are dependent one after other, then position will need to be in sync.
Major Dependency should be in last in array so that initial scripts can use it
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
_x000D_
const recursivelyAddScript = (script, cb) => {_x000D_
const el = document.createElement('script')_x000D_
el.src = script_x000D_
if(count < scripts.length) {_x000D_
count ++_x000D_
el.onload = recursivelyAddScript(scripts[count])_x000D_
document.body.appendChild(el)_x000D_
} else {_x000D_
console.log('All script loaded')_x000D_
return_x000D_
}_x000D_
}_x000D_
_x000D_
recursivelyAddScript(scripts[count])
_x000D_
As already mentioned by several people, eq
is the right operator here.
If you use warnings;
in your script, you'll get warnings about this (and many other useful things); I'd recommend use strict;
as well.
var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
$(this).find("td").each(function () {
values[count] = $(this).text();
count++;
});
});
Now values array contain all the cell values of that row can be used like values[0] first cell value of clicked row
*.dll files are archive files open with winzip/7zip etc. That isnt to say that all .dll files are archives you can save anything with the .dll extension however most windows .dll files are generated to be archives examples of this are windows>twain_32.dll which is an archive file however twain.dll is not if you look at twain.dll you will see an MZŽ as the first three notepad characters which denotes a Compiled C file/program or part of a program. Whereas MZ seems to be an archive.
Also most .exe files are archives mostly containing an icon image etc for the file and the windows installer packages as well they contain all the information the program needs to run images,movies etc and also directories including installation information and plain text file.
I have a game here game.exe and it contains java class files an image a pointer directing the .exe to run a .bat file. Obviously your .bat file will run a javac call from the archive and run the game there is also a few .dll archives containing java class files also.
[autorun]
ICON=AUTORUN\MINCRAFTLOGO.ICO
standard icon redirect here .ico is an image file within a .dll file within a .exe file. So the image seen on the .exe file is the minecraft logo. This is in a file called autorun.inf. Second example
[discstarter]
startpage=Autostart\Disk1.html
uselanguagestartpage=1
windowcaption=Solid Edge
licensee=Siemens PLM Software
productguid=05B227DF-DB00-4934-B3C8-40B7D8FAA54A
singleinstance=1
hidesplashscreen=1
noscrollbars=0
showstatusbar=1
splashscreentime=0
windowwidth=750
windowheight=775
buttondir=Autostart
toolbarcolor=16777215
toolbar=goback,goforward,gohome,print,exit
[autorun]
open=autostart.exe
icon=Autostart\ENGINE.ICO
This is the solid edge autorun.inf file contained in solidedge.exe Autostart\ is the Autostart.dll directory. open=autostart.exe specifies the autostart.exe file to run from within the original solidedge.exe archive. Here is a sample program using the .dll (dynamic link library) files http://www.flipcode.com/archives/Creating_And_Using_DLLs.shtml.
It also shows how they are created. As you can see the contents of the dll file is called by an exe file as I previously explained also there is a tutorial here http://msdn.microsoft.com/en-us/library/ms235636.aspx and as i said before 7zip or winzip will open a dynamic link library as an archive as long as you have the .dll file. If the contents of the dynamic link library have been compiled obviously you need a program which can read the file.
However since .dll files are by definition just archive library files the dll itself should be readable and not a compiled C,C# file etc etc Basically .dll files are archives well should be when a .dll file is created in visual studio the dll is created and any information you store in the dll file is encrypted. Mostly this encryption is handled by visual studio itself and generally isn't edited by hand. When you read a .dll file contents as a .exe the contents are automatically decrypted. Now when we talk about compiling a program we are changing the contents into bytecode the machine easily interprets.
This filesize would be smaller than the original file of the same contents. However the filesize is larger suggesting that the file has actually been encrypted. Probably to stop people reading their code. As a result the reading of .dll contents is termed decryption and not decompilation. Decompilation would convert the already compiled txt files to unreadable byte code. The use of standard .dll files is by definition not opensource because it involves the deliberate obfuscation of byte code.
A slightly hackier way (that is different than the answers above, which are all valid) would be to just direct the output into a file via console.
So imagine you had main.py
if True:
print "hello world"
else:
print "goodbye world"
You can do
python main.py >> text.log
and then text.log will get all of the output.
This is handy if you already have a bunch of print statements and don't want to individually change them to print to a specific file. Just do it at the upper level and direct all prints to a file (only drawback is that you can only print to a single destination).
Try this...
Calendar calendar = Calendar.getInstance();
String currentDate24Hrs = (String) DateFormat.format(
"MM/dd/yyyy kk:mm:ss", calendar.getTime());
Log.i("DEBUG_TAG", "24Hrs format date: " + currentDate24Hrs);
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
You can call max(vector, na.rm = TRUE)
. More generally, you can use the na.omit()
function.
As of Socket.IO 1.0 (May 2014), all connections begin with an HTTP polling request (more info here). That means that in addition to forwarding WebSocket traffic, you need to forward any transport=polling
HTTP requests.
The solution below should redirect all socket traffic correctly, without redirecting any other traffic.
Enable the following Apache2 mods:
sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
Use these settings in your *.conf file (e.g. /etc/apache2/sites-available/mysite.com.conf
). I've included comments to explain each piece:
<VirtualHost *:80>
ServerName www.mydomain.com
# Enable the rewrite engine
# Requires: sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
# In the rules/conds, [NC] means case-insensitve, [P] means proxy
RewriteEngine On
# socket.io 1.0+ starts all connections with an HTTP polling request
RewriteCond %{QUERY_STRING} transport=polling [NC]
RewriteRule /(.*) http://localhost:3001/$1 [P]
# When socket.io wants to initiate a WebSocket connection, it sends an
# "upgrade: websocket" request that should be transferred to ws://
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /(.*) ws://localhost:3001/$1 [P]
# OPTIONAL: Route all HTTP traffic at /node to port 3001
ProxyRequests Off
ProxyPass /node http://localhost:3001
ProxyPassReverse /node http://localhost:3001
</VirtualHost>
I've included an extra section for routing /node
traffic that I find handy, see here for more info.
On most devices, the other answers work. For me, to ensure it worked on every device (in react) I had to wrap it in an anchor tag <a>
and add the following:
:hover
, :focus
, :active
(in that order), as well as role="button"
and tabIndex="0"
.
I'd probably change your example to look like this:
<ul ng-repeat="task in tasks">
<li ng-mouseover="enableEdit(task)" ng-mouseleave="disableEdit(task)">{{task.name}}</li>
<span ng-show="task.editable"><a>Edit</a></span>
</ul>
//js
$scope.enableEdit = function(item){
item.editable = true;
};
$scope.disableEdit = function(item){
item.editable = false;
};
I know it's a subtle difference, but makes the domain a little less bound to UI actions. Mentally it makes it easier to think about an item being editable rather than having been moused over.
Example jsFiddle.
$result = mysql_query("SHOW TABLES FROM $dbname");
while($row = mysql_fetch_row($result))
{
$arr[] = $row[0];
}
if(in_array($table,$arr))
{
echo 'Table exists';
}
name=Ricardo
echo "Please enter your name: $name \c"
read newname
[ -n "$newname" ] && name=$newname
Set the default; print it; read a new value; if there is a new value, use it in place of the default. There is (or was) some variations between shells and systems on how to suppress a newline at the end of a prompt. The '\c' notation seems to work on MacOS X 10.6.3 with a 3.x bash, and works on most variants of Unix derived from System V, using Bourne or Korn shells.
Also note that the user would probably not realize what is going on behind the scenes; their new data would be entered after the name already on the screen. It might be better to format it:
echo "Please enter your name ($name): \c"
This is a rewrite of the great post by @Kay, which throws IOException and provides an early exit:
/**
* Gets image dimensions for given file
* @param imgFile image file
* @return dimensions of image
* @throws IOException if the file is not a known image
*/
public static Dimension getImageDimension(File imgFile) throws IOException {
int pos = imgFile.getName().lastIndexOf(".");
if (pos == -1)
throw new IOException("No extension for file: " + imgFile.getAbsolutePath());
String suffix = imgFile.getName().substring(pos + 1);
Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
while(iter.hasNext()) {
ImageReader reader = iter.next();
try {
ImageInputStream stream = new FileImageInputStream(imgFile);
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
return new Dimension(width, height);
} catch (IOException e) {
log.warn("Error reading: " + imgFile.getAbsolutePath(), e);
} finally {
reader.dispose();
}
}
throw new IOException("Not a known image file: " + imgFile.getAbsolutePath());
}
I guess my rep is not high enough for my input to be considered worthy as a reply.
Here is an example that should give you some idea..
=IIF(First(Fields!Gender.Value,"vw_BrgyClearanceNew")="Female" and
(First(Fields!CivilStatus.Value,"vw_BrgyClearanceNew")="Married"),false,true)
I think you have to identify the datasource name or the table name where your data is coming from.
Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.
Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is
float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);
This is pretty common use I suppose.
I think you're looking for something like freopen()
npm i -S lodash.uniqueid
Then in your code...
<script>
const uniqueId = require('lodash.uniqueid')
export default {
data () {
return {
id: ''
}
},
mounted () {
this.id = uniqueId()
}
}
</script>
This way you're not loading the entire lodash library, or even saving the entire library to node_modules
.
$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
foreach( $row as $key => $value )
{
if ( $value = BTABLE ) // BTABLE IS A DEFINED NAME OF TABLE
echo "exist";
else
echo "not exist";
}
}
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
If you add double paranthesis to the ngModel reference you get a two-way binding to your model property. That property can then be read and used in the event handler. In my view that is the most clean approach.
<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" />
try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables
Exact same thing, just omit the -c
option. Apache's docs on it here.
htpasswd /etc/apache2/.htpasswd newuser
Also, htpasswd
typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).
In my case, it was because we had an invalid ssl cert. The problem was on our staging box and we use our prod cert on that as well. It had worked for the past couple of years with this configuration, but all of a sudden we started getting this error. Strange.
If others are getting this error, check that the ssl certificate is valid. You can enable logging to s3 via the AWS CloudFront Distribution interface to aid debugging.
Also, you can refer to amazon's docs on the matter here: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html