If the error happens to be because your data has NAs, then you need to set the glm() function options of how you would like to treat the NA cases. More information on this is found in a relevant post here: https://stats.stackexchange.com/questions/46692/how-the-na-values-are-treated-in-glm-in-r
To print the names of all files in and below $dir of size 0:
find "$dir" -size 0
Note that not all implementations of find
will produce output by default, so you may need to do:
find "$dir" -size 0 -print
Two comments on the final loop in the question:
Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:
printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
test "$size" -eq 0 && echo "$path"; done
Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls
, and have a sane naming policy that doesn't allow whitespace in paths.
Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo
it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.
select top 0 *
into #mytemptable
from myrealtable
Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.
Try go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically.
PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for.[...]
See Cannot find or open the PDB file in Visual Studio C++ 2010
It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:
Bool DmgrGetVersion (String szVersion);
Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010
In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ here. As AnnotationMethodHandlerAdapter is deprecated and replaced by RequestMappingHandlerAdapter.
Little old post but I had the same problem
Using express 4.+ my code looks like this and it works great after two days of extensive testing.
var url = require('url'),
homePath = __dirname + '/../',
apiV1 = require(homePath + 'api/v1/start'),
bodyParser = require('body-parser').json({limit:'100mb'});
module.exports = function(app){
app.get('/', function (req, res) {
res.render( homePath + 'public/template/index');
});
app.get('/api/v1/', function (req, res) {
var query = url.parse(req.url).query;
if ( !query ) {
res.redirect('/');
}
apiV1( 'GET', query, function (response) {
res.json(response);
});
});
app.get('*', function (req,res) {
res.redirect('/');
});
app.post('/api/v1/', bodyParser, function (req, res) {
if ( !req.body ) {
res.json({
status: 'error',
response: 'No data to parse'
});
}
apiV1( 'POST', req.body, function (response) {
res.json(response);
});
});
};
Use this Command:
curl -s http://php-osx.liip.ch/install.sh | bash -s 7.0
You do not include a <scope>
tag in your dependency. If you add it, your dependency becomes something like:
<dependency>
<groupId>org.openrdf.sesame</groupId>
<artifactId>sesame-runtime</artifactId>
<version>2.7.2</version>
<scope> ... </scope>
</dependency>
The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.
In order to give a value in the table, we need to give a command:
php artisan make:migration create_users_table
and after then this command line
php artisan migrate
......
Joel's answer is good for reasons you might have to use C, though there are a few others:
In some cases, though, you might want to use C rather than C++:
You want the performance of assembler without the trouble of coding in assembler (C++ is, in theory, capable of 'perfect' performance, but the compilers aren't as good at seeing optimizations a good C programmer will see)
The software you're writing is trivial, or nearly so - whip out the tiny C compiler, write a few lines of code, compile and you're all set - no need to open a huge editor with helpers, no need to write practically empty and useless classes, deal with namespaces, etc. You can do nearly the same thing with a C++ compiler and simply use the C subset, but the C++ compiler is slower, even for tiny programs.
You need extreme performance or small code size and know the C++ compiler will actually make it harder to accomplish due to the size and performance of the libraries.
You contend that you could just use the C subset and compile with a C++ compiler, but you'll find that if you do that you'll get slightly different results depending on the compiler.
Regardless, if you're doing that, you're using C. Is your question really "Why don't C programmers use C++ compilers?" If it is, then you either don't understand the language differences, or you don't understand the compiler theory.
I've written an article which contains a proof of concept, support classes and a test class which demonstrates how Super Type Tokens can be retrieved by your classes at runtime. In a nutshell, it allows you to delegate to alternative implementations depending on actual generic parameters passed by the caller. Example:
TimeSeries<Double>
delegates to a private inner class which uses double[]
TimeSeries<OHLC>
delegates to a private inner class which uses ArrayList<OHLC>
See:
Thanks
Richard Gomes - Blog
For sanity, you probably want to have all datetimes
calculated by your DB server, rather than the application server. Calculating the timestamp in the application can lead to problems because network latency is variable, clients experience slightly different clock drift, and different programming languages occasionally calculate time slightly differently.
SQLAlchemy allows you to do this by passing func.now()
or func.current_timestamp()
(they are aliases of each other) which tells the DB to calculate the timestamp itself.
server_default
Additionally, for a default where you're already telling the DB to calculate the value, it's generally better to use server_default
instead of default
. This tells SQLAlchemy to pass the default value as part of the CREATE TABLE
statement.
For example, if you write an ad hoc script against this table, using server_default
means you won't need to worry about manually adding a timestamp call to your script--the database will set it automatically.
onupdate
/server_onupdate
SQLAlchemy also supports onupdate
so that anytime the row is updated it inserts a new timestamp. Again, best to tell the DB to calculate the timestamp itself:
from sqlalchemy.sql import func
time_created = Column(DateTime(timezone=True), server_default=func.now())
time_updated = Column(DateTime(timezone=True), onupdate=func.now())
There is a server_onupdate
parameter, but unlike server_default
, it doesn't actually set anything serverside. It just tells SQLalchemy that your database will change the column when an update happens (perhaps you created a trigger on the column ), so SQLAlchemy will ask for the return value so it can update the corresponding object.
You might be surprised to notice that if you make a bunch of changes within a single transaction, they all have the same timestamp. That's because the SQL standard specifies that CURRENT_TIMESTAMP
returns values based on the start of the transaction.
PostgreSQL provides the non-SQL-standard statement_timestamp()
and clock_timestamp()
which do change within a transaction. Docs here: https://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT
If you want to use UTC timestamps, a stub of implementation for func.utcnow()
is provided in SQLAlchemy documentation. You need to provide appropriate driver-specific functions on your own though.
Alternatively if one does not see "Untrust App Developer" dialog:
Go to your iPhone > Settings > General > Profile > "[email protected]" > Trust
You can use convert
from hablar
to change a column of the data frame quickly.
library(tidyverse)
library(hablar)
x <- tibble(var = c(1.34, 4.45, 6.98))
x %>%
convert(int(var))
gives you:
# A tibble: 3 x 1
var
<int>
1 1
2 4
3 6
I'm a little surprised nobody has suggested the most obvious solution:
grep -v '^#' filename
This solves the problem as stated.
But note that a common convention is for everything from a #
to the end of a line to be treated as a comment:
sed 's/#.*$//' filename
though that treats, for example, a #
character within a string literal as the beginning of a comment (which may or may not be relevant for your case) (and it leaves empty lines).
A line starting with arbitrary whitespace followed by #
might also be treated as a comment:
grep -v '^ *#' filename
if whitespace is only spaces, or
grep -v '^[ ]#' filename
where the two spaces are actually a space followed by a literal tab character (type "control-v tab").
For all these commands, omit the filename
argument to read from standard input (e.g., as part of a pipe).
You get an extension ID when you upload your extension to Google Web Store. Ie. Adblock has URL https://chrome.google.com/webstore/detail/cfhdojbkjhnklbpkdaibdccddilifddb
and the last part of this URL is its extension ID cfhdojbkjhnklbpkdaibdccddilifddb
.
If you wish to read installed extension IDs from your extension, check out the managment module. chrome.management.getAll
allows to fetch information about all installed extensions.
**There are numerous ways to change heap size like,
What worked for me was
Set proper appropriate JAVA_HOME path incase you java got updated.
create new system variable computer->properties->advanced setting->create new system variable
FYI: you can find default VMoption in Intellij help->edit custom VM option , In this file you see min and max size of heap.**
JavaScript is executed in the browser, which is pretty far removed from Eclipse. Eclipse would have to somehow hook into the browser's JavaScript engine to debug it. Therefore there's no built-in debugging of JavaScript via Eclipse, since JS isn't really its main focus anyways.
However, there are plug-ins which you can install to do JavaScript debugging. I believe the main one is the AJAX Toolkit Framework (ATF). It embeds a Mozilla browser in Eclipse in order to do its debugging, so it won't be able to handle cross-browser complications that typically arise when writing JavaScript, but it will certainly help.
Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,
input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}
Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.
You can use the "dir()" function to do this.
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>
Another useful feature is help.
>>> help(sys)
Help on built-in module sys:
NAME
sys
FILE
(built-in)
MODULE DOCS
http://www.python.org/doc/current/lib/module-sys.html
DESCRIPTION
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
Dynamic objects:
argv -- command line arguments; argv[0] is the script pathname if known
set<T> s;
//....
vector<T> v;
v.assign(s.begin(), s.end());
This will work intialize the spinner and findviewbyid and use this it will work
Spinner schemeStatusSpinner;
schemeStatusSpinner = (Spinner) dialog.findViewById(R.id.spinner);
schemeStatusSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
if(schemeStatusSpinner.getSelectedItemId()==4){
reasonll.setVisibility(View.VISIBLE);
}
else {
reasonll.setVisibility(View.GONE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
There is no way to do this with slf4j
.
I imagine that the reason that this functionality is missing is that it is next to impossible to construct a Level
type for slf4j
that can be efficiently mapped to the Level
(or equivalent) type used in all of the possible logging implementations behind the facade. Alternatively, the designers decided that your use-case is too unusual to justify the overheads of supporting it.
Concerning @ripper234's use-case (unit testing), I think the pragmatic solution is modify the unit test(s) to hard-wire knowledge of what logging system is behind the slf4j facade ... when running the unit tests.
If you don't want to show controls then try this code
<audio autoplay>
<source src="song.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
You can put the file "hibernate.cfg.xml" to the src folder (src\hibernate.cfg.xml) and then init the config as the code below:
Configuration configuration = new Configuration();
sessionFactory =configuration.configure().buildSessionFactory();
The problem is that the keys provided in the loop do not refer to the index of the file.
for (var i in this.files) {
console.log(i);
}
The output of the above code is:
0
length
item
But what was expected was:
0
1
2
etc...
Then the error occurs when the browser tries to execute, for example:
window.URL.createObjectURL(this.files["length"])
I suggest implementation based on the following code:
var files = this.files;
for (var i = 0; i < files.length; i++) {
var file = files[i],
src = (window.URL || window.webkitURL).createObjectURL(file);
...
}
I hope this can help someone.
Greetings!
If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:
opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;
You can also use:
my @files = glob( $dir . '/*' );
But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.
On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:
use File::Find;
my @content;
find( \&wanted, '/some/path');
do_something_with( @content );
exit;
sub wanted {
push @content, $File::Find::name;
return;
}
A missing intermediate certificate might be the problem.
You may want to check your https://hostname with curl, openssl or a website like https://www.digicert.com/help/.
No idea why Chrome (possibly) sometimes has problems validating these certs.
assylias and Head of Catering have already given your the reason why the error is occurring.
Now regarding what you are doing, from what I understand, you don't need to use Select
at all
I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as
Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String
filepath = CStr(FileDialog)
'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")
lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)
lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)
You are using multiple versions of the Android Support Libraries:
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
compile 'com.android.support:design:25+'
Two are 26.0.0-alpha1
, and one is using 25+
.
Pick one concrete version and use it for all three of these. Since your compileSdkVersion
is not O
, use 25.3.1
for all three of these libraries, resulting in:
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
psxls gave a great answer but I think my Notepad++ version is slightly different so the $ (dollar sign) capturing did not work.
I have Notepad++ v.5.9.3 and here's how you can accomplish your task:
Search for the pattern: value=\"([0-9]*)\" And replace with: \1 (whatever you want to do around that capturing group)
Ex. Surround with square brackets
[\1] --> will produce value="[4]"
You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.
If you use Spring, take a look at their MethodInterceptor class.
The only option I can think of is using width:100%
. If you want to have a padding on the input field too, than just place a container label
around it, move the formatting to that label instead, while also specify the padding to the label. Input fields are rigid.
The loop only breaks if you return literally false
. Ex:
// this is how jquery calls your function
// notice hard comparison (===) against false
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
This means you can return anything else, including undefined
, which is what you return if you return nothing, so you can simply use an empty return statement:
$.each(collection, function (index, item) {
if (!someTestCondition)
return; // go to next iteration
// otherwise do something
});
It's possible this might vary by version; this is applicable for jquery 1.12.4. But really, when you exit out the bottom of the function, you are also returning nothing, and that's why the loop continues, so I would expect that there is no possibility whatsoever that returning nothing could not continue the loop. Unless they want to force everyone to start returning something to keep the loop going, returning nothing has to be a way to keep it going.
Store connection string in web.config
It is a good practice to store the connection string for your application in a config file rather than as a hard coded string in your code. The way to do this differs between .NET 2.0 and .NET 3.5 (and above). This article cover both. https://www.connectionstrings.com/store-connection-string-in-webconfig/
Further to Ramnath's answer, the behaviour you are experiencing is that due to as.numeric(x)
returning the internal, numeric representation of the factor x
at the R level. If you want to preserve the numbers that are the levels of the factor (rather than their internal representation), you need to convert to character via as.character()
first as per Ramnath's example.
Your for
loop is just as reasonable as an apply
call and might be slightly more readable as to what the intention of the code is. Just change this line:
stats[,i] <- as.numeric(stats[,i])
to read
stats[,i] <- as.numeric(as.character(stats[,i]))
This is FAQ 7.10 in the R FAQ.
HTH
.myDiv {
background-color: red;
width: 100%;
min-height: 100vh;
max-height: 100%;
position: absolute;
top: 0;
left: 0;
margin: 0 auto;
}
Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.
Swift 3, with extension:
extension UIView{
var globalPoint :CGPoint? {
return self.superview?.convert(self.frame.origin, to: nil)
}
var globalFrame :CGRect? {
return self.superview?.convert(self.frame, to: nil)
}
}
# A Simple Confusion Matrix Implementation
def confusionmatrix(actual, predicted, normalize = False):
"""
Generate a confusion matrix for multiple classification
@params:
actual - a list of integers or strings for known classes
predicted - a list of integers or strings for predicted classes
normalize - optional boolean for matrix normalization
@return:
matrix - a 2-dimensional list of pairwise counts
"""
unique = sorted(set(actual))
matrix = [[0 for _ in unique] for _ in unique]
imap = {key: i for i, key in enumerate(unique)}
# Generate Confusion Matrix
for p, a in zip(predicted, actual):
matrix[imap[p]][imap[a]] += 1
# Matrix Normalization
if normalize:
sigma = sum([sum(matrix[imap[i]]) for i in unique])
matrix = [row for row in map(lambda i: list(map(lambda j: j / sigma, i)), matrix)]
return matrix
The approach here is to pair up the unique classes found in the actual
vector into a 2-dimensional list. From there, we simply iterate through the zipped actual
and predicted
vectors and populate the counts using the indices to access the matrix positions.
Usage
cm = confusionmatrix(
[1, 1, 2, 0, 1, 1, 2, 0, 0, 1], # actual
[0, 1, 1, 0, 2, 1, 2, 2, 0, 2] # predicted
)
# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]
Note: the actual
classes are along the columns and the predicted
classes are along the rows.
# Actual
# 0 1 2
# # #
[[2, 1, 0], # 0
[0, 2, 1], # 1 Predicted
[1, 2, 1]] # 2
Class Names Can be Strings or Integers
cm = confusionmatrix(
["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"] # predicted
)
# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]
You Can Also Return The Matrix With Proportions (Normalization)
cm = confusionmatrix(
["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"], # predicted
normalize = True
)
# And The Output
print(cm)
[[0.2, 0.1, 0.0], [0.0, 0.2, 0.1], [0.1, 0.2, 0.1]]
Since writing this post, I've updated my library implementation to be a class that uses a confusion matrix representation internally to compute statistics, in addition to pretty printing the confusion matrix itself. See this Gist.
Example Usage
# Actual & Predicted Classes
actual = ["A", "B", "C", "C", "B", "C", "C", "B", "A", "A", "B", "A", "B", "C", "A", "B", "C"]
predicted = ["A", "B", "B", "C", "A", "C", "A", "B", "C", "A", "B", "B", "B", "C", "A", "A", "C"]
# Initialize Performance Class
performance = Performance(actual, predicted)
# Print Confusion Matrix
performance.tabulate()
With the output:
===================================
A? B? C?
A? 3 2 1
B? 1 4 1
C? 1 0 4
Note: class? = Predicted, class? = Actual
===================================
And for the normalized matrix:
# Print Normalized Confusion Matrix
performance.tabulate(normalized = True)
With the normalized output:
===================================
A? B? C?
A? 17.65% 11.76% 5.88%
B? 5.88% 23.53% 5.88%
C? 5.88% 0.00% 23.53%
Note: class? = Predicted, class? = Actual
===================================
Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:
class ThreadableMixin:
def start_worker(self):
threading.Thread(target=self.worker).start()
def worker(self):
try:
self._worker()
except tornado.web.HTTPError, e:
self.set_status(e.status_code)
except:
logging.error("_worker problem", exc_info=True)
self.set_status(500)
tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))
...
and the child that have a _worker method
class Handler(tornado.web.RequestHandler, ThreadableMixin):
def _worker(self):
self.res = self.render_string("template.html",
title = _("Title"),
data = self.application.db.query("select ... where object_id=%s", self.object_id)
)
...
Execute:
rails generate migration add_column_to_table column:boolean
It will generate this migration:
class AddColumnToTable < ActiveRecord::Migration
def change
add_column :table, :column, :boolean
end
end
Set the default value adding :default => 1
add_column :table, :column, :boolean, :default => 1
Run:
rake db:migrate
typeof callback === "function"
if num % 2 == 0:
pass # Even
else:
pass # Odd
The %
sign is like division only it checks for the remainder, so if the number divided by 2
has a remainder of 0
it's even otherwise odd.
Or reverse them for a little speed improvement, since any number above 0 is also considered "True" you can skip needing to do any equality check:
if num % 2:
pass # Odd
else:
pass # Even
The min-width
property does not work correctly in Internet Explorer, which is most likely the cause of your problems.
Read info and a brilliant script that fixes many IE CSS problems.
If you're using npm you could use Gulp.js a build tool to build your Font Awesome packages from SCSS or LESS. This example will compile the code from SCSS.
Install Gulp.js v4 locally and CLI V2 globally.
Install a plugin called gulp-sass using npm.
Create a main.scss file in your public folder and use this code:
$fa-font-path: "../webfonts";
@import "fontawesome/fontawesome";
@import "fontawesome/brands";
@import "fontawesome/regular";
@import "fontawesome/solid";
@import "fontawesome/v4-shims";
Create a gulpfile.js in your app directory and copy this.
const { src, dest, series, parallel } = require('gulp');
const sass = require('gulp-sass');
const fs = require('fs');
function copyFontAwesomeSCSS() {
return src('node_modules/@fortawesome/fontawesome-free/scss/*.scss')
.pipe(dest('public/scss/fontawesome'));
}
function copyFontAwesomeFonts() {
return src('node_modules/@fortawesome/fontawesome-free/webfonts/*')
.pipe(dest('public/dist/webfonts'));
}
function compileSCSS() {
return src('./public/scss/theme.scss')
.pipe(sass()).pipe(dest('public/css'));
}
// Series completes tasks sequentially and parallel completes them asynchronously
exports.build = parallel(
copyFontAwesomeFonts,
series(copyFontAwesomeSCSS, compileSCSS)
);
Run 'gulp build' in your command line and watch the magic.
The plugin vagrant-vbguest solved my problem:
$ vagrant plugin install vagrant-vbguest
Output:
$ vagrant reload
==> default: Attempting graceful shutdown of VM...
...
==> default: Machine booted and ready!
GuestAdditions 4.3.12 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Exporting NFS shared folders...
==> default: Preparing to edit /etc/exports. Administrator privileges will be required...
==> default: Mounting NFS shared folders...
==> default: VM already provisioned. Run `vagrant provision` or use `--provision` to force it
Just make sure you are running the latest version of VirtualBox
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Another option would be to abandon the syntactic sugar and decorate in the __init__
of the class.
def countdown(number):
def countdown_decorator(func):
def func_wrapper():
for index in reversed(range(1, number+1)):
print(index)
func()
return func_wrapper
return countdown_decorator
class MySuperClass():
def __init__(self, number):
self.number = number
self.do_thing = countdown(number)(self.do_thing)
def do_thing(self):
print('im doing stuff!')
myclass = MySuperClass(3)
myclass.do_thing()
which would print
3
2
1
im doing stuff!
Well, it actually looks like the warning is telling you what to do.
As part of sklearn.pipeline
stages' uniform interfaces, as a rule of thumb:
when you see X
, it should be an np.array
with two dimensions
when you see y
, it should be an np.array
with a single dimension.
Here, therefore, you should consider the following:
temp = [1,2,3,4,5,5,6,....................,7]
# This makes it into a 2d array
temp = np.array(temp).reshape((len(temp), 1))
temp = scaler.transform(temp)
SlickGrid has this functionality, see the tree demo.
If you want to build your own, here is an example (jsFiddle demo): Build your table with a data-depth
attribute to indicate the depth of the item in the tree (the levelX
CSS classes are just for styling indentation):
<table id="mytable">
<tr data-depth="0" class="collapse level0">
<td><span class="toggle collapse"></span>Item 1</td>
<td>123</td>
</tr>
<tr data-depth="1" class="collapse level1">
<td><span class="toggle"></span>Item 2</td>
<td>123</td>
</tr>
</table>
Then when a toggle link is clicked, use Javascript to hide all <tr>
elements until a <tr>
of equal or less depth is found (excluding those already collapsed):
$(function() {
$('#mytable').on('click', '.toggle', function () {
//Gets all <tr>'s of greater depth below element in the table
var findChildren = function (tr) {
var depth = tr.data('depth');
return tr.nextUntil($('tr').filter(function () {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var tr = el.closest('tr'); //Get <tr> parent of toggle button
var children = findChildren(tr);
//Remove already collapsed nodes from children so that we don't
//make them visible.
//(Confused? Remove this code and close Item 2, close Item 1
//then open Item 1 again, then you will understand)
var subnodes = children.filter('.expand');
subnodes.each(function () {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (tr.hasClass('collapse')) {
tr.removeClass('collapse').addClass('expand');
children.hide();
} else {
tr.removeClass('expand').addClass('collapse');
children.show();
}
return children;
});
});
Check you routes, the update on 9/28/2014 impacted us. We had to adjust our older servers and add new routes. Here is the article http://www.rackspace.com/knowledge_center/article/updating-servicenet-routes-on-cloud-servers-created-before-june-3-2013
Prompted by this question, may I present another alternative which might be a bit nicer to use and will look the same for both methods and functions:
@static_var2('seed',0)
def funccounter(statics, add=1):
statics.seed += add
return statics.seed
print funccounter() #1
print funccounter(add=2) #3
print funccounter() #4
class ACircle(object):
@static_var2('seed',0)
def counter(statics, self, add=1):
statics.seed += add
return statics.seed
c = ACircle()
print c.counter() #1
print c.counter(add=2) #3
print c.counter() #4
d = ACircle()
print d.counter() #5
print d.counter(add=2) #7
print d.counter() #8
If you like the usage, here's the implementation:
class StaticMan(object):
def __init__(self):
self.__dict__['_d'] = {}
def __getattr__(self, name):
return self.__dict__['_d'][name]
def __getitem__(self, name):
return self.__dict__['_d'][name]
def __setattr__(self, name, val):
self.__dict__['_d'][name] = val
def __setitem__(self, name, val):
self.__dict__['_d'][name] = val
def static_var2(name, val):
def decorator(original):
if not hasattr(original, ':staticman'):
def wrapped(*args, **kwargs):
return original(getattr(wrapped, ':staticman'), *args, **kwargs)
setattr(wrapped, ':staticman', StaticMan())
f = wrapped
else:
f = original #already wrapped
getattr(f, ':staticman')[name] = val
return f
return decorator
That's no problem.
@Html.Partial("../Controller/View", model)
or
@Html.Partial("~/Views/Controller/View.cshtml", model)
Should do the trick.
If you want to pass through the (other) controller, you can use:
@Html.Action("action", "controller", parameters)
or any of the other overloads
For those who would like to allow all certificates to work (for testing purposes) over OAuth, follow these steps:
1) Download the source code of the Android OAuth API here: https://github.com/kaeppler/signpost
2) Find the file "CommonsHttpOAuthProvider" class
3) Change it as below:
public class CommonsHttpOAuthProvider extends AbstractOAuthProvider {
private static final long serialVersionUID = 1L;
private transient HttpClient httpClient;
public CommonsHttpOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl,
String authorizationWebsiteUrl) {
super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl);
//this.httpClient = new DefaultHttpClient();//Version implemented and that throws the famous "javax.net.ssl.SSLException: Not trusted server certificate" if the certificate is not signed with a CA
this.httpClient = MySSLSocketFactory.getNewHttpClient();//This will work with all certificates (for testing purposes only)
}
The "MySSLSocketFactory" above is based on the accepted answer. To make it even easier, here goes the complete class:
package com.netcomps.oauth_example;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
//http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
public static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
Hope this helps someone.
Is this endpoint taking too many time?
Maybe you are using flask without asynchronous support, so every request will block the call. To create async support without make difficult, add the gevent
worker.
With gevent, a new call will spawn a new thread, and you app will be able to receive more requests
pip install gevent
gunicon .... --worker-class gevent
Another approach could be using Array.prototype.forEach()
as
Array.from({_x000D_
length: 5_x000D_
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {_x000D_
console.log(val, index)_x000D_
})
_x000D_
Pro single
Easy to find.
Hunting down exclusion rules can be quite difficult if I have multiple gitignore, at several levels in the repo.
With multiple files, you also typically wind up with a fair bit of duplication.
Pro multiple
Scopes "knowledge" to the part of the file tree where it is needed.
Since Git only tracks files, an empty .gitignore is the only way to commit an "empty" directory.
(And before Git 1.8, the only way to exclude a pattern like my/**.example
was to create my/.gitignore
in with the pattern **.foo
. This reason doesn't apply now, as you can do /my/**/*.example
.)
I much prefer a single file, where I can find all the exclusions. I've never missed per-directory .svn, and I won't miss per-directory .gitignore either.
That said, multiple gitignores are quite common. If you do use them, at least be consistent in their use to make them reasonable to work with. For example, you may put them in directories only one level from the root.
Here is the way I've found to load all image data for all products in a collection. I am not sure at the moment why its needed to switch from Mage::getModel to Mage::helper and reload the product, but it must be done. I've reverse engineered this code from the magento image soap api, so I'm pretty sure its correct.
I have it set to load products with a vendor code equal to '39' but you could change that to any attribute, or just load all the products, or load whatever collection you want (including the collections in the phtml files showing products currently on the screen!)
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(
array('attribute'=>'vendor_code','eq'=>'39'),
));
$collection->addAttributeToSelect('*');
foreach ($collection as $product) {
$prod = Mage::helper('catalog/product')->getProduct($product->getId(), null, null);
$attributes = $prod->getTypeInstance(true)->getSetAttributes($prod);
$galleryData = $prod->getData('media_gallery');
foreach ($galleryData['images'] as &$image) {
var_dump($image);
}
}
login to cqlsh
use below command to get names/list of keyspaces present
SELECT keyspace_name FROM system_schema.keyspaces;
On Unix systems, for several projects, I added these lines into the CMakeLists.txt and it was compiling successfully because base (/usr/include) and local includes (/usr/local/include) go into separated directories:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include -L/usr/local/lib")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib")
It appends the correct directory, including paths for the C and C++ compiler flags and the correct directory path for the linker flags.
Note: C++ compiler (c++) doesn't support -L, so we have to use CMAKE_EXE_LINKER_FLAGS
To collapse methods in the Visual Studio Code editor:
NB.: As per the Visual Studio Code documentation, a folding region starts when a line has a smaller indent than one or more following lines, and ends when there is a line with the same or smaller indent.
Use '
for a straight apostrophe. This tends to be more readable than the numeric '
(if others are ever likely to read the HTML directly).
Edit: msanders points out that '
isn't valid HTML4, which I didn't know, so follow most other answers and use '
.
A metaclass is a class that tells how (some) other class should be created.
This is a case where I saw metaclass as a solution to my problem: I had a really complicated problem, that probably could have been solved differently, but I chose to solve it using a metaclass. Because of the complexity, it is one of the few modules I have written where the comments in the module surpass the amount of code that has been written. Here it is...
#!/usr/bin/env python
# Copyright (C) 2013-2014 Craig Phillips. All rights reserved.
# This requires some explaining. The point of this metaclass excercise is to
# create a static abstract class that is in one way or another, dormant until
# queried. I experimented with creating a singlton on import, but that did
# not quite behave how I wanted it to. See now here, we are creating a class
# called GsyncOptions, that on import, will do nothing except state that its
# class creator is GsyncOptionsType. This means, docopt doesn't parse any
# of the help document, nor does it start processing command line options.
# So importing this module becomes really efficient. The complicated bit
# comes from requiring the GsyncOptions class to be static. By that, I mean
# any property on it, may or may not exist, since they are not statically
# defined; so I can't simply just define the class with a whole bunch of
# properties that are @property @staticmethods.
#
# So here's how it works:
#
# Executing 'from libgsync.options import GsyncOptions' does nothing more
# than load up this module, define the Type and the Class and import them
# into the callers namespace. Simple.
#
# Invoking 'GsyncOptions.debug' for the first time, or any other property
# causes the __metaclass__ __getattr__ method to be called, since the class
# is not instantiated as a class instance yet. The __getattr__ method on
# the type then initialises the class (GsyncOptions) via the __initialiseClass
# method. This is the first and only time the class will actually have its
# dictionary statically populated. The docopt module is invoked to parse the
# usage document and generate command line options from it. These are then
# paired with their defaults and what's in sys.argv. After all that, we
# setup some dynamic properties that could not be defined by their name in
# the usage, before everything is then transplanted onto the actual class
# object (or static class GsyncOptions).
#
# Another piece of magic, is to allow command line options to be set in
# in their native form and be translated into argparse style properties.
#
# Finally, the GsyncListOptions class is actually where the options are
# stored. This only acts as a mechanism for storing options as lists, to
# allow aggregation of duplicate options or options that can be specified
# multiple times. The __getattr__ call hides this by default, returning the
# last item in a property's list. However, if the entire list is required,
# calling the 'list()' method on the GsyncOptions class, returns a reference
# to the GsyncListOptions class, which contains all of the same properties
# but as lists and without the duplication of having them as both lists and
# static singlton values.
#
# So this actually means that GsyncOptions is actually a static proxy class...
#
# ...And all this is neatly hidden within a closure for safe keeping.
def GetGsyncOptionsType():
class GsyncListOptions(object):
__initialised = False
class GsyncOptionsType(type):
def __initialiseClass(cls):
if GsyncListOptions._GsyncListOptions__initialised: return
from docopt import docopt
from libgsync.options import doc
from libgsync import __version__
options = docopt(
doc.__doc__ % __version__,
version = __version__,
options_first = True
)
paths = options.pop('<path>', None)
setattr(cls, "destination_path", paths.pop() if paths else None)
setattr(cls, "source_paths", paths)
setattr(cls, "options", options)
for k, v in options.iteritems():
setattr(cls, k, v)
GsyncListOptions._GsyncListOptions__initialised = True
def list(cls):
return GsyncListOptions
def __getattr__(cls, name):
cls.__initialiseClass()
return getattr(GsyncListOptions, name)[-1]
def __setattr__(cls, name, value):
# Substitut option names: --an-option-name for an_option_name
import re
name = re.sub(r'^__', "", re.sub(r'-', "_", name))
listvalue = []
# Ensure value is converted to a list type for GsyncListOptions
if isinstance(value, list):
if value:
listvalue = [] + value
else:
listvalue = [ None ]
else:
listvalue = [ value ]
type.__setattr__(GsyncListOptions, name, listvalue)
# Cleanup this module to prevent tinkering.
import sys
module = sys.modules[__name__]
del module.__dict__['GetGsyncOptionsType']
return GsyncOptionsType
# Our singlton abstract proxy class.
class GsyncOptions(object):
__metaclass__ = GetGsyncOptionsType()
I think that the best way to do this is:
Stash your local changes:
git stash
Update the branch to the latest code
git pull
Merge your local changes into the latest code:
git stash apply
Add, commit and push your changes
git add
git commit
git push
In my experience this is the path to least resistance with Git (on the command line anyway).
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@id", "abc");
command.Parameters.AddWithValue("@username", "abc");
command.Parameters.AddWithValue("@password", "abc");
command.Parameters.AddWithValue("@email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Using the minus
operator was working but also it was taking more time to execute which was not acceptable.
I have a similar kind of requirement for data migration and I used the NOT IN
operator for that.
The modified query is :
select *
from A
where (emp_id,emp_name) not in
(select emp_id,emp_name from B)
union all
select * from B
where (emp_id,emp_name) not in
(select emp_id,emp_name from A);
This query executed fast. Also you can add any number of columns in the select query. Only catch is that both tables should have the exact same table structure for this to be executed.
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
Swift 4+:
let myTableViewController = UITableViewController(style: .grouped)
It's a magic number used in various places because it also happens to be readable in English, making it stand out. There's a partial list on Wikipedia.
To my knowledge, only ENV
allows that, as mentioned in "Environment replacement"
Environment variables (declared with the
ENV
statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.
They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build
.
In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.
This day, I use both ARG
(docker 1.10+, and docker build --build-arg var=value
) and ENV
.
Using ARG
alone means your variable is visible at build time, not at runtime.
My Dockerfile usually has:
ARG var
ENV var=${var}
In your case, ARG
is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.
Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.
As a beginner in SQL I find that when using a BEGIN
and END
SSMS usually adds a squiggly line with incorrect syntax near 'END'
to END, simply because there's no content in between yet. If you're just setting up BEGIN
and END
to get started and add the actual query later, then simply add a bogus PRINT
statement so SSMS stops bothering you.
For example:
IF (1=1)
BEGIN
PRINT 'BOGUS'
END
The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:
IF (1=1)
BEGIN
END
Ctrl + A, Ctrl + \ - Exit screen and terminate all programs in this screen. It is helpful, for example, if you need to close a tty connection.
Ctrl + D, D or - Ctrl + A, Ctrl + D - "minimize" screen and screen -r
to restore it.
You won't find anything overlaying GDB which can compete with the raw power of the Visual Studio debugger. It's just too powerful, and it's just too well integrated inside the IDE.
For a Linux alternative, try DDD if free software is your thing.
Here is a flexible way to do deal with multiple indented lines without using heredoc.
echo 'Hello!'
sed -e 's:^\s*::' < <(echo '
Some indented text here.
Some indented text here.
')
if [[ true ]]; then
sed -e 's:^\s\{4,4\}::' < <(echo '
Some indented text here.
Some extra indented text here.
Some indented text here.
')
fi
Some notes on this solution:
\
or replace the string delimiters with double quotes. In the latter case, be careful that construction like $(command)
will be interpreted. If the string contains both simple and double quotes, you'll have to escape at least of kind.This helped me:
Posted: 8/12/2011 4:54
Set tnsnames directory tools->Preferences->Database->advanced->Tnsnames Directory
https://forums.oracle.com/forums/thread.jspa?messageID=10020012�
It's even easier to do without a library
window.onload = function() {
// code
};
Your user don't have the right permissions to read
the file, since you used open()
without specifying a mode.
Since you're using Windows, you should read a little more about File and Folder Permissions.
Also, if you want to play with your file permissions, you should right-click
it, choose Properties
and select Security
tab.
Or if you want to be a little more hardcore, you can run your script as admin.
SO Related Questions:
Surprisingly this library not mentioned yet
python package named python-slugify, which does a pretty good job of slugifying:
pip install python-slugify
Works like this:
from slugify import slugify
txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")
txt = 'Nín hao. Wo shì zhong guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")
txt = '?????????'
r = slugify(txt)
self.assertEquals(r, "kompiuter")
txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a")
It could depend on your framework. (for each of them could exist an easier solution).
But to answer your question: there are a lot of external libraries for this functionality. Look here how to use apache commons fileupload.
Change it to
public static class LinqHelper
I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:
<partial name="_My_Partial" model="Model.MyInfo" />
It's best not to target any specific resolution, but to adapt easily to many different resolutions.
var fileStream = fs.createWriteStream('/path/to/file.jpg');
var s3Stream = s3.getObject({Bucket: 'myBucket', Key: 'myImageFile.jpg'}).createReadStream();
// Listen for errors returned by the service
s3Stream.on('error', function(err) {
// NoSuchKey: The specified key does not exist
console.error(err);
});
s3Stream.pipe(fileStream).on('error', function(err) {
// capture any errors that occur when writing data to the file
console.error('File Stream:', err);
}).on('close', function() {
console.log('Done.');
});
Reference: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/requests-using-stream-objects.html
Another solution which, in my opinion, is easier to read would be:
UPDATE test
SET something = 1, field = IF(condition is true, 1, field)
WHERE id = 123
What this does is set 'field' to 1 (like OP used as example) if the condition is met and use the current value of 'field' if not met. Using the previous value is the same as not changing, so there you go.
Why are you specifying myFile
there?
Git revert reverts the commit(s) that you specify.
git revert HEAD~2
reverts the HEAD~2
commit
git revert HEAD~2 myfile
reverts HEAD~2
AND myFile
I take myFile
is a file that you want to revert? In that case use
git checkout HEAD~2 -- myFile
str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:
removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})
This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
If you still want to show the item but make it not clickable and look disabled with CSS:
CSS:
.disabled {
pointer-events:none; //This makes it not clickable
opacity:0.6; //This grays it out to look disabled
}
HTML:
<li class="disabled">Disabled List Item</li>
Also, if you are using BootStrap, they already have a class called disabled for this purpose. See this example.
As @LV98 pointed out, users could change this on the client side and submit a selection you weren't expecting. You will want to validate at the server as well.
The only way I've found to work with files on SharePoint while having to server rights is to map the WebDAV folder to a drive letter. Here's an example for the implementation.
Add references to the following ActiveX libraries in VBA:
wshom.ocx
) - for WshNetworkscrrun.dll
) - for FileSystemObjectCreate a new class module, call it DriveMapper
and add the following code:
Option Explicit
Private oMappedDrive As Scripting.Drive
Private oFSO As New Scripting.FileSystemObject
Private oNetwork As New WshNetwork
Private Sub Class_Terminate()
UnmapDrive
End Sub
Public Function MapDrive(NetworkPath As String) As Scripting.Folder
Dim DriveLetter As String, i As Integer
UnmapDrive
For i = Asc("Z") To Asc("A") Step -1
DriveLetter = Chr(i)
If Not oFSO.DriveExists(DriveLetter) Then
oNetwork.MapNetworkDrive DriveLetter & ":", NetworkPath
Set oMappedDrive = oFSO.GetDrive(DriveLetter)
Set MapDrive = oMappedDrive.RootFolder
Exit For
End If
Next i
End Function
Private Sub UnmapDrive()
If Not oMappedDrive Is Nothing Then
If oMappedDrive.IsReady Then
oNetwork.RemoveNetworkDrive oMappedDrive.DriveLetter & ":"
End If
Set oMappedDrive = Nothing
End If
End Sub
Then you can implement it in your code:
Sub test()
Dim dm As New DriveMapper
Dim sharepointFolder As Scripting.Folder
Set sharepointFolder = dm.MapDrive("http://your/sharepoint/path")
Debug.Print sharepointFolder.Path
End Sub
Just use
File.Copy(filepath, "\\\\192.168.1.28\\Files");
A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.
The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.
You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!
If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"
If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.
Resizing the icon is not straightforward. You need to use Java's graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon
class. You can use ImageIcon
class to load your image file and then simply call getter method to get the image.
private Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
Most of these answers are out of date.
Google now has an easy way to import it.. We will continue to see a lot of outdated information as they did not create this solution for a good 2-3 years.
https://bintray.com/android/android-utils/com.android.volley.volley/view
All you need to do is add to your Build.Gradle the following:
compile 'com.android.volley:volley:1.0.0'
IE
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.example.foobar.ebay"
minSdkVersion 23
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.volley:volley:1.0.0'
testCompile 'junit:junit:4.12'
}
You can use git checkout <file>
to check out the committed version of the file (thus discarding your changes), or git reset --hard HEAD
to throw away any uncommitted changes for all files.
Make sure not to miss the explanation of :host-context
which is directly above ::ng-deep
in the angular guide : https://angular.io/guide/component-styles. I missed it up until now and wish I'd seen it sooner.
::ng-deep
is often necessary when you didn't write the component and don't have access to its source, but :host-context
can be a very useful option when you do.
For example I have a black <h1>
header inside a component I designed, and I want the ability to change it to white when it's displayed on a dark themed background.
If I didn't have access to the source I may have to do this in the css for the parent:
.theme-dark widget-box ::ng-deep h1 { color: white; }
But instead with :host-context
you can do this inside the component.
h1
{
color: black; // default color
:host-context(.theme-dark) &
{
color: white; // color for dark-theme
}
// OR set an attribute 'outside' with [attr.theme]="'dark'"
:host-context([theme='dark']) &
{
color: white; // color for dark-theme
}
}
This will look anywhere in the component chain for .theme-dark
and apply the css to the h1 if found. This is a good alternative to relying too much on ::ng-deep
which while often necessary is somewhat of an anti-pattern.
In this case the &
is replaced by the h1
(that's how sass/scss works) so you can define your 'normal' and themed/alternative css right next to each other which is very handy.
Be careful to get the correct number of :
. For ::ng-deep
there are two and for :host-context
only one.
Consider following code
<ul id="myTask">
<li>Coding</li>
<li>Answering</li>
<li>Getting Paid</li>
</ul>
Now, here goes the difference
// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
$(this).remove()
});
Now, what if we add a myTask again?
$('#myTask').append('<li>Answer this question on SO</li>');
Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on
, the new item would work without any extra effort on our part. Here's how the .on version would look:
$('#myTask').on('click', 'li', function (event) {
$(event.target).remove()
});
Summary:
The difference between .on()
and .click()
would be that .click()
may not work when the DOM elements associated with the .click()
event are added dynamically at a later point while .on()
can be used in situations where the DOM elements associated with the .on()
call may be generated dynamically at a later point.
This will get you a Bitmap
from the ImageView
. Though, it is not the same bitmap object that you've set. It is a new one.
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
=== EDIT ===
imageView.setDrawingCacheEnabled(true);
imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
imageView.layout(0, 0,
imageView.getMeasuredWidth(), imageView.getMeasuredHeight());
imageView.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
imageView.setDrawingCacheEnabled(false);
I have put together a collection of categories for NSData and NSString which uses solutions found on Jeff LaMarche's blog and some hints by Quinn Taylor here on Stack Overflow.
It uses categories to extend NSData to provide AES256 encryption and also offers an extension of NSString to BASE64-encode encrypted data safely to strings.
Here's an example to show the usage for encrypting strings:
NSString *plainString = @"This string will be encrypted";
NSString *key = @"YourEncryptionKey"; // should be provided by a user
NSLog( @"Original String: %@", plainString );
NSString *encryptedString = [plainString AES256EncryptWithKey:key];
NSLog( @"Encrypted String: %@", encryptedString );
NSLog( @"Decrypted String: %@", [encryptedString AES256DecryptWithKey:key] );
Get the full source code here:
Thanks for all the helpful hints!
-- Michael
You can write a script and then use nohup ./yourscript &
to execute
For example:
vi yourscript
put
#!/bin/bash
script here
you may also need to change permission to run script on server
chmod u+rwx yourscript
finally
nohup ./yourscript &
When you use ng-options to populate a select list, it uses the entire object as the selected value, not just the single value you see in the select list. So in your case, you'd need to set
$scope.object.setDefault = {
id:600,
name:"def"
};
or
$scope.object.setDefault = $scope.selectItems[1];
I also recommend just outputting the value of $scope.object.setDefault in your template to see what I'm talking about getting selected.
<pre>{{object.setDefault}}</pre>
I've just stumbled upon this problem too, learning React, and solved it by showing spinner until the data is ready.
render() {
if (this.state.data === null) {
return (
<div className="MyView">
<Spinner/>
</div>
);
}
else {
return(
<div className="MyView">
<ReactJson src={this.state.data}/>
</div>
);
}
}
Every method in Web API will return data (JSON) without serialization.
However, in order to return JSON Data in MVC controllers, we will set the returned Action Result type to JsonResult and call the Json method on our object to ensure it is packaged in JSON.
I found a better way to do this with powershell under windows (but really only because I was looking for a way to script changing the user agent string, not muck about with proxies).
function set-uas
{
Param
(
[string]$UAS = "Default"
)
$FirefoxPrefs = "C:\Users\Admin\AppData\Roaming\Mozilla\Firefox\Profiles\*.default\prefs.js"
if ($UAS -eq "Default")
{
$fileinfo = type $FirefoxPrefs
$fileinfo = $fileinfo | findstr /v "general.appname.override"
$fileinfo = $fileinfo | findstr /v "general.appversion.override"
$fileinfo = $fileinfo | findstr /v "general.platform.override"
$fileinfo = $fileinfo | findstr /v "general.useragent.appName"
$fileinfo = $fileinfo | findstr /v "general.useragent.override"
$fileinfo = $fileinfo | findstr /v "general.useragent.vendor"
$fileinfo = $fileinfo | findstr /v "general.useragent.vendorSub"
$fileinfo += "user_pref(`"useragentswitcher.import.overwrite`", false);`n"
$fileinfo += "user_pref(`"useragentswitcher.menu.hide`", false);`n"
$fileinfo += "user_pref(`"useragentswitcher.reset.onclose`", false);`n"
$fileinfo | Out-File -FilePath $FirefoxPrefs -Encoding ASCII
}
else
{
set-uas Default
}
if ($UAS -eq "iphone")
{
$fileinfo = ""
$fileinfo += "user_pref(`"general.appname.override`", `"Netscape`");`n"
$fileinfo += "user_pref(`"general.appversion.override`", `"5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16`");`n"
$fileinfo += "user_pref(`"general.platform.override`", `"iPhone`");`n"
$fileinfo += "user_pref(`"general.useragent.appName`", `"Mozilla`");`n"
$fileinfo += "user_pref(`"general.useragent.override`", `"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16`");`n"
$fileinfo += "user_pref(`"general.useragent.vendor`", `"Apple Computer, Inc.`");`n"
$fileinfo += "user_pref(`"general.useragent.vendorSub`", `"`");`n"
$fileinfo += "user_pref(`"useragentswitcher.reset.onclose`", false);`n"
$fileinfo | Out-File -FilePath $FirefoxPrefs -Encoding ASCII -Append
}
elseif ($UAS -eq "lumia")
{
$fileinfo = ""
$fileinfo += "user_pref(`"general.appname.override`", `"Netscape`");`n"
$fileinfo += "user_pref(`"general.appversion.override`", `"9.80 (Windows Phone; Opera Mini/9.0.0/37.6652; U; en) Presto/2.12.423 Version/12.16`");`n"
$fileinfo += "user_pref(`"general.platform.override`", `"Nokia`");`n"
$fileinfo += "user_pref(`"general.useragent.appName`", `"Mozilla`");`n"
$fileinfo += "user_pref(`"general.useragent.override`", `"Opera/9.80 (Windows Phone; Opera Mini/9.0.0/37.6652; U; en) Presto/2.12.423 Version/12.16`");`n"
$fileinfo += "user_pref(`"general.useragent.vendor`", `"Microsoft`");`n"
$fileinfo += "user_pref(`"general.useragent.vendorSub`", `"`");`n"
$fileinfo += "user_pref(`"useragentswitcher.reset.onclose`", false);`n"
$fileinfo | Out-File -FilePath $FirefoxPrefs -Encoding ASCII -Append
}
}
I have the firefox plugin "useragentswitcher" also installed, and have not tested this without it.
I also have set "user_pref("useragentswitcher.reset.onclose", false);"
[EDIT] I've revised my code, it was occasionally outputting some bad character or something. For some reason this is detected by firefox as a corrupt profile, and the entire profile was discarded, and refreshed with a default profile.
Also, credit where credit is due: this code is loosely based off of what xBoarder posted in his response to sam3344920 (https://stackoverflow.com/a/2509088/5403057). Also, I was able to fix the encoding bug with help from a post from Phoenix14830 (https://stackoverflow.com/a/32080395/5403057)
[Edit2] Added support for setting the UAS to lumia. This is actually using an Opera mobile UAS, because I still wanted bing to work, and if you use the regular lumia UAS www.bing.com redirects to bing://?%^&* which firefox doesn't know how to process
Thinking that manually setting up .gitmodules
is enough is WRONG
My local git version 2.22.0
as of this writing.
So I came to this thread wondering why wasn't git submodule init
working; I setup the .gitmodules
file and proceeded to do git submodule init
...
IMPORTANT
git submodule add company/project.git includes/project
is required (when adding the module for the first time), this will:
.git/config
.gitmodules
fileincludes/project
in this example).you must then git commit
after you have added the submodule, this will commit .gitmodules
and the tracked submodule location.
When the project is cloned again, it will have the .gitmodules
and the empty submodules directory (e.g. includes/project
in this example). At this point .git/config
does not have submodule config yet, until git submodule init
is run, and remember this only works because .gitmodules
AND includes/project
are tracked in the main git repo.
Also for reference see:
This is an old question I know, but this is in the top five for several related Google searches. Here's the CSS-only solution without changing the images to background images:
width: auto;
height: auto;
max-width: MaxSize;
max-height: MaxSize;
"MaxSize" is a placeholder for whatever max-width
and max-height
you want to use, in pixels or percentage. auto
will increase (or decrease) the width and height to occupy the space you specify with MaxSize. It will override any defaults for images you or the viewer's browser might have for images. I've found it's especially important on Android's Firefox. Pixels or percentages work for max size. With both the height and width set to auto
, the aspect ratio of the original image will be retained.
If you want to fill the space entirely and don't mind the image being larger than its original size, change the two max-width
s to min-width: 100%
- this will make them completely occupy their space and maintain aspect ratio. You can see an example of this with a Twitter profile's background image.
If you're just comparing for equality, you can just do this:
if not dict1 == dict2:
match = False
Otherwise, the only major problem I see is that you're going to get a KeyError if there is a key in dict1 that is not in dict2, so you may want to do something like this:
for key in dict1:
if not key in dict2 or dict1[key] != dict2[key]:
match = False
You could compress this into a comprehension to just get the list of keys that don't match too:
mismatch_keys = [key for key in x if not key in y or x[key] != y[key]]
match = not bool(mismatch_keys) #If the list is not empty, they don't match
for key in mismatch_keys:
print key
print '%s -> %s' % (dict1[key],dict2[key])
The only other optimization I can think of might be to use "len(dict)" to figure out which dict has fewer entries and loop through that one first to have the shortest loop possible.
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
There are a bunch of resources out there:
Plugins with ThemeRoller support:
UPDATE: Here is something I put together that will style the table:
<script type="text/javascript">
(function ($) {
$.fn.styleTable = function (options) {
var defaults = {
css: 'styleTable'
};
options = $.extend(defaults, options);
return this.each(function () {
input = $(this);
input.addClass(options.css);
input.find("tr").live('mouseover mouseout', function (event) {
if (event.type == 'mouseover') {
$(this).children("td").addClass("ui-state-hover");
} else {
$(this).children("td").removeClass("ui-state-hover");
}
});
input.find("th").addClass("ui-state-default");
input.find("td").addClass("ui-widget-content");
input.find("tr").each(function () {
$(this).children("td:not(:first)").addClass("first");
$(this).children("th:not(:first)").addClass("first");
});
});
};
})(jQuery);
$(document).ready(function () {
$("#Table1").styleTable();
});
</script>
<table id="Table1" class="full">
<tr>
<th>one</th>
<th>two</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
The CSS:
.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
$('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
$('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>
You have to add Imports System.Runtime.InteropServices
to the top of your source file.
Alternatively, you can fully qualify attribute name:
<System.Runtime.InteropService.DllImport("user32.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _
The boolean value for NO
in Swift is false
.
button.isEnabled = false
should do it.
Here is the Swift documentation for UIControl
's isEnabled
property.
\begingroup
\fontsize{10pt}{12pt}\selectfont
\begin{verbatim}
% how to set font size here to 10 px ?
\end{verbatim}
\endgroup
If you're OK with a JavaScript solution, there's a jQuery plug-in to do this in a cross-browser fashion - see http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/
use the 'web server for chrome app'. (you actually have it on your pc, wether you know or not. just search it in cortana!). open it and click 'choose file' choose the folder with your file in it. do not actually select your file. select your files folder then click on the link(s) under the 'choose folder' button.
if it doesnt take you to the file, then add the name of the file to the urs. like this:
https://127.0.0.1:8887/fileName.txt
link to web server for chrome: click me
If you are going to trust a sub-domain, for example, aaa.localhost,
Please don't do it like mkcert localhost *.localhost 127.0.0.1
, this will not work since some browser doesn't accept wildcard subdomain.
Maybe try mkcert localhost aaa.localhost 127.0.0.1
.
WebClient client = new WebClient();
using (Stream data = client.OpenRead(Text))
{
using (StreamReader reader = new StreamReader(data))
{
string content = reader.ReadToEnd();
string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
MatchCollection matches = Regex.Matches(content,pattern);
List<string> urls = new List<string>();
foreach (Match match in matches)
{
urls.Add(match.Value);
}
}
It is not a valid answer as it gives following error
Cannot find table 0.
Use the following statement instead
if (ds.Tables.Count == 0)
{
//DataSet is empty
}
If you have empty rows, not NAs, you can do:
data[!apply(data == "", 1, all),]
To remove both (NAs and empty):
data <- data[!apply(is.na(data) | data == "", 1, all),]
Adapted from the previous answer:
public static String execCmdSync(String cmd, CmdExecResult callback) throws java.io.IOException, InterruptedException {
RLog.i(TAG, "Running command:", cmd);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
//String[] commands = {"system.exe", "-get t"};
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
StringBuffer stdOut = new StringBuffer();
StringBuffer errOut = new StringBuffer();
// Read the output from the command:
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
stdOut.append(s);
}
// Read any errors from the attempted command:
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
errOut.append(s);
}
if (callback == null) {
return stdInput.toString();
}
int exitVal = proc.waitFor();
callback.onComplete(exitVal == 0, exitVal, errOut.toString(), stdOut.toString(), cmd);
return stdInput.toString();
}
public interface CmdExecResult{
void onComplete(boolean success, int exitVal, String error, String output, String originalCmd);
}
How about something like Arrays.asList(String.split(" ")).contains("xx")
?
See String.split() and How can I test if an array contains a certain value.
There is no block comment on shell script.
Using vi
(yes, vi
) you can easily comment from line n to m
<ESC>
:10,100s/^/#/
(that reads, from line 10 to 100 substitute line start (^) with a # sign.)
and un comment with
<ESC>
:10,100s/^#//
(that reads, from line 10 to 100 substitute line start (^) followed by # with noting //.)
vi
is almost universal anywhere where there is /bin/sh
.
There are no pointers in Java. However, every variable that "contains" an object is a reference to that object. To have output parameters, you would have to use objects. In your case, Integer objects.
So you would have to make an object which contains an integer, and change that integer. You can not use the Integer class, since it is immutable (i.e. its value cannot be changed).
An alternative is to let the method return an array or pair of ints.
From the Android documentation:
The recommended way to develop an Android application is to use Eclipse with the ADT plugin... However, if you'd rather develop your application in another IDE, such as IntelliJ, or in a basic editor, such as Emacs, you can do that instead.
Currently, there are plug-ins for IntelliJ IDEA and NetBeans, but you can still use the tools in /tools to build, debug, monitor, measure and start the emulator.
update ubuntu:
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
Install rvm, which manages the ruby versions:
to install rvm use the following command.
\curl -sSL https://get.rvm.io | bash -s stable
source ~/.bash_profile
rvm install ruby-2.1.4
Check ruby versions installed and in use:
rvm list
rvm use --default ruby-2.1.4
After heavy testing we came to the conclusion that GROUP BY is faster
SELECT sql_no_cache
opnamegroep_intern
FROM telwerken
WHERE opnemergroep
IN (7,8,9,10,11,12,13) group by opnamegroep_intern
635 totaal 0.0944 seconds Weergave van records 0 - 29 ( 635 totaal, query duurde 0.0484 sec)
SELECT sql_no_cache
distinct (opnamegroep_intern)
FROM telwerken
WHERE opnemergroep
IN (7,8,9,10,11,12,13)
635 totaal 0.2117 seconds ( almost 100% slower ) Weergave van records 0 - 29 ( 635 totaal, query duurde 0.3468 sec)
I got same problem but different reason. I had "reg.bat" in the current directory. Renaming that into anything else solved the issue.
Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.
If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow
How to convert <select> dropdown into an unordered list using jquery?
Use the following coding construct to handle exceptions
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
//Handle exception
}
The increasingly popular D3 library handles the oddities of appending/manipulating svg very nicely. You may want to consider using it as opposed to the jQuery hacks mentioned here.
HTML
<svg xmlns="http://www.w3.org/2000/svg"></svg>
Javascript
var circle = d3.select("svg").append("circle")
.attr("r", "10")
.attr("style", "fill:white;stroke:black;stroke-width:5");
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
To open the dedicated ‘Console’ panel, either:
press
the ‘Console’ tab.Please refer here
This code worked for me
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserDetail>()
.HasRequired(d => d.User)
.WithOptional(u => u.UserDetail)
.WillCascadeOnDelete(true);
}
The migration code was:
public override void Up()
{
AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
}
And it worked fine. When I first used
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
The migration code was:
AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true);
but it does not match any of the two overloads available (in EntityFramework 6)
What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.
// new answer
function justTesting() {
return new Promise((resolve, reject) => {
if (true) {
return resolve("testing");
} else {
return reject("promise failed");
}
});
}
justTesting()
.then(res => {
let test = res;
// do something with the output :)
})
.catch(err => {
console.log(err);
});
Hope this helps!
// old answer
function justTesting() {
return promise.then(function(output) {
return output + 1;
});
}
justTesting().then((res) => {
var test = res;
// do something with the output :)
}
Timings for Python 3.6 for extracting the second element from a 2-tuple list.
Also, added numpy
array method, which is simpler to read (but arguably simpler than the list comprehension).
from operator import itemgetter
elements = [(1,1) for _ in range(100000)]
%timeit second = [x[1] for x in elements]
%timeit second = list(map(itemgetter(1), elements))
%timeit second = dict(elements).values()
%timeit second = list(zip(*elements))[1]
%timeit second = np.array(elements)[:,1]
and the timings:
list comprehension: 4.73 ms ± 206 µs per loop
list(map): 5.3 ms ± 167 µs per loop
dict: 2.25 ms ± 103 µs per loop
list(zip) 5.2 ms ± 252 µs per loop
numpy array: 28.7 ms ± 1.88 ms per loop
Note that map()
and zip()
do not return a list anymore, hence the explicit conversion.
Try this out: its in Kotlin
//button from xml
button.setOnClickListener{
val new=addText.text.toString()//addText is an EditText
if(new=isNotEmpty())
{
//do something
}
else{
new.setError("Enter some msg")
//or
Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
}
}
Thank you
v2.0.0 of cordova-check-plugins enables you to remove all plugins in a project:
$ npm install -g cordova-check-plugins
$ cordova-check-plugins --remove-all
It will attempt to use the Cordova CLI to remove each plugin, but if this fails it will force removal of the plugin from platforms/
and plugins/
.
If you also want to remove from config.xml, use:
$ cordova-check-plugins --remove-all --save
Disclaimer: I am the author of cordova-check-plugins
As to why, no idea.
A reset will most certainly fix this:
ul { margin: 0; padding: 0; }
import java.util.Scanner;
public class FarenheitToCelsius{
public static void main(String[]args){
Scanner input= new Scanner(System.in);
System.out.println("Enter Degree in Farenheit:");
double Farenheit=input.nextDouble();
//convert farenheit to celsius
double celsuis=(5.0/9)*(farenheit 32);
system.out.println("Farenheit"+farenheit+"is"+celsius+"in celsius")
{
I had the same problem and resolved by pressing Ctrl + R , Ctrl + W.
Execute:
$ export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-3.b16.el6_9.x86_64
and set operating system environment:
vi /etc/environment
Then follow these steps:
Paste
JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-3.b16.el6_9.x86_64
Press esc
Everything that you need to run Docker on Linux Ubuntu/Mint:
sudo apt-get -y install lxc
sudo gpasswd -a ${USER} docker
newgrp docker
sudo service docker restart
Optionally, you may need to install two additional dependencies if the above doesn't work:
sudo apt-get -y install apparmor cgroup-lite
sudo service docker restart
There are two kinds of reflection
swimming around.
template-tricks
. Use boost::type_traits
for many things (like checking whether a type is integral). For checking for the existance of a member function, use Is it possible to write a template to check for a function's existence? . For checking whether a certain nested type exists, use plain SFINAE . If you are rather looking for ways to accomplish 1), like looking how many methods a class has, or like getting the string representation of a class id, then i'm afraid there is no Standard C++ way of doing this. You have to use either
C++ is made with speed in mind. If you want high-level inspection, like C# or Java has, then I'm afraid i have to tell you there is no way without some effort.
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
I ran into this on my Mac using the MacPorts vim with +python. Problem was that the MacPorts vim will only bind to python 2.5 with +python, while my extensions were installed under python 2.7. Installing the extensions using pip-2.5 solved it.
You would want to replace all spaces with
(non-breaking space) and all new lines \n
with <br>
(line break in html). This should achieve the result you're looking for.
body = body.replace(' ', ' ').replace('\n', '<br>');
Something of that nature.
Share application with title is you app_name, content is your application link
private static void shareApp(Context context) {
final String appPackageName = BuildConfig.APPLICATION_ID;
final String appName = context.getString(R.string.app_name);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareBodyText = "https://play.google.com/store/apps/details?id=" +
appPackageName;
shareIntent.putExtra(Intent.EXTRA_SUBJECT, appName);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string
.share_with)));
}
<table style="border: 1px solid red">
<thead>
<tr>
<td>Header stays put, no scrolling</td>
</tr>
</thead>
<tbody id="tbodyMain" style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
<tr>
<td>cell 1/1</td>
<td>cell 1/2</td>
</tr>
<tr>
<td>cell 2/1</td>
<td>cell 2/2</td>
</tr>
<tr>
<td>cell 3/1</td>
<td>cell 3/2</td>
</tr>
</tbody>
</table>
Javascript Section
<script>
$(document).ready(function(){
var maxHeight = Math.max.apply(null, $("body").map(function () { return $(this).height(); }).get());
// alert(maxHeight);
var borderheight =3 ;
// Added some pixed into maxheight
// If you set border then need to add this "borderheight" to maxheight varialbe
$("#tbodyMain").css("min-height", parseInt(maxHeight + borderheight) + "px");
});
</script>
please, refer How to set maximum possible height to your Table Body
Fiddle Here
What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.
On a rooted device, you may be able to bypass the message using either
the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup>
is set to any value but "mifareclassic" or "all". For instance, you could use:
<CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet>
that already exists in that file).
Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).
This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode
) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
.
If the string you are operating on is very long, or you are operating on many strings, then it could be worthwhile using a java.util.regex.Matcher (this requires time up-front to compile, so it won't be efficient if your input is very small or your search pattern changes frequently).
Below is a full example, based on a list of tokens taken from a map. (Uses StringUtils from Apache Commons Lang).
Map<String,String> tokens = new HashMap<String,String>();
tokens.put("cat", "Garfield");
tokens.put("beverage", "coffee");
String template = "%cat% really needs some %beverage%.";
// Create pattern of the format "%(cat|beverage)%"
String patternString = "%(" + StringUtils.join(tokens.keySet(), "|") + ")%";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(template);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, tokens.get(matcher.group(1)));
}
matcher.appendTail(sb);
System.out.println(sb.toString());
Once the regular expression is compiled, scanning the input string is generally very quick (although if your regular expression is complex or involves backtracking then you would still need to benchmark in order to confirm this!)
Old question but I had similar issue and I solved it by adding
extern void* memset(void*, int, size_t);
or just
extern void* memset();
at the top of translation unit ( *.c file ).
With Python 3.2 and later, you can use int.to_bytes
and int.from_bytes
: https://docs.python.org/3/library/stdtypes.html#int.to_bytes
C++20 will add constexpr
strings and vectors
The following proposal has been accepted apparently: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0980r0.pdf and it adds constructors such as:
// 20.3.2.2, construct/copy/destroy
constexpr
basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { }
constexpr
explicit basic_string(const Allocator& a) noexcept;
constexpr
basic_string(const basic_string& str);
constexpr
basic_string(basic_string&& str) noexcept;
in addition to constexpr versions of all / most methods.
There is no support as of GCC 9.1.0, the following fails to compile:
#include <string>
int main() {
constexpr std::string s("abc");
}
with:
g++-9 -std=c++2a main.cpp
with error:
error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not literal
std::vector
discussed at: Cannot create constexpr std::vector
Tested in Ubuntu 19.04.
echo "$(basename "`test -L ${BASH_SOURCE[0]} \
&& readlink ${BASH_SOURCE[0]} \
|| echo ${BASH_SOURCE[0]}`")"
You can add header "Content-Type: text/html; charset=UTF-8" to your message body.
$headers = "Content-Type: text/html; charset=UTF-8";
If you use native mail()
function $headers array will be the 4th parameter
mail($to, $subject, $message, $headers)
If you user PEAR Mail::factory() code will be:
$smtp = Mail::factory('smtp', $params);
$mail = $smtp->send($to, $headers, $body);
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
You'd better go with something like this. Just give an id to the div which you want to hide and make a function like this. call this function by adding onclick event on body.
function myFunction(event) {
if(event.target.id!="target_id")
{
document.getElementById("target_id").style.display="none";
}
}
running the following command helps me running https web-page, with iframe which has ws (unsecured) connection
chrome.exe --user-data-dir=c:\temp-chrome --disable-web-security --allow-running-insecure-content
You could also use a regular expression:
/[?&]q=/.test(location.search)
If you are on linux (as windows does not support calling select on files) you can use the subprocess module along with the select module.
import time
import subprocess
import select
f = subprocess.Popen(['tail','-F',filename],\
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p = select.poll()
p.register(f.stdout)
while True:
if p.poll(1):
print f.stdout.readline()
time.sleep(1)
This polls the output pipe for new data and prints it when it is available. Normally the time.sleep(1)
and print f.stdout.readline()
would be replaced with useful code.
You can use the subprocess module without the extra select module calls.
import subprocess
f = subprocess.Popen(['tail','-F',filename],\
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while True:
line = f.stdout.readline()
print line
This will also print new lines as they are added, but it will block until the tail program is closed, probably with f.kill()
.
I "Set as Startup Project" the unloaded/unfound library/project.
Then deployed it.
It worked!
I think it couldn't found the .dll because it was not in the assembly at first.
It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {}
but your JSON actually starts with square brackets []
designating an array.
What you actually have is a List<product>
To describe generic types, due to Java's type erasure, you must use a TypeReference
. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});
A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception
which saves you all the useless catch
blocks.
quite possibly the simplest method ...
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
One probably crazy idea or patch :
Just toggle the flag of network reachability
This is code which I use to toggle my flag runtime by triggering 'Simulator Memory Warning' and its COMPLETELY SAFE, just make sure code should be in DEBUG Mode only
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
#ifdef DEBUG
isInternetAvailable = !isInternetAvailable;
#endif
}
This's weird!
I tested the solutions both sizeThatFits:
and [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"]
are NOT working for me.
However, I found an interesting easy way to get the right height of webpage content. Currently, I used it in my delegate method scrollViewDidScroll:
.
CGFloat contentHeight = scrollView.contentSize.height - CGRectGetHeight(scrollView.frame);
Verified in iOS 9.3 Simulator/Device, good luck!
EDIT:
Background: The html content is calculated by my string variable and HTTP content template, loaded by method loadHTMLString:baseURL:
, no registered JS scripts there.
I also had to do this myself. I did it via the --parents argument for cp:
find SOURCEPATH -name filename*.txt -exec cp --parents {} DESTPATH \;
[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]
You can do
result = {'a': 'b'}
return jsonify(result), 201
if you want to return a JSON data in the response along with the error code You can read about responses here and here for make_response API details
Running after the page load should partially be satisfied by setting an event listener to the window load event
window.addEventListener("load",function()...)
Inside the module.run(function()...)
of angular you will have all access to the module structure and dependencies.
You can broadcast
and emit
events for communications bridges.
For example:
All the existing answers only work from the sqlite command line, which isn't ideal if you'd like to build a reusable script. Python makes it easy to build a script that can be executed programatically.
import pandas as pd
import sqlite3
conn = sqlite3.connect('your_cool_database.sqlite')
df = pd.read_sql('SELECT * from orders', conn)
df.to_csv('orders.csv', index = False)
You can customize the query to only export part of the sqlite table to the CSV file.
You can also run a single command to export all sqlite tables to CSV files:
for table in c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
t = table[0]
df = pd.read_sql('SELECT * from ' + t, conn)
df.to_csv(t + '_one_command.csv', index = False)
See here for more info.
I attended a coursera course, there was lesson in which, we were taught about design recipe.
Below docstring format I found preety useful.
def area(base, height): '''(number, number ) -> number #**TypeContract** Return the area of a tring with dimensions base #**Description** and height >>>area(10,5) #**Example ** 25.0 >>area(2.5,3) 3.75 ''' return (base * height) /2
I think if docstrings are written in this way, it might help a lot to developers.
Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI
I think below approach will solve the conversion without taking time-zone into consideration. Please comment if it has any pitfalls.
LocalDateTime datetime //input
public static final DateTimeFormatter yyyyMMddHHmmss_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = datetime.format(yyyyMMddHHmmss_DATE_FORMAT);
Date outputDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(formatDateTime); //output
First option (bad because of throw-catch, but MS will do work for you):
bool IsValidEmail(string email)
{
try {
var mail = new System.Net.Mail.MailAddress(email);
return true;
}
catch {
return false;
}
}
Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
This is how i solve it.:
items: [
{ title: 'Dashboard', icon: require('@/assets/icons/sidebar/dashboard.svg') },
{ title: 'Projects', icon: require('@/assets/icons/sidebar/projects.svg') },
{ title: 'Clients', icon: require('@/assets/icons/sidebar/clients.svg') },
],
And on the template part:
<img :src="item.icon" />
Accepted answer is not the best in all cases because sometimes you want to perserve classes of options and different arguments (for example data-foo).
My solution is:
var sel = $('#select_id');
var selected = sel.val(); // cache selected value, before reordering
var opts_list = sel.find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
sel.html('').append(opts_list);
sel.val(selected); // set cached selected value
//For ie11 or those who get a blank options, replace html('') empty()
One-hot encoding requires bit more than converting the values to indicator variables. Typically ML process requires you to apply this coding several times to validation or test data sets and applying the model you construct to real-time observed data. You should store the mapping (transform) that was used to construct the model. A good solution would use the DictVectorizer
or LabelEncoder
(followed by get_dummies
. Here is a function that you can use:
def oneHotEncode2(df, le_dict = {}):
if not le_dict:
columnsToEncode = list(df.select_dtypes(include=['category','object']))
train = True;
else:
columnsToEncode = le_dict.keys()
train = False;
for feature in columnsToEncode:
if train:
le_dict[feature] = LabelEncoder()
try:
if train:
df[feature] = le_dict[feature].fit_transform(df[feature])
else:
df[feature] = le_dict[feature].transform(df[feature])
df = pd.concat([df,
pd.get_dummies(df[feature]).rename(columns=lambda x: feature + '_' + str(x))], axis=1)
df = df.drop(feature, axis=1)
except:
print('Error encoding '+feature)
#df[feature] = df[feature].convert_objects(convert_numeric='force')
df[feature] = df[feature].apply(pd.to_numeric, errors='coerce')
return (df, le_dict)
This works on a pandas dataframe and for each column of the dataframe it creates and returns a mapping back. So you would call it like this:
train_data, le_dict = oneHotEncode2(train_data)
Then on the test data, the call is made by passing the dictionary returned back from training:
test_data, _ = oneHotEncode2(test_data, le_dict)
An equivalent method is to use DictVectorizer
. A related post on the same is on my blog. I mention it here since it provides some reasoning behind this approach over simply using get_dummies post (disclosure: this is my own blog).
I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress
P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.
Add a <version>
element after the <plugin>
<artifactId>
in your pom.xml
file. Find the following text:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
Add the version tag to it:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
The warning should be resolved.
Regarding this:
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing
Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version>
tag as shown above.
To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---
Take that version number (as in the 2.3.2
above) and add it to your POM, as shown.
It might be worth adding here there are a few pointers when using the @ you should be aware of, for a complete run down view this post: http://mstd.eu/index.php/2016/06/30/php-rapid-fire-what-is-the-symbol-used-for-in-php/
The error handler is still fired even with the @ symbol prepended, it just means a error level of 0 is set, this will have to be handled appropriately in a custom error handler.
Prepending a include with @ will set all errors in the include file to an error level of 0
check if you have installed all the add-ons that are necessary. Also I recommend you to use a real android phone for debugging. It's better, It's real and faster.
If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306
- you provided 3360
. The 3306
is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect()
is the port, which is where it should be specified.
You could just remove the port specification altogether, as you're using the default port, making it
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'test_db13';
References
Also, using the StringBuilder.AppendLine method.
This will be a simple command for this
nodemon --exec npm start
You're using splice
in a wrong way.
The overloads are:
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, itemForInsertAfterDeletion1, itemForInsertAfterDeletion2, ...)
Start means the index that you want to start, not the element you want to remove. And you should pass the second parameter deleteCount
as 1, which means: "I want to delete 1 element starting at the index {start}".
So you better go with:
deleteEvent: function(event) {
this.events.splice(this.events.indexOf(event), 1);
}
Also, you're using a parameter, so you access it directly, not with this.event
.
But in this way you will look up unnecessary for the indexOf
in every delete, for solving this you can define the index
variable at your v-for
, and then pass it instead of the event object.
That is:
v-for="(event, index) in events"
...
<button ... @click="deleteEvent(index)"
And:
deleteEvent: function(index) {
this.events.splice(index, 1);
}
@paweloque For Comparing two Map Objects in java, you can add the keys of a map to list and with those 2 lists you can use the methods retainAll() and removeAll() and add them to another common keys list and different keys list. Using the keys of the common list and different list you can iterate through map, using equals you can compare the maps.
The below code will give output like this:
Before {zoo=barbar, foo=barbar}
After {zoo=barbar, foo=barbar}
Equal: Before- barbar After- barbar
Equal: Before- barbar After- barbar
package com.demo.compareExample
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
public class Demo
{
public static void main(String[] args)
{
Map<String, String> beforeMap = new HashMap<String, String>();
beforeMap.put("foo", "bar"+"bar");
beforeMap.put("zoo", "bar"+"bar");
Map<String, String> afterMap = new HashMap<String, String>();
afterMap.put(new String("foo"), "bar"+"bar");
afterMap.put(new String("zoo"), "bar"+"bar");
System.out.println("Before "+beforeMap);
System.out.println("After "+afterMap);
List<String> beforeList = getAllKeys(beforeMap);
List<String> afterList = getAllKeys(afterMap);
List<String> commonList1 = beforeList;
List<String> commonList2 = afterList;
List<String> diffList1 = getAllKeys(beforeMap);
List<String> diffList2 = getAllKeys(afterMap);
commonList1.retainAll(afterList);
commonList2.retainAll(beforeList);
diffList1.removeAll(commonList1);
diffList2.removeAll(commonList2);
if(commonList1!=null & commonList2!=null) // athough both the size are same
{
for (int i = 0; i < commonList1.size(); i++)
{
if ((beforeMap.get(commonList1.get(i))).equals(afterMap.get(commonList1.get(i))))
{
System.out.println("Equal: Before- "+ beforeMap.get(commonList1.get(i))+" After- "+afterMap.get(commonList1.get(i)));
}
else
{
System.out.println("Unequal: Before- "+ beforeMap.get(commonList1.get(i))+" After- "+afterMap.get(commonList1.get(i)));
}
}
}
if (CollectionUtils.isNotEmpty(diffList1))
{
for (int i = 0; i < diffList1.size(); i++)
{
System.out.println("Values present only in before map: "+beforeMap.get(diffList1.get(i)));
}
}
if (CollectionUtils.isNotEmpty(diffList2))
{
for (int i = 0; i < diffList2.size(); i++)
{
System.out.println("Values present only in after map: "+afterMap.get(diffList2.get(i)));
}
}
}
/**getAllKeys API adds the keys of the map to a list */
private static List<String> getAllKeys(Map<String, String> map1)
{
List<String> key = new ArrayList<String>();
if (map1 != null)
{
Iterator<String> mapIterator = map1.keySet().iterator();
while (mapIterator.hasNext())
{
key.add(mapIterator.next());
}
}
return key;
}
}
I realize this question was asked nearly 7 years ago but it's still a top Google search result for certain keywords regarding importing excel data with C#, so I wanted to provide an alternative based on some recent tech developments.
Importing Excel data has become such a common task to my everyday duties, that I've streamlined the process and documented the method on my blog: best way to read excel file in c#.
I use NPOI because it can read/write Excel files without Microsoft Office installed and it doesn't use COM+ or any interops. That means it can work in the cloud!
But the real magic comes from pairing up with NPOI Mapper from Donny Tian because it allows me to map the Excel columns to properties in my C# classes without writing any code. It's beautiful.
Here is the basic idea:
I create a .net class that matches/maps the Excel columns I'm interested in:
class CustomExcelFormat
{
[Column("District")]
public int District { get; set; }
[Column("DM")]
public string FullName { get; set; }
[Column("Email Address")]
public string EmailAddress { get; set; }
[Column("Username")]
public string Username { get; set; }
public string FirstName
{
get
{
return Username.Split('.')[0];
}
}
public string LastName
{
get
{
return Username.Split('.')[1];
}
}
}
Notice, it allows me to map based on column name if I want to!
Then when I process the excel file all I need to do is something like this:
public void Execute(string localPath, int sheetIndex)
{
IWorkbook workbook;
using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
{
workbook = WorkbookFactory.Create(file);
}
var importer = new Mapper(workbook);
var items = importer.Take<CustomExcelFormat>(sheetIndex);
foreach(var item in items)
{
var row = item.Value;
if (string.IsNullOrEmpty(row.EmailAddress))
continue;
UpdateUser(row);
}
DataContext.SaveChanges();
}
Now, admittedly, my code does not modify the Excel file itself. I am instead saving the data to a database using Entity Framework (that's why you see "UpdateUser" and "SaveChanges" in my example). But there is already a good discussion on SO about how to save/modify a file using NPOI.
To do this, you simple need to add a border-top
or border-bottom
to your <hr/>
tag as the following:
<hr style="border-top: 2px dotted navy" />
with any line type or color you want
You can do this dynamically that way:
mkdir($dirname);
@touch($dirname . "/.htaccess");
$f = fopen($dirname . "/.htaccess", "w");
fwrite($f, "deny from all");
fclose($f);
This will get you all the user created tables:
select * from sysobjects where xtype='U'
To get the cols:
Select * from Information_Schema.Columns Where Table_Name = 'Insert Table Name Here'
Also, I find http://www.sqlservercentral.com/ to be a pretty good db resource.
var jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07", "postalCode": "75007", "countryCode": "FRA", "countryLabel": "France" };
document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);
In case of displaying in HTML, you should to add a balise <pre></pre>
document.getElementById("result-after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, 2) +"</pre>"
Example:
var jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07", "postalCode": "75007", "countryCode": "FRA", "countryLabel": "France" };_x000D_
_x000D_
document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);_x000D_
_x000D_
document.getElementById("result-after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, 2) +"</pre>"
_x000D_
div { float:left; clear:both; margin: 1em 0; }
_x000D_
<div id="result-before"></div>_x000D_
<div id="result-after"></div>
_x000D_
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
I needed something I could run as one command, instead of having to write docker ps
and copying over each Container ID and running the command multiple times. I've adapted BMitch's answer and thought I'd share in case someone else may find this useful.
Mixing xargs
seems to pull off what I need here:
docker ps --format='{{.ID}}' | \
xargs -I {} sh -c 'echo > $(docker inspect --format="{{.LogPath}}" {})'
This grabs each Container ID listed by docker ps
(will erase your logs for any container on that list!), pipes it into xargs
and then echoes a blank string to replace the log path of the container.
You should use <h:panelGroup ...>
tag with attribute rendered
. If you set true
to rendered, the content of <h:panelGroup ...>
won't be shown. Your XHTML file should have something like this:
<h:panelGroup rendered="#{userBean.showPassword}">
<h:outputText id="password" value="#{userBean.password}"/>
</h:panelGroup>
UserBean.java:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean implements Serializable{
private boolean showPassword = false;
private String password = "";
public boolean isShowPassword(){
return showPassword;
}
public void setPassword(password){
this.password = password;
}
public String getPassword(){
return this.password;
}
}
Further to Sean's post, it isn't necessary to nest the using statements. By using
the StreamWriter it will be flushed and closed at the end of the block so no need to explicitly call the Flush()
and Close()
methods:
var request = (HttpWebRequest)WebRequest.Create("http://url");
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
user = "Foo",
password = "Baz"
});
streamWriter.Write(json);
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
This other solution for covert datetime to unixtimestampmillis C#.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}