Proper use of 'yield return'
And what about this?
public static IEnumerable<Product> GetAllProducts()
{
using (AdventureWorksEntities db = new AdventureWorksEntities())
{
var products = from product in db.Product
select product;
return products.ToList();
}
}
I guess this is much cleaner. I do not have VS2008 at hand to check, though.
In any case, if Products implements IEnumerable (as it seems to - it is used in a foreach statement), I'd return it directly.
IIS error, Unable to start debugging on the webserver
Just to add in my 2 cents.
Recently I installed docker for another project and this was causing a project running on IIS Express
to generate the error “The specified port is in use”. To solve this I did a few things, but namely I executed this command:
netsh http add iplisten ipaddress=::
This commands breaks down sites running on IIS Local
, so if you executed this command you can make your IIS Local
sites working again by executing the following which undoes the previous command:
netsh http delete iplisten ipaddress=::
Post a json object to mvc controller with jquery and ajax
What am I doing incorrectly?
You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.
How can I receive a json object in the controller?
View:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>
var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });
<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>
Controller:
public void PostRawJson(string json)
{
var order = System.Web.Helpers.Json.Decode(json);
var orderDate = order.OrderDate;
var secondOrderId = order.Item[1].Id;
}
Python: tf-idf-cosine: to find document similarity
Let me give you another tutorial written by me. It answers your question, but also makes an explanation why we are doing some of the things. I also tried to make it concise.
So you have a list_of_documents
which is just an array of strings and another document
which is just a string. You need to find such document from the list_of_documents
that is the most similar to document
.
Let's combine them together: documents = list_of_documents + [document]
Let's start with dependencies. It will become clear why we use each of them.
from nltk.corpus import stopwords
import string
from nltk.tokenize import wordpunct_tokenize as tokenize
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.spatial.distance import cosine
One of the approaches that can be uses is a bag-of-words approach, where we treat each word in the document independent of others and just throw all of them together in the big bag. From one point of view, it looses a lot of information (like how the words are connected), but from another point of view it makes the model simple.
In English and in any other human language there are a lot of "useless" words like 'a', 'the', 'in' which are so common that they do not possess a lot of meaning. They are called stop words and it is a good idea to remove them. Another thing that one can notice is that words like 'analyze', 'analyzer', 'analysis' are really similar. They have a common root and all can be converted to just one word. This process is called stemming and there exist different stemmers which differ in speed, aggressiveness and so on. So we transform each of the documents to list of stems of words without stop words. Also we discard all the punctuation.
porter = PorterStemmer()
stop_words = set(stopwords.words('english'))
modified_arr = [[porter.stem(i.lower()) for i in tokenize(d.translate(None, string.punctuation)) if i.lower() not in stop_words] for d in documents]
So how will this bag of words help us? Imagine we have 3 bags: [a, b, c]
, [a, c, a]
and [b, c, d]
. We can convert them to vectors in the basis [a, b, c, d]
. So we end up with vectors: [1, 1, 1, 0]
, [2, 0, 1, 0]
and [0, 1, 1, 1]
. The similar thing is with our documents (only the vectors will be way to longer). Now we see that we removed a lot of words and stemmed other also to decrease the dimensions of the vectors. Here there is just interesting observation. Longer documents will have way more positive elements than shorter, that's why it is nice to normalize the vector. This is called term frequency TF, people also used additional information about how often the word is used in other documents - inverse document frequency IDF. Together we have a metric TF-IDF which have a couple of flavors. This can be achieved with one line in sklearn :-)
modified_doc = [' '.join(i) for i in modified_arr] # this is only to convert our list of lists to list of strings that vectorizer uses.
tf_idf = TfidfVectorizer().fit_transform(modified_doc)
Actually vectorizer allows to do a lot of things like removing stop words and lowercasing. I have done them in a separate step only because sklearn does not have non-english stopwords, but nltk has.
So we have all the vectors calculated. The last step is to find which one is the most similar to the last one. There are various ways to achieve that, one of them is Euclidean distance which is not so great for the reason discussed here. Another approach is cosine similarity. We iterate all the documents and calculating cosine similarity between the document and the last one:
l = len(documents) - 1
for i in xrange(l):
minimum = (1, None)
minimum = min((cosine(tf_idf[i].todense(), tf_idf[l + 1].todense()), i), minimum)
print minimum
Now minimum will have information about the best document and its score.
How to add items to a spinner in Android?
For adding item in Spinner, you can do one thing, try to create an adapter and then add/remove items into the adapter, then you can easily bind that adapter to spinner by using setAdapter()
method.
Here is an example:
spinner.setAdapter(adapter);
adapter.add(item1);
adapter.add(item2);
adapter.add(item3);
adapter.add(item4);
adapter.add(item5);
adapter.notifyDataSetChanged();
spinner.setAdapter(adapter);
Aborting a stash pop in Git
I could reproduce clean git stash pop
on "dirty" directory, with uncommitted changes, but not yet pop that generates a merge conflict.
If on merge conflict the stash you tried to apply didn't disappear, you can try to examine git show stash@{0}
(optionally with --ours
or --theirs
) and compare with git statis
and git diff HEAD
. You should be able to see which changes came from applying a stash.
Python Math - TypeError: 'NoneType' object is not subscriptable
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
Is there any way to delete local commits in Mercurial?
I came across this problem too. I made 2 commit
and wanted to rollback and delete both commits.
$ hg rollback
But hg rollback
just rolls back to the last commit, not the 2 commits. At that time I did not realize this and I changed the code.
When I found hg rollback
had just rolled back one commit, I found I could use hg strip #changeset#
. So, I used hg log -l 10
to find the latest 10 commits and get the right changeset I wanted to strip
.
$ hg log -l 10
changeset: 2499:81a7a8f7a5cd
branch: component_engine
tag: tip
user: myname<[email protected]>
date: Fri Aug 14 12:22:02 2015 +0800
summary: get runs from sandbox
changeset: 2498:9e3e1de76127
branch: component_engine
user: other_user_name<[email protected]>
date: Mon Aug 03 09:50:18 2015 +0800
summary: Set current destination to a copy incoming exchange
......
$ hg strip 2499
abort: local changes found
What does abort: local changes found
mean? It means that hg
found changes to the code that haven't been committed yet. So, to solve this, you should hg diff
to save the code you have changed and hg revert
and hg strip #changeset#
. Just like this:
$ hg diff > /PATH/TO/SAVE/YOUR/DIFF/FILE/my.diff
$ hg revert file_you_have_changed
$ hg strip #changeset#
After you have done the above, you can patch
the diff file and your code can be added back to your project.
$ patch -p1 < /PATH/TO/SAVE/YOUR/DIFF/FILE/my.diff
Oracle query to fetch column names
The query to use with Oracle is:
String sqlStr="select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='"+_db+".users' and COLUMN_NAME not in ('password','version','id')"
Never heard of HQL for such queries. I assume it doesn't make sense for ORM implementations to deal with it. ORM is an Object Relational Mapping, and what you're looking for is metadata mapping... You wouldn't use HQL, rather use API methods for this purpose, or direct SQL. For instance, you can use JDBC DatabaseMetaData.
I think tablespace has nothing to do with schema. AFAIK tablespaces are mainly used for logical internal technical purposes which should bother DBAs. For more information regarding tablespaces, see Oracle doc.
How to create exe of a console application
The following steps are necessary to create .exe i.e. executable files which are as
1) Open visual studio framework
2) Then, create a new project or application
3) Build or execute your application by pressing F5
OS X: equivalent of Linux's wget
brew install wget
Homebrew is a package manager for OSX analogous to yum, apt-get, choco, emerge, etc. Be aware that you will also need to install Xcode and the Command Line Tools. Virtually anyone who uses the command line in OSX will want to install these things anyway.
If you can't or don't want to use homebrew, you could also:
Install wget manually:
curl -# "http://ftp.gnu.org/gnu/wget/wget-1.17.1.tar.xz" -o "wget.tar.xz"
tar xf wget.tar.xz
cd wget-1.17.1
./configure --with-ssl=openssl -with-libssl-prefix=/usr/local/ssl && make -j8 && make install
Or, use a bash alias:
function _wget() { curl "${1}" -o $(basename "${1}") ; };
alias wget='_wget'
Android Studio SDK location
create a new folder in your android studio parent directory folder. Name it sdk or whatever you want.
Select that folder from the drop down list when asked.
Thats what solves it for me.
splitting a string into an array in C++ without using vector
Here's a suggestion: use two indices into the string, say start
and end
. start
points to the first character of the next string to extract, end
points to the character after the last one belonging to the next string to extract. start
starts at zero, end
gets the position of the first char after start
. Then you take the string between [start..end)
and add that to your array. You keep going until you hit the end of the string.
how does int main() and void main() work
Neither main()
or void main()
are standard C. The former is allowed as it has an implicit int
return value, making it the same as int main()
. The purpose of main
's return value is to return an exit status to the operating system.
In standard C, the only valid signatures for main
are:
int main(void)
and
int main(int argc, char **argv)
The form you're using: int main()
is an old style declaration that indicates main
takes an unspecified number of arguments. Don't use it - choose one of those above.
Which Architecture patterns are used on Android?
I tried using both the model–view–controller (MVC) and model–view–presenter architectural patterns for doing android development. My findings are model–view–controller works fine, but there are a couple of "issues". It all comes down to how you perceive the Android Activity
class. Is it a controller, or is it a view?
The actual Activity
class doesn't extend Android's View
class, but it does, however, handle displaying a window to the user and also handle the events of that window (onCreate, onPause, etc.).
This means, that when you are using an MVC pattern, your controller will actually be a pseudo view–controller. Since it is handling displaying a window to the user, with the additional view components you have added to it with setContentView, and also handling events for at least the various activity life cycle events.
In MVC, the controller is supposed to be the main entry point. Which is a bit debatable if this is the case when applying it to Android development, since the activity is the natural entry point of most applications.
Because of this, I personally find that the model–view–presenter pattern is a perfect fit for Android development. Since the view's role in this pattern is:
- Serving as a entry point
- Rendering components
- Routing user events to the presenter
This allows you to implement your model like so:
View - this contains your UI components, and handles events for them.
Presenter - this will handle communication between your model and your view, look at it as a gateway to your model. Meaning, if you have a complex domain model representing, God knows what, and your view only needs a very small subset of this model, the presenters job is to query the model and then update the view. For example, if you have a model containing a paragraph of text, a headline and a word-count. But in a given view, you only need to display the headline in the view. Then the presenter will read the data needed from the model, and update the view accordingly.
Model - this should basically be your full domain model. Hopefully it will help making your domain model more "tight" as well, since you won't need special methods to deal with cases as mentioned above.
By decoupling the model from the view all together (through use of the presenter), it also becomes much more intuitive to test your model. You can have unit tests for your domain model, and unit tests for your presenters.
Try it out. I personally find it a great fit for Android development.
Mysql select distinct
You can use DISTINCT
like that
mysql_query("SELECT DISTINCT(ticket_id), column1, column2, column3
FROM temp_tickets
ORDER BY ticket_id");
print call stack in C or C++
You can implement the functionality yourself:
Use a global (string)stack and at start of each function push the function name and such other values (eg parameters) onto this stack; at exit of function pop it again.
Write a function that will printout the stack content when it is called, and use this in the function where you want to see the callstack.
This may sound like a lot of work but is quite useful.
Javascript date regex DD/MM/YYYY
This validates date like dd-mm-yyyy
([0-2][0-9]|(3)[0-1])(\-)(((0)[0-9])|((1)[0-2]))(\-)([0-9][0-9][0-9][0-9])
This can use with javascript like angular reactive forms
Query to get only numbers from a string
With the previous queries I get these results:
'AAAA1234BBBB3333' >>>> Output: 1234
'-çã+0!\aº1234' >>>> Output: 0
The code below returns All numeric chars:
1st output: 12343333
2nd output: 01234
declare @StringAlphaNum varchar(255)
declare @Character varchar
declare @SizeStringAlfaNumerica int
declare @CountCharacter int
set @StringAlphaNum = 'AAAA1234BBBB3333'
set @SizeStringAlfaNumerica = len(@StringAlphaNum)
set @CountCharacter = 1
while isnumeric(@StringAlphaNum) = 0
begin
while @CountCharacter < @SizeStringAlfaNumerica
begin
if substring(@StringAlphaNum,@CountCharacter,1) not like '[0-9]%'
begin
set @Character = substring(@StringAlphaNum,@CountCharacter,1)
set @StringAlphaNum = replace(@StringAlphaNum, @Character, '')
end
set @CountCharacter = @CountCharacter + 1
end
set @CountCharacter = 0
end
select @StringAlphaNum
How to disable scrolling the document body?
The following JavaScript could work:
var page = $doc.getElementsByTagName('body')[0];
To disable Scroll use:
page.classList.add('noscroll');
To enable Scroll use:
page.classList.remove('noscroll');
In the CSS file, add:
.noscroll {
position: fixed!important
}
Set a div width, align div center and text align left
Set auto margins on the inner div:
<div id="header" style="width:864px;">
<div id="centered" style="margin: 0 auto; width:855px;"></div>
</div>
Alternatively, text align center the parent, and force text align left on the inner div:
<div id="header" style="width:864px;text-align: center;">
<div id="centered" style="text-align: left; width:855px;"></div>
</div>
What is the best way to compare floats for almost-equality in Python?
The common wisdom that floating-point numbers cannot be compared for equality is inaccurate. Floating-point numbers are no different from integers: If you evaluate "a == b", you will get true if they are identical numbers and false otherwise (with the understanding that two NaNs are of course not identical numbers).
The actual problem is this: If I have done some calculations and am not sure the two numbers I have to compare are exactly correct, then what? This problem is the same for floating-point as it is for integers. If you evaluate the integer expression "7/3*3", it will not compare equal to "7*3/3".
So suppose we asked "How do I compare integers for equality?" in such a situation. There is no single answer; what you should do depends on the specific situation, notably what sort of errors you have and what you want to achieve.
Here are some possible choices.
If you want to get a "true" result if the mathematically exact numbers would be equal, then you might try to use the properties of the calculations you perform to prove that you get the same errors in the two numbers. If that is feasible, and you compare two numbers that result from expressions that would give equal numbers if computed exactly, then you will get "true" from the comparison. Another approach is that you might analyze the properties of the calculations and prove that the error never exceeds a certain amount, perhaps an absolute amount or an amount relative to one of the inputs or one of the outputs. In that case, you can ask whether the two calculated numbers differ by at most that amount, and return "true" if they are within the interval. If you cannot prove an error bound, you might guess and hope for the best. One way of guessing is to evaluate many random samples and see what sort of distribution you get in the results.
Of course, since we only set the requirement that you get "true" if the mathematically exact results are equal, we left open the possibility that you get "true" even if they are unequal. (In fact, we can satisfy the requirement by always returning "true". This makes the calculation simple but is generally undesirable, so I will discuss improving the situation below.)
If you want to get a "false" result if the mathematically exact numbers would be unequal, you need to prove that your evaluation of the numbers yields different numbers if the mathematically exact numbers would be unequal. This may be impossible for practical purposes in many common situations. So let us consider an alternative.
A useful requirement might be that we get a "false" result if the mathematically exact numbers differ by more than a certain amount. For example, perhaps we are going to calculate where a ball thrown in a computer game traveled, and we want to know whether it struck a bat. In this case, we certainly want to get "true" if the ball strikes the bat, and we want to get "false" if the ball is far from the bat, and we can accept an incorrect "true" answer if the ball in a mathematically exact simulation missed the bat but is within a millimeter of hitting the bat. In that case, we need to prove (or guess/estimate) that our calculation of the ball's position and the bat's position have a combined error of at most one millimeter (for all positions of interest). This would allow us to always return "false" if the ball and bat are more than a millimeter apart, to return "true" if they touch, and to return "true" if they are close enough to be acceptable.
So, how you decide what to return when comparing floating-point numbers depends very much on your specific situation.
As to how you go about proving error bounds for calculations, that can be a complicated subject. Any floating-point implementation using the IEEE 754 standard in round-to-nearest mode returns the floating-point number nearest to the exact result for any basic operation (notably multiplication, division, addition, subtraction, square root). (In case of tie, round so the low bit is even.) (Be particularly careful about square root and division; your language implementation might use methods that do not conform to IEEE 754 for those.) Because of this requirement, we know the error in a single result is at most 1/2 of the value of the least significant bit. (If it were more, the rounding would have gone to a different number that is within 1/2 the value.)
Going on from there gets substantially more complicated; the next step is performing an operation where one of the inputs already has some error. For simple expressions, these errors can be followed through the calculations to reach a bound on the final error. In practice, this is only done in a few situations, such as working on a high-quality mathematics library. And, of course, you need precise control over exactly which operations are performed. High-level languages often give the compiler a lot of slack, so you might not know in which order operations are performed.
There is much more that could be (and is) written about this topic, but I have to stop there. In summary, the answer is: There is no library routine for this comparison because there is no single solution that fits most needs that is worth putting into a library routine. (If comparing with a relative or absolute error interval suffices for you, you can do it simply without a library routine.)
How to disable Excel's automatic cell reference change after copy/paste?
Simple workaround I used just now while in a similar situation:
- Make a duplicate of the worksheet.
- Cut + Paste the cells with formulas from the duplicate worksheet (e.g.
Copy of Sheet1
) into the original worksheet.
- Remove all occurrences of the the duplicate sheet's name from the newly pasted formulas; e.g. find-and-replace all occurrences of the search term
'Copy of Sheet1'!
with an empty string (i.e. blank).
- Delete duplicate worksheet to clean up.
Note: if your sheet name lacks spaces you won't need to use the single quote/apostrophe (').
Your cell references are now copied without being altered.
dplyr mutate with conditional values
It looks like derivedFactor
from the mosaic
package was designed for this. In this example, it would look something like:
library(mosaic)
myfile <- mutate(myfile, V5 = derivedFactor(
"1" = (V1==1 & V2!=4),
"2" = (V2==4 & V3!=1),
.method = "first",
.default = 0
))
(If you want the outcome to be numeric instead of a factor, wrap the derivedFactor
with an as.numeric
.)
Note that the .default
option combined with .method = "first"
sets the "else" condition -- this approach is described in the help file for derivedFactor
.
Python: IndexError: list index out of range
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a
will be generated just once, and if it is in winning_numbers
already, it won't be added. Since the generation of a
is outside the while
(in your code), if a
is already in winning_numbers
then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]
. (Your winning_numbers
isn't always of length 5).
How to increase maximum execution time in php
Use the PHP function
void set_time_limit ( int $seconds )
The maximum execution time, in seconds. If set to zero, no time limit is imposed.
This function has no effect when PHP is running in safe mode. There is
no workaround other than turning off safe mode or changing the time
limit in the php.ini.
Get loop count inside a Python FOR loop
Agree with Nick.
Here is more elaborated code.
#count=0
for idx, item in enumerate(list):
print item
#count +=1
#if count % 10 == 0:
if (idx+1) % 10 == 0:
print 'did ten'
I have commented out the count variable in your code.
How to set the title of UIButton as left alignment?
Set the contentHorizontalAlignment:
emailBtn.contentHorizontalAlignment = .left;
You might also want to adjust the content left inset otherwise the text will touch the left border:
emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
// Swift 3 and up:
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);
android.view.InflateException: Binary XML file: Error inflating class fragment
I also had this issue. I solved it by replacing the import in MainActivity
and NavigationDrawerFragment
From
import android.app.Activity;
import android.app.ActionBar;
To
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
I updated MainActivity
to extends ActionBarActivity
instead of Activity
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks
Also use ActionBar actionBar = getSupportActionBar();
to get the ActionBar
And I updated the following function in NavigationDrawerFragment
private ActionBar getActionBar()
{
return ((ActionBarActivity)getActivity()).getSupportActionBar();
}
disable editing default value of text input
You can either use the readonly
or the disabled
attribute. Note that when disabled, the input's value will not be submitted when submitting the form.
<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">
Get just the filename from a path in a Bash script
Some more alternative options because regexes (regi ?) are awesome!
Here is a Simple regex to do the job:
regex="[^/]*$"
Example (grep):
FP="/hello/world/my/file/path/hello_my_filename.log"
echo $FP | grep -oP "$regex"
#Or using standard input
grep -oP "$regex" <<< $FP
Example (awk):
echo $FP | awk '{match($1, "$regex",a)}END{print a[0]}
#Or using stardard input
awk '{match($1, "$regex",a)}END{print a[0]} <<< $FP
If you need a more complicated regex:
For example your path is wrapped in a string.
StrFP="my string is awesome file: /hello/world/my/file/path/hello_my_filename.log sweet path bro."
#this regex matches a string not containing / and ends with a period
#then at least one word character
#so its useful if you have an extension
regex="[^/]*\.\w{1,}"
#usage
grep -oP "$regex" <<< $StrFP
#alternatively you can get a little more complicated and use lookarounds
#this regex matches a part of a string that starts with / that does not contain a /
##then uses the lazy operator ? to match any character at any amount (as little as possible hence the lazy)
##that is followed by a space
##this allows use to match just a file name in a string with a file path if it has an exntension or not
##also if the path doesnt have file it will match the last directory in the file path
##however this will break if the file path has a space in it.
regex="(?<=/)[^/]*?(?=\s)"
#to fix the above problem you can use sed to remove spaces from the file path only
## as a side note unfortunately sed has limited regex capibility and it must be written out in long hand.
NewStrFP=$(echo $StrFP | sed 's:\(/[a-z]*\)\( \)\([a-z]*/\):\1\3:g')
grep -oP "$regex" <<< $NewStrFP
Total solution with Regexes:
This function can give you the filename with or without extension of a linux filepath even if the filename has multiple "."s in it.
It can also handle spaces in the filepath and if the file path is embedded or wrapped in a string.
#you may notice that the sed replace has gotten really crazy looking
#I just added all of the allowed characters in a linux file path
function Get-FileName(){
local FileString="$1"
local NoExtension="$2"
local FileString=$(echo $FileString | sed 's:\(/[a-zA-Z0-9\<\>\|\\\:\)\(\&\;\,\?\*]*\)\( \)\([a-zA-Z0-9\<\>\|\\\:\)\(\&\;\,\?\*]*/\):\1\3:g')
local regex="(?<=/)[^/]*?(?=\s)"
local FileName=$(echo $FileString | grep -oP "$regex")
if [[ "$NoExtension" != "" ]]; then
sed 's:\.[^\.]*$::g' <<< $FileName
else
echo "$FileName"
fi
}
## call the function with extension
Get-FileName "my string is awesome file: /hel lo/world/my/file test/path/hello_my_filename.log sweet path bro."
##call function without extension
Get-FileName "my string is awesome file: /hel lo/world/my/file test/path/hello_my_filename.log sweet path bro." "1"
If you have to mess with a windows path you can start with this one:
[^\\]*$
How do I use HTML as the view engine in Express?
No view engine is necessary, if you want to use angular with simple plain html file. Here's how to do it:
In your route.js
file:
router.get('/', (req, res) => {
res.sendFile('index.html', {
root: 'yourPathToIndexDirectory'
});
});
How to enable Bootstrap tooltip on disabled button?
You can imitate the effect using CSS3.
Simply take the disabled state off the button and the tooltip doesn't appear anymore.. this is great for validation as the code requires less logic.
I wrote this pen to illustrate.
CSS3 Disabled Tooltips
[disabled] {
&[disabled-tooltip] {
cursor:not-allowed;
position: relative;
&:hover {
&:before {
content:'';
border:5px solid transparent;
border-top:5px solid black;
position: absolute;
left: 50%;
transform: translate(-50%, calc(-100% + -5px));
}
&:after {
content: attr(disabled-tooltip);
position: absolute;
left: 50%;
transform: translate(-50%, calc(-100% + -15px));
width:280px;
background-color:black;
color:white;
border-radius:5px;
padding:8px 12px;
white-space:normal;
line-height:1;
}
}
}
}
<button type="button" class="btn btn-primary" disabled-tooltip="I am a disabled tooltip using CSS3.. You can not click this button." disabled>Primary Button</button>
How to export html table to excel or pdf in php
<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">xxxxx</td>
<td width="700">xxxxxx</td>
<td width="170">xxxxxx</td>
<td width="30">xxxxxx</td>
</tr>
<tr bgcolor="#FFFFFF">
<td><?php
$date = date_create($row_Recordset3['fecha']);
echo date_format($date, 'd-m-Y');
?></td>
<td><?php echo $row_Recordset3['descripcion']; ?></td>
<td><?php echo $row_Recordset3['producto']; ?></td>
<td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
</tr>
</table>
<input type="hidden" id="datatodisplay" name="datatodisplay">
<input type="submit" value="Export to Excel">
exporttable.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
Can I try/catch a warning?
Combining these lines of code around a file_get_contents()
call to an external url helped me handle warnings like "failed to open stream: Connection timed out" much better:
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);
try {
$iResult = file_get_contents($sUrl);
} catch (Exception $e) {
$this->sErrorMsg = $e->getMessage();
}
restore_error_handler();
This solution works within object context, too. You could use it in a function:
public function myContentGetter($sUrl)
{
... code above ...
return $iResult;
}
How to validate a date?
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}
Bootstrap 4 multiselect dropdown
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
Set up Python 3 build system with Sublime Text 3
Steps for configuring Sublime Text Editor3 for Python3 :-
- Go to preferences in the toolbar.
- Select Package Control.
- A pop up will open.
- Type/Select Package Control:Install Package.
- Wait for a minute till repositories are loading.
- Another Pop up will open.
- Search for Python 3.
- Now sublime text is set for Python3.
- Now go to Tools-> Build System.
- Select Python3.
Enjoy Coding.
Exception: "URI formats are not supported"
Try This
ImagePath = "http://localhost/profilepics/abc.png";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
Android: Access child views from a ListView
This assumes you know the position of the element in the ListView :
View element = listView.getListAdapter().getView(position, null, null);
Then you should be able to call getLeft() and getTop() to determine the elements on screen position.
Creating a pandas DataFrame from columns of other DataFrames with similar indexes
What you ask for is the join operation.
With the how
argument, you can define how unique indices are handled.
Here, some article, which looks helpful concerning this point.
In the example below, I left out cosmetics (like renaming columns) for simplicity.
Code
import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )
df3 = df1.join(df2, how='outer', lsuffix='_df1', rsuffix='_df2')
print(df3)
Output
a_df1 b_df1 c_df1 a_df2 b_df2 c_df2
2014-01-01 NaN NaN NaN 0.109898 1.107033 -1.045376
2014-01-02 0.573754 0.169476 -0.580504 -0.664921 -0.364891 -1.215334
2014-01-03 -0.766361 -0.739894 -1.096252 0.962381 -0.860382 -0.703269
2014-01-04 0.083959 -0.123795 -1.405974 1.825832 -0.580343 0.923202
2014-01-05 1.019080 -0.086650 0.126950 -0.021402 -1.686640 0.870779
2014-01-06 -1.036227 -1.103963 -0.821523 -0.943848 -0.905348 0.430739
2014-01-07 NaN NaN NaN 0.312005 0.586585 1.531492
2014-01-08 NaN NaN NaN -0.077951 -1.189960 0.995123
Pass Model To Controller using Jquery/Ajax
As suggested in other answers it's probably easiest to "POST" the form data to the controller. If you need to pass an entire Model/Form you can easily do this with serialize()
e.g.
$('#myform').on('submit', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.post('/student/update', formData, function(response){
//Do something with response
});
});
So your controller could have a view model as the param e.g.
[HttpPost]
public JsonResult Update(StudentViewModel studentViewModel)
{}
Alternatively if you just want to post some specific values you can do:
$('#myform').on('submit', function(e){
e.preventDefault();
var studentId = $(this).find('#Student_StudentId');
var isActive = $(this).find('#Student_IsActive');
$.post('/my/url', {studentId : studentId, isActive : isActive}, function(response){
//Do something with response
});
});
With a controller like:
[HttpPost]
public JsonResult Update(int studentId, bool isActive)
{}
Wordpress - Images not showing up in the Media Library
Did you ever change the directory of your Wordpress install?
I had a problem with not finding my uploaded images after changing the Wordpress location on my server. In Wordpress, I went to Dashboard-> Settings -> Media and changed the uploads folder in the "Store uploads in this folder" field.
Android Writing Logs to text File
After long time of investigation I found that:
android.util.Log
by default use java.util.logging.Logger
- LogCat uses
logger
with name ""
, to get instance of it use LogManager.getLogManager().getLogger("")
- Android Devices adds to LogCat
logger
instance of com.android.internal.logging.AndroidHandler
after run of debug apps
- But!!!
com.android.internal.logging.AndroidHandler
prints messages to logcat only with levels more then java.util.logging.Level.INFO
such as (Level.INFO, Level.WARNING, Level.SEVERE, Level.OFF
)
So to write logs to file just simple to the rootLogger
""
add a java.util.logging.FileHandler
:
class App : Application{
override fun onCreate() {
super.onCreate()
Log.d(TAG, printLoggers("before setup"))
val rootLogger = java.util.logging.LogManager.getLogManager().getLogger("")
val dirFile = destinationFolder
val file = File(dirFile,"logFile.txt")
val handler = java.util.logging.FileHandler(file.absolutePath, 5* 1024 * 1024/*5Mb*/, 1, true)
handler.formatter = AndroidLogFormatter(filePath = file.absolutePath)
rootLogger?.addHandler(handler)
Log.d(TAG, printLoggers("after setup"))
}
}
val destinationFolder: File
get() {
val parent =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absoluteFile
val destinationFolder = File(parent, "MyApp")
if (!destinationFolder.exists()) {
destinationFolder.mkdirs()
destinationFolder.mkdir()
}
return destinationFolder
}
class AndroidLogFormatter(val filePath: String = "", var tagPrefix: String = "") : Formatter() {
override fun format(record: LogRecord): String {
val tag = record.getTag(tagPrefix)
val date = record.getDate()
val level = record.getLogCatLevel()
val message = record.getLogCatMessage()
return "$date $level$tag: $message\n"
}
}
fun LogRecord.getTag(tagPrefix: String): String {
val name = loggerName
val maxLength = 30
val tag = tagPrefix + (if (name.length > maxLength) name.substring(name.length - maxLength) else name)
return tag
}
fun LogRecord.getDate(): String? {
return Date(millis).formatedBy("yyyy-MM-dd HH:mm:ss.SSS")
}
fun Date?.formatedBy(dateFormat: String): String? {
val date = this
date ?: return null
val writeFormat = SimpleDateFormat(dateFormat, Locale.getDefault()) //MM ? HH:mm
return writeFormat.format(date)
}
fun LogRecord.getLogCatMessage(): String {
var message = message
if (thrown != null) {
message += Log.getStackTraceString(thrown)
}
return message
}
fun Int.getAndroidLevel(): Int {
return when {
this >= Level.SEVERE.intValue() -> { // SEVERE
Log.ERROR
}
this >= Level.WARNING.intValue() -> { // WARNING
Log.WARN
}
this >= Level.INFO.intValue() -> { // INFO
Log.INFO
}
else -> {
Log.DEBUG
}
}
}
fun LogRecord.getLogCatLevel(): String {
return when (level.intValue().getAndroidLevel()) {
Log.ERROR -> { // SEVERE
"E/"
}
Log.WARN -> { // WARNING
"W/"
}
Log.INFO -> { // INFO
"I/"
}
Log.DEBUG -> {
"D/"
}
else -> {
"D/"
}
}
}
fun getLoggerLevel(level: Int): Level {
return when (level) {
Log.ERROR -> { // SEVERE
Level.SEVERE
}
Log.WARN -> { // WARNING
Level.WARNING
}
Log.INFO -> { // INFO
Level.INFO
}
Log.DEBUG -> {
Level.FINE
}
else -> {
Level.FINEST
}
}
}
To print all loggers at your app use:
Log.e(TAG, printLoggers("before setup"))
private fun printLoggers(caller: String, printIfEmpty: Boolean = true): String {
val builder = StringBuilder()
val loggerNames = LogManager.getLogManager().loggerNames
builder.appendln("--------------------------------------------------------------")
builder.appendln("printLoggers: $caller")
while (loggerNames.hasMoreElements()) {
val element = loggerNames.nextElement()
val logger = LogManager.getLogManager().getLogger(element)
val parentLogger: Logger? = logger.parent
val handlers = logger.handlers
val level = logger?.level
if (!printIfEmpty && handlers.isEmpty()) {
continue
}
val handlersNames = handlers.map {
val handlerName = it.javaClass.simpleName
val formatter: Formatter? = it.formatter
val formatterName = if (formatter is AndroidLogFormatter) {
"${formatter.javaClass.simpleName}(${formatter.filePath})"
} else {
formatter?.javaClass?.simpleName
}
"$handlerName($formatterName)"
}
builder.appendln("level: $level logger: \"$element\" handlers: $handlersNames parentLogger: ${parentLogger?.name}")
}
builder.appendln("--------------------------------------------------------------")
return builder.toString()
}
Find and replace with a newline in Visual Studio Code
With VS Code release 1.38 you can press CTRL + Enter in the editor find box to add a newline character.
With VS Code release 1.30 you can type Shift
+ Enter
in the search box to add a newline character without needing to use regex mode.
Since VS Code release 1.3, the regex find has supported newline characters. To use this feature set the find window to regex mode and use \n
as the newline character.
How to make a drop down list in yii2?
It Seems there are many good answers for this question .So i will try to give a detailed answer
active form and hardcoded data
<?php
echo $form->field($model, 'name')->dropDownList(['1' => 'Yes', '0' => 'No'],['prompt'=>'Select Option']);
?>
or
<?php
$a= ['1' => 'Yes', '0' => 'No'];
echo $form->field($model, 'name')->dropDownList($a,['prompt'=>'Select Option']);
?>
active form and data from a db table
we are going to use ArrayHelper so first add it to the name space by
<?php
use yii\helpers\ArrayHelper;
?>
ArrayHelper has many use full functions which could be used to process arrays
map () is the one we are going to use here
this function help to make a map ( of key-value pairs) from a multidimensional array or an array of objects.
<?php
echo $form->field($model, 'name')->dropDownList(ArrayHelper::map(User::find()->all(),'id','username'),['prompt'=>'Select User']);
?>
not part of a active form
<?php
echo Html::activeDropDownList($model, 'filed_name',['1' => 'Yes', '0' => 'No']) ;
?>
or
<?php
$a= ['1' => 'Yes', '0' => 'No'];
echo Html::activeDropDownList($model, 'filed_name',$a) ;
?>
not an active form but data from a db table
<?php
echo Html::activeDropDownList($model, 'filed_name',ArrayHelper::map(User::find()->all(),'id','username'),['prompt'=>'Select User']);
?>
Android dependency has different version for the compile and runtime
In my case, I was having two different versions of the below implementation in two different modules, So i changed both implementation to versions ie : 6.0.2 and it worked. You may also need to write dependency resolution see the accepted answer.
app module
implementation 'com.karumi:dexter:5.0.0'
commons module
implementation 'com.karumi:dexter:6.0.2'
Git - Ignore node_modules folder everywhere
Try doing something like this
**/node_modules
**
is used for a recursive call in the whole project
Two consecutive asterisks **
in patterns matched against full pathname may have special meaning:
A leading **
followed by a slash means match in all directories. For example, **/foo
matches file or directory foo
anywhere, the same as pattern foo
. **/foo/bar
matches file or directory bar
anywhere that is directly under directory foo
.
A trailing /**
matches everything inside. For example, abc/**
matches all files inside directory abc
, relative to the location of the .gitignore file, with infinite depth.
A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, a/\**/b
matches a/b
, a/x/b
, a/x/y/b
and so on.
Other consecutive asterisks are considered invalid.
Reference
How to get array keys in Javascript?
For your input data:
let widthRange = new Array()
widthRange[46] = { min:0, max:52 }
widthRange[61] = { min:52, max:70 }
widthRange[62] = { min:52, max:70 }
widthRange[63] = { min:52, max:70 }
widthRange[66] = { min:52, max:70 }
widthRange[90] = { min:70, max:94 }
Declarative approach:
const relevantKeys = [46,66,90]
const relevantValues = Object.keys(widthRange)
.filter(index => relevantKeys.includes(parseInt(index)))
.map(relevantIndex => widthRange[relevantIndex])
Object.keys
to get the keys, using parseInt
to cast them as numbers.
filter
to get only ones you want.
map
to build an array from the original object of just the indices you're after, since Object.keys
loses the object values.
Debug:
console.log(widthRange)
console.log(relevantKeys)
console.log(relevantValues)
No space left on device
Maybe you are out of inodes. Try df -i
2591792 136322 2455470 6% /home
/dev/sdb1 1887488 1887488 0 100% /data
Disk used 6% but inode table full.
How to create a link to another PHP page
Easiest:
<a href="page2.php">Link</a>
And if you need to pass a value:
<a href="page2.php?val=1">Link that pass the value 1</a>
To retrive the value put in page2.php this code:
<?php
$val = $_GET["val"];
?>
Now the variable $val
has the value 1
.
Palindrome check in Javascript
If you want efficiency and simplicity, I recommend this approach:
function Palindrome(str) {
let len = str.length,
i = 0;
if (len < 3)
return false;
while (len--) {
if (str[i] === str[len])
i++;
else
return false;
}
return true;
}
console.log(Palindrome('aba'))//true
console.log(Palindrome('abc'))//false
Get index of selected option with jQuery
You can get the index of the select box by using : .prop() method of JQuery
Check This :
<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
alert($("#NumberSelector").prop('selectedIndex'));
alert(document.getElementById("NumberSelector").value);
}
</script>
</head>
<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
<option value="Its Zero">Zero</option>
<option value="Its One">One</option>
<option value="Its Two">Two</option>
<option value="Its Three">Three</option>
<option value="Its Four">Four</option>
<option value="Its Five">Five</option>
<option value="Its Six">Six</option>
<option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>
How to get std::vector pointer to the raw data?
&something
gives you the address of the std::vector
object, not the address of the data it holds. &something.begin()
gives you the address of the iterator returned by begin()
(as the compiler warns, this is not technically allowed because something.begin()
is an rvalue expression, so its address cannot be taken).
Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via
&something[0]
or &something.front()
(the address of the element at index 0), or
&*something.begin()
(the address of the element pointed to by the iterator returned by begin()
).
In C++11, a new member function was added to std::vector
: data()
. This member function returns the address of the initial element in the container, just like &something.front()
. The advantage of this member function is that it is okay to call it even if the container is empty.
ProgressDialog spinning circle
Try this.........
ProgressDialog pd1;
pd1=new ProgressDialog(<current context reference here>);
pd1.setMessage("Loading....");
pd1.setCancelable(false);
pd1.show();
To dismiss....
if(pd1!=null)
pd1.dismiss();
How to create a pivot query in sql server without aggregate function
SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
MAX([Value])
FOR [Period] IN ([2000], [2001], [2002])
) as pvt
Another way,
SELECT ACCOUNT,
MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account
How to change resolution (DPI) of an image?
This code using merge and convert 200 dbi
static void Main(string[] args)
{ Path string Outputpath = @"C:\Users\MDASARATHAN\Desktop\TX_HARDIN_10-01-2016_K";
string[] TotalFiles = Directory.GetFiles(Outputpath, "*.tif", SearchOption.AllDirectories);
foreach (string filename in TotalFiles)
{
Bitmap bitmap = (Bitmap)Image.FromFile(filename);
string ExportFilename = string.Empty;
int Pagecount = 0;
bool bFirstImage = true;
bitmap.SetResolution(200, 200);
ExportFilename = Path.GetDirectoryName(filename) + "\\" + Path.GetFileName(filename)+"f";
MemoryStream byteStream = new MemoryStream();
Pagecount = bitmap.GetFrameCount(FrameDimension.Page);
if (bFirstImage)
{
bitmap.Save(byteStream, ImageFormat.Tiff);
bFirstImage = false;
} Image tiff = Image.FromStream(byteStream);
ImageCodecInfo encoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
EncoderParameters encoderParams = new EncoderParameters(2);
EncoderParameter parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
encoderParams.Param[0] = parameter;
parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
encoderParams.Param[1] = parameter;
// bitmap.Dispose();
try
{
tiff.Save(ExportFilename, encoderInfo, encoderParams);
}
catch (Exception ex)
{
}
EncoderParameters EncoderParams = new EncoderParameters(2);
EncoderParameter SaveEncodeParam = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage);
EncoderParameter CompressionEncodeParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
EncoderParams.Param[0] = CompressionEncodeParam;
EncoderParams.Param[1] = SaveEncodeParam;
if (bFirstImage == false)
{
for (int i = 1; i < Pagecount; i++)
{
//bitmap = (Bitmap)Image.FromFile(filenames);
byteStream = new MemoryStream();
bitmap.SelectActiveFrame(FrameDimension.Page, i);
bitmap.Save(byteStream, ImageFormat.Tiff);
bitmap.SetResolution(200, 200);
tiff.SaveAdd(bitmap, EncoderParams);
}
} SaveEncodeParam = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush);
EncoderParams = new EncoderParameters(1);
EncoderParams.Param[0] = SaveEncodeParam;
tiff.SaveAdd(EncoderParams);
tiff.Dispose();
bitmap.Dispose();
File.Delete(filename);
}
}
How do you assert that a certain exception is thrown in JUnit 4 tests?
Just make a Matcher that can be turned off and on, like this:
public class ExceptionMatcher extends BaseMatcher<Throwable> {
private boolean active = true;
private Class<? extends Throwable> throwable;
public ExceptionMatcher(Class<? extends Throwable> throwable) {
this.throwable = throwable;
}
public void on() {
this.active = true;
}
public void off() {
this.active = false;
}
@Override
public boolean matches(Object object) {
return active && throwable.isAssignableFrom(object.getClass());
}
@Override
public void describeTo(Description description) {
description.appendText("not the covered exception type");
}
}
To use it:
add public ExpectedException exception = ExpectedException.none();
,
then:
ExceptionMatcher exMatch = new ExceptionMatcher(MyException.class);
exception.expect(exMatch);
someObject.somethingThatThrowsMyException();
exMatch.off();
How to use UIVisualEffectView to Blur Image?
-(void) addBlurEffectOverImageView:(UIImageView *) _imageView
{
UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
visualEffectView.frame = _imageView.bounds;
[_imageView addSubview:visualEffectView];
}
How to import or copy images to the "res" folder in Android Studio?
I'm in Mac OSX as well and in a new project I need to:
- Right click on res folder in the project and add a new Android resource directory.
- Select drawable from the drop down and Accept.
- Copy and paste the image into the drawable folder.
Disclaimer : This does NOT cover different resolutions etc.
how do I get eclipse to use a different compiler version for Java?
Eclipse uses it's own internal compiler that can compile to several Java versions.
From Eclipse Help > Java development user guide > Concepts > Java Builder
The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.
For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.
When you configure a project:
[project-name] > Properties > Java Compiler > Compiler compliance level
This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.
Host environment variables, eg JAVA_HOME etc, are not used.
The Oracle/Sun JDK compiler is not used.
Postgresql 9.2 pg_dump version mismatch
I had same error and this is how I solved it in my case.
This means your postgresql version is 9.2.1 but you have started postgresql service of 9.1.6.
If you run psql postgres
you will see:
psql (9.2.1, server 9.1.6)
What I did to solve this problem is:
brew services stop [email protected]
brew services restart [email protected]
Now run psql postgres
and you should have: psql (9.2.1)
You can also run brew services list
to see the status of your postgres.
Proper usage of Java -D command-line parameters
You're giving parameters to your program instead to Java. Use
java -Dtest="true" -jar myApplication.jar
instead.
Consider using
"true".equalsIgnoreCase(System.getProperty("test"))
to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like
System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")
is right (providing default true). A shorter possibility is
!"false".equalsIgnoreCase(System.getProperty("test"))
but not using double negation doesn't make it less hard to misunderstand.
How does delete[] know it's an array?
just define a destructor inside a class and execute your code with both syntax
delete pointer
delete [] pointer
according to the output u can find the solutions
How to get the parent dir location
A simple way can be:
import os
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir
Is Python interpreted, or compiled, or both?
If ( You know Java ) {
Python code is converted into bytecode like java does.
That bytecode is executed again everytime you try to access it.
} else {
Python code is initially traslated into something called bytecode
that is quite
close to machine language but not actual machine code
so each time we access or run it that bytecode is executed again
}
How to return the output of stored procedure into a variable in sql server
That depends on the nature of the information you want to return.
If it is a single integer value, you can use the return
statement
create proc myproc
as
begin
return 1
end
go
declare @i int
exec @i = myproc
If you have a non integer value, or a number of scalar values, you can use output parameters
create proc myproc
@a int output,
@b varchar(50) output
as
begin
select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output
If you want to return a dataset, you can use insert exec
create proc myproc
as
begin
select name from sysobjects
end
go
declare @t table (name varchar(100))
insert @t (name)
exec myproc
You can even return a cursor but that's just horrid so I shan't give an example :)
Load json from local file with http.get() in angular 2
You have to change
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json");
console.log(this.navItems);
}
for
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json")
.map(res => res.json())
.do(data => console.log(data));
//This is optional, you can remove the last line
// if you don't want to log loaded json in
// console.
}
Because this.http.get
returns an Observable<Response>
and you don't want the response, you want its content.
The console.log
shows you an observable, which is correct because navItems contains an Observable<Response>
.
In order to get data properly in your template, you should use async
pipe.
<app-nav-item-comp *ngFor="let item of navItems | async" [item]="item"></app-nav-item-comp>
This should work well, for more informations, please refer to HTTP Client documentation
make: *** No rule to make target `all'. Stop
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
How do you append rows to a table using jQuery?
I'm assuming you want to add this row to the <tbody>
element, and simply using append()
on the <table>
will insert the <tr>
outside the <tbody>
, with perhaps undesirable results.
$('a').click(function() {
$('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});
EDIT: Here is the complete source code, and it does indeed work: (Note the $(document).ready(function(){});
, which was not present before.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a').click(function() {
$('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});
});
</script>
<title></title>
</head>
<body>
<a href="javascript:void(0);">Link</a>
<table id="myTable">
<tbody>
<tr>
<td>test</td>
</tr>
</tbody>
</table>
</body>
</html>
Check if element exists in jQuery
How do I check if an element exists
if ($("#mydiv").length){ }
If it is 0
, it will evaluate to false
, anything more than that true
.
There is no need for a greater than, less than comparison.
How to modify a CSS display property from JavaScript?
It should be
document.getElementById("hidden").style.display = "block";
not
document.getElementById["hidden"].style.display = "block";
EDIT due to author edit:
Why are you using a <div>
here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">
How to pass a value from one jsp to another jsp page?
Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp'
Make three hidden text boxes and a button that is click automatically(using javascript).
//Code to written in 'show.jsp'
<body>
<form action="display.jsp" method="post">
<input type="hidden" name="u1" value="<%=u1%>"/>
<input type="hidden" name="u2" value="<%=u2%>" />
<input type="hidden" name="u3" value="<%=u3%>" />
<button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
<script type="text/javascript">
document.getElementById("qq").click();
</script>
</body>
// Code to be written in 'display.jsp'
<% String u1 = request.getParameter("u1").toString();
String u2 = request.getParameter("u2").toString();
String u3 = request.getParameter("u3").toString();
%>
If you want to use these variables of servlets in javascript then simply write
<script type="text/javascript">
var a=<%=u1%>;
</script>
Hope it helps :)
Column/Vertical selection with Keyboard in SublimeText 3
You should see Sublime Column Selection:
Using the Mouse
Different mouse buttons are used on each platform:
OS X
- Left Mouse Button + ?
OR: Middle Mouse Button
Add to selection: ?
- Subtract from selection: ?+?
Windows
- Right Mouse Button + Shift
OR: Middle Mouse Button
Add to selection: Ctrl
- Subtract from selection: Alt
Linux
Using the Keyboard
OS X
- Ctrl + Shift + ?
- Ctrl + Shift + ?
Windows
- Ctrl + Alt + ?
- Ctrl + Alt + ?
Linux
- Ctrl + Alt + ?
- Ctrl + Alt + ?
iOS: how to perform a HTTP POST request?
NOTE: Pure Swift 3 (Xcode 8) example:
Please try out the following sample code. It is the simple example of dataTask
function of URLSession
.
func simpleDataRequest() {
//Get the url from url string
let url:URL = URL(string: "YOUR URL STRING")!
//Get the session instance
let session = URLSession.shared
//Create Mutable url request
var request = URLRequest(url: url as URL)
//Set the http method type
request.httpMethod = "POST"
//Set the cache policy
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
//Post parameter
let paramString = "key=value"
//Set the post param as the request body
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(data, response, error) in
guard let _:Data = data as Data?, let _:URLResponse = response , error == nil else {
//Oops! Error occured.
print("error")
return
}
//Get the raw response string
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
//Print the response
print(dataString!)
}
//resume the task
task.resume()
}
take(1) vs first()
Operators first()
and take(1)
aren't the same.
The first()
operator takes an optional predicate
function and emits an error
notification when no value matched when the source completed.
For example this will emit an error:
import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';
EMPTY.pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
... as well as this:
range(1, 5).pipe(
first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));
While this will match the first value emitted:
range(1, 5).pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
On the other hand take(1)
just takes the first value and completes. No further logic is involved.
range(1, 5).pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
Then with empty source Observable it won't emit any error:
EMPTY.pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
Jan 2019: Updated for RxJS 6
Reload nginx configuration
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?
Kotlin version:
Use these extensions with infix functions that simplify later calls
infix fun View.below(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}
infix fun View.leftOf(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}
infix fun View.alightParentRightIs(aligned: Boolean) {
val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
if (aligned) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
} else {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
}
this.layoutParams = layoutParams
}
Then use them as infix functions calls:
view1 below view2
view1 leftOf view2
view1 alightParentRightIs true
Or you can use them as normal functions:
view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)
WampServer orange icon
If you are using wampserver 3 (recommended, works with no configuration usually)
- click wampserver icon > apache > service administration > install service
- click wampserver icon > mysql > service administration > install service
- click wampserver icon > mariadb > service administration > install service
- click wampserver icon > restart all services
if this doesnt fix it, try:
right click wampserver icon > Tools > Check httpd.conf syntax (then fix the issue it identifies and restart all services, likely it's bad syntax in your virtual hosts file)
right click wampserver icon > Tools > test port 80 (you likely have skype turned on or something else, turn it off and restart all services)
If this doesnt fix it, maybe have a windows conflict:
If this doesnt fix it:
- right click wampserver icon > tools
- check all of those for clues
When saving, how can you check if a field has changed?
I have extended the mixin of @livskiy as follows:
class ModelDiffMixin(models.Model):
"""
A model mixin that tracks model fields' values and provide some useful api
to know what fields have been changed.
"""
_dict = DictField(editable=False)
def __init__(self, *args, **kwargs):
super(ModelDiffMixin, self).__init__(*args, **kwargs)
self._initial = self._dict
@property
def diff(self):
d1 = self._initial
d2 = self._dict
diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
return dict(diffs)
@property
def has_changed(self):
return bool(self.diff)
@property
def changed_fields(self):
return self.diff.keys()
def get_field_diff(self, field_name):
"""
Returns a diff for field if it's changed and None otherwise.
"""
return self.diff.get(field_name, None)
def save(self, *args, **kwargs):
"""
Saves model and set initial state.
"""
object_dict = model_to_dict(self,
fields=[field.name for field in self._meta.fields])
for field in object_dict:
# for FileFields
if issubclass(object_dict[field].__class__, FieldFile):
try:
object_dict[field] = object_dict[field].path
except :
object_dict[field] = object_dict[field].name
# TODO: add other non-serializable field types
self._dict = object_dict
super(ModelDiffMixin, self).save(*args, **kwargs)
class Meta:
abstract = True
and the DictField is:
class DictField(models.TextField):
__metaclass__ = models.SubfieldBase
description = "Stores a python dict"
def __init__(self, *args, **kwargs):
super(DictField, self).__init__(*args, **kwargs)
def to_python(self, value):
if not value:
value = {}
if isinstance(value, dict):
return value
return json.loads(value)
def get_prep_value(self, value):
if value is None:
return value
return json.dumps(value)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
it can be used by extending it in your models
a _dict field will be added when you sync/migrate and that field will store the state of your objects
Make docker use IPv4 for port binding
As @daniel-t points out in the comment: github.com/docker/docker/issues/2174 is about showing binding only to IPv6 in netstat
, but that is not an issue. As that github issues states:
When setting up the proxy, Docker requests the loopback address '127.0.0.1', Linux realises this is an address that exists in IPv6 (as ::0) and opens on both (but it is formally an IPv6 socket). When you run netstat it sees this and tells you it is an IPv6 - but it is still listening on IPv4. If you have played with your settings a little, you may have disabled this trick Linux does - by setting net.ipv6.bindv6only = 1.
In other words, just because you see it as IPv6 only, it is still able to communicate on IPv4 unless you have IPv6 set to only bind on IPv6 with the net.ipv6.bindv6only setting. To be clear, net.ipv6.bindv6only should be 0 - you can run sysctl net.ipv6.bindv6only
to verify.
How do I change the text size in a label widget, python tkinter
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
SMTP error 554
To resolve problem go to the MDaemon-->setup-->Miscellaneous options-->Server-->SMTP Server Checks commands and headers for RFC Compliance
How do I localize the jQuery UI Datepicker?
Here is example how you can do localization without some extra library.
_x000D_
_x000D_
jQuery(function($) {_x000D_
$('input.datetimepicker').datepicker({_x000D_
duration: '',_x000D_
changeMonth: false,_x000D_
changeYear: false,_x000D_
yearRange: '2010:2020',_x000D_
showTime: false,_x000D_
time24h: true_x000D_
});_x000D_
_x000D_
$.datepicker.regional['cs'] = {_x000D_
closeText: 'Zavrít',_x000D_
prevText: '<Dríve',_x000D_
nextText: 'Pozdeji>',_x000D_
currentText: 'Nyní',_x000D_
monthNames: ['leden', 'únor', 'brezen', 'duben', 'kveten', 'cerven', 'cervenec', 'srpen',_x000D_
'zárí', 'ríjen', 'listopad', 'prosinec'_x000D_
],_x000D_
monthNamesShort: ['led', 'úno', 'bre', 'dub', 'kve', 'cer', 'cvc', 'srp', 'zár', 'ríj', 'lis', 'pro'],_x000D_
dayNames: ['nedele', 'pondelí', 'úterý', 'streda', 'ctvrtek', 'pátek', 'sobota'],_x000D_
dayNamesShort: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
dayNamesMin: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
weekHeader: 'Týd',_x000D_
dateFormat: 'dd/mm/yy',_x000D_
firstDay: 1,_x000D_
isRTL: false,_x000D_
showMonthAfterYear: false,_x000D_
yearSuffix: ''_x000D_
};_x000D_
_x000D_
$.datepicker.setDefaults($.datepicker.regional['cs']);_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link data-require="jqueryui@*" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />_x000D_
<script data-require="jqueryui@*" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>_x000D_
<script src="datepicker-cs.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
console.log("test");_x000D_
$("#test").datepicker({_x000D_
dateFormat: "dd.m.yy",_x000D_
minDate: 0,_x000D_
showOtherMonths: true,_x000D_
firstDay: 1_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>Here is your datepicker</h1>_x000D_
<input id="test" type="text" />_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
How to use ArrayList.addAll()?
Collections.addAll is what you want.
Collections.addAll(myArrayList, '+', '-', '*', '^');
Another option is to pass the list into the constructor using Arrays.asList like this:
List<Character> myArrayList = new ArrayList<Character>(Arrays.asList('+', '-', '*', '^'));
If, however, you are good with the arrayList being fixed-length, you can go with the creation as simple as list = Arrays.asList(...)
. Arrays.asList specification states that it returns a fixed-length list which acts as a bridge to the passed array, which could be not what you need.
Using JSON POST Request
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).
Otherwise, you might want to go with another JS library like jQuery or Mootools.
Changing nav-bar color after scrolling?
Here is simplest way how to change navbar color after window scroll:
Add follow JS to head:
$(function () {
$(document).scroll(function () {
var $nav = $(".navbar-fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
});
and this CSS code
.navbar-fixed-top.scrolled {
background-color: #fff !important;
transition: background-color 200ms linear;
}
Background color of fixed navbar will be change to white when scroll exceeds height of navbar.
See follow JsFiddle
Unzipping files in Python
import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall(directory_to_extract_to)
That's pretty much it!
Converting NSString to NSDate (and back again)
String To Date
var dateFormatter = DateFormatter()
dateFormatter.format = "dd/MM/yyyy"
var dateFromString: Date? = dateFormatter.date(from: dateString) //pass string here
Date To String
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let newDate = dateFormatter.string(from: date) //pass Date here
Resource files not found from JUnit test cases
My mistake, the resource files WERE actually copied to target/test-classes
. The problem seemed to be due to spaces in my project name, e.g. Project%20Name
.
I'm now loading the file as follows and it works:
org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);
Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):
myClass().getResource("resourceFile.txt")??.toURI();
How to get current language code with Swift?
It's important to make the difference between the App language and the device locale language (The code below is in Swift 3)
Will return the Device language:
let locale = NSLocale.current.languageCode
Will return the App language:
let pre = Locale.preferredLanguages[0]
Leaflet - How to find existing markers, and delete markers?
(1) add layer group and array to hold layers and reference to layers as global variables:
var search_group = new L.LayerGroup();
var clickArr = new Array();
(2) add map
(3) Add group layer to map
map.addLayer(search_group);
(4) the add to map function, with a popup that contains a link, which when clicked will have a remove option. This link will have, as its id the lat long of the point. This id will then be compared to when you click on one of your created markers and you want to delete it.
map.on('click', function(e) {
var clickPositionMarker = L.marker([e.latlng.lat,e.latlng.lng],{icon: idMarker});
clickArr.push(clickPositionMarker);
mapLat = e.latlng.lat;
mapLon = e.latlng.lng;
clickPositionMarker.addTo(search_group).bindPopup("<a name='removeClickM' id="+e.latlng.lat+"_"+e.latlng.lng+">Remove Me</a>")
.openPopup();
/* clickPositionMarker.on('click', function(e) {
markerDelAgain();
}); */
});
(5) The remove function, compare the marker lat long to the id fired in the remove:
$(document).on("click","a[name='removeClickM']", function (e) {
// Stop form from submitting normally
e.preventDefault();
for(i=0;i<clickArr.length;i++) {
if(search_group.hasLayer(clickArr[i]))
{
if(clickArr[i]._latlng.lat+"_"+clickArr[i]._latlng.lng==$(this).attr('id'))
{
hideLayer(search_group,clickArr[i]);
clickArr.splice(clickArr.indexOf(clickArr[i]), 1);
}
}
}
How to remove the last character from a string?
if (str.endsWith("x")) {
return str.substring(0, str.length() - 1);
}
return str;
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.
In case you're trying to stem English words
Stemming is the process for reducing inflected (or sometimes derived) words to their stem, base or root form—generally a written word form.
...
A stemmer for English, for example, should identify the string "cats" (and possibly "catlike", "catty" etc.) as based on the root "cat", and "stemmer", "stemming", "stemmed" as based on "stem". A stemming algorithm reduces the words "fishing", "fished", "fish", and "fisher" to the root word, "fish".
Difference between Lucene stemmers: EnglishStemmer, PorterStemmer, LovinsStemmer outlines some Java options.
Creating an Instance of a Class with a variable in Python
This is a very strange question to ask, specifically of python, so being more specific will definitely help me answer it. As is, I'll try to take a stab at it.
I'm going to assume what you want to do is create a new instance of a datastructure and give it a variable. For this example I'll use the dictionary data structure and the variable mydictionary.
mydictionary = dict()
This will create a new instance of the dictionary data structure and place it in the variable named mydictionary. Alternatively the dictionary constructor can also take arguments:
mydictionary = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
Finally, python will attempt to figure out what data structure I mean from the data I give it. IE
mydictionary = {'jack': 4098, 'sape': 4139}
These examples were taken from Here
Fetch the row which has the Max value for a column
This will also take care of duplicates (return one row for each user_id):
SELECT *
FROM (
SELECT u.*, FIRST_VALUE(u.rowid) OVER(PARTITION BY u.user_id ORDER BY u.date DESC) AS last_rowid
FROM users u
) u2
WHERE u2.rowid = u2.last_rowid
Email address validation in C# MVC 4 application: with or without using Regex
Don't.
Use a regex for a quick sanity check, something like .@..
, but almost all langauges / frameworks have better methods for checking an e-mail address. Use that.
It is possible to validate an e-mail address with a regex, but it is a long regex. Very long.
And in the end you will be none the wiser. You'll only know that the format is valid, but you still don't know if it's an active e-mail address. The only way to find out, is by sending a confirmation e-mail.
How to get the difference between two arrays of objects in JavaScript
Most of answers here are rather complex, but isn't logic behind this quite simple?
- check which array is longer and provide it as first parameter (if length is equal, parameters order doesnt matter)
- Iterate over array1.
- For current iteration element of array1 check if it is present in array2
- If it is NOT present, than
- Push it to 'difference' array
const getArraysDifference = (longerArray, array2) => {
const difference = [];
longerArray.forEach(el1 => { /*1*/
el1IsPresentInArr2 = array2.some(el2 => el2.value === el1.value); /*2*/
if (!el1IsPresentInArr2) { /*3*/
difference.push(el1); /*4*/
}
});
return difference;
}
O(n^2) complexity.
Convert HTML to NSAttributedString in iOS
The only solution you have right now is to parse the HTML, build up some nodes with given point/font/etc attributes, then combine them together into an NSAttributedString. It's a lot of work, but if done correctly, can be reusable in the future.
Best HTML5 markup for sidebar
First of all ASIDE is to be used only to denote related content to main content, not for a generic sidebar. Second, one aside for each sidebar only
You will have only one aside for each sidebar. Elements of a sidebar are divs or sections inside a aside.
I would go with Option 1: Aside with sections
<aside id="sidebar">
<section id="widget_1"></section>
<section id="widget_2"></section>
<section id="widget_3"></section>
</aside>
Here is the spec https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside
Again use section only if they have a header or footer in them, otherwise use a plain div.
Select 50 items from list at random to write to file
If the list is in random order, you can just take the first 50.
Otherwise, use
import random
random.sample(the_list, 50)
random.sample
help text:
sample(self, population, k) method of random.Random instance
Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use xrange as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60)
How to trap the backspace key using jQuery?
The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault()
. However as the OP alluded to, if you always call it preventDefault()
you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.
Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.
// Bind keydown event to this function. Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){
// Use jquery's constants rather than an unintuitive magic number.
// $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
if (e.keyCode == $.ui.keyCode.BACKSPACE) {
// Filters out events coming from any of the following tags so Backspace
// will work when typing text, but not take the page back otherwise.
var rx = /INPUT|SELECT|TEXTAREA/i;
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
// Add your code here.
}
});
Authenticate with GitHub using a token
By having struggling so many hours on applying GitHub token finally it works as below:
$ cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o
yaml | yq -y .spec.data.auth.password)
- code follows Codefresh guidance on cloning a repo using token (freestyle}
- test carried: sed
%d%H%M
on match word '-123456-whatever'
- push back to the repo (which is private repo)
- triggered by DockerHub webhooks
Following is the complete code:
version: '1.0'
steps:
get_git_token:
title: Reading Github token
image: codefresh/cli
commands:
- cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)
main_clone:
title: Updating the repo
image: alpine/git:latest
commands:
- git clone https://chetabahana:[email protected]/chetabahana/compose.git
- cd compose && git remote rm origin
- git config --global user.name "chetabahana"
- git config --global user.email "[email protected]"
- git remote add origin https://chetabahana:[email protected]/chetabahana/compose.git
- sed -i "s/-[0-9]\{1,\}-\([a-zA-Z0-9_]*\)'/-`date +%d%H%M`-whatever'/g" cloudbuild.yaml
- git status && git add . && git commit -m "fresh commit" && git push -u origin master
Output...
On branch master
Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git checkout -- ..." to discard changes in working directory)
modified: cloudbuild.yaml
no changes added to commit (use "git add" and/or "git commit -a")
[master dbab20f] fresh commit
1 file changed, 1 insertion(+), 1 deletion(-)
Enumerating objects: 5, done.
Counting objects: 20% (1/5) ... Counting objects: 100% (5/5), done.
Delta compression using up to 4 threads
Compressing objects: 33% (1/3) ... Writing objects: 100% (3/3), 283 bytes | 283.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 0% (0/2) ... (2/2), completed with 2 local objects.
To https://github.com/chetabahana/compose.git
bbb6d2f..dbab20f master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.
Reading environment variable exporting file contents.
Successfully ran freestyle step: Cloning the repo
Convert Word doc, docx and Excel xls, xlsx to PDF with PHP
For a PHP-specific you could try PHPWord - this library is written in pure PHP and provides a set of classes to write to and read from different document file formats (including .doc and .docx). The main drawback is that the quality of converted files can be quite variable.
Alternatively if you want a higher quality option you could use a file conversion API like Zamzar. You can use it to convert a wide range of office formats (and others) into PDF, and you can call from any platform (Windows, Linux, OS X etc).
PHP code to convert a file would look like this:
<?php
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "API_KEY";
$sourceFilePath = "/my.doc"; // Or docx/xls/xlsx etc
$targetFormat = "pdf";
$postData = array(
"source_file" => $sourceFile,
"target_format" => $targetFormat
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);
$response = json_decode($body, true);
print_r($response);
?>
Full disclosure: I'm the lead developer for the Zamzar API.
Emulate a 403 error page
I have read all the answers here and none of them was complete answer for my situation (which is exactly the same in this question) so here is how I gathered some parts of the suggested answers and come up with the exact solution:
- Land on your server's real 403 page. (Go to a forbidden URL on your server, or go to any 403 page you like)
- Right-click and select 'view source'. Select all the source and save it to file on your domain like: http://domain.com/403.html
- now go to your real forbidden page (or a forbidden situation in some part of your php) example: http://domain.com/members/this_is_forbidden.php
echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won't work)
The code below should be your first line!
<?php header('HTTP/1.0 403 Forbidden');
$contents = file_get_contents('/home/your_account/public_html/domain.com/403.html', TRUE);
exit($contents);
Now you have the exact solution. I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.
How to decrease prod bundle size?
One thing I wish to share is how imported libraries increase the size of the dist. I had angular2-moment package imported, whereas I could do all the date time formatting I required using the standard DatePipe exported from @angular/common.
With Angular2-Moment "angular2-moment": "^1.6.0",
chunk {0} polyfills.036982dc15bb5fc67cb8.bundle.js (polyfills) 191
kB {4} [initial] [rendered] chunk {1}
main.e7496551a26816427b68.bundle.js (main) 2.2 MB {3} [initial]
[rendered] chunk {2} styles.056656ed596d26ba0192.bundle.css
(styles) 69 bytes {4} [initial] [rendered] chunk {3}
vendor.62c2cfe0ca794a5006d1.bundle.js (vendor) 3.84 MB [initial]
[rendered] chunk {4} inline.0b9c3de53405d705e757.bundle.js (inline)
0 bytes [entry] [rendered]
After removing Angular2-moment and using DatePipe instead
chunk {0} polyfills.036982dc15bb5fc67cb8.bundle.js (polyfills) 191
kB {4} [initial] [rendered] chunk {1}
main.f2b62721788695a4655c.bundle.js (main) 2.2 MB {3} [initial]
[rendered] chunk {2} styles.056656ed596d26ba0192.bundle.css
(styles) 69 bytes {4} [initial] [rendered] chunk {3}
vendor.e1de06303258c58c9d01.bundle.js (vendor) 3.35 MB [initial]
[rendered] chunk {4} inline.3ae24861b3637391ba70.bundle.js (inline)
0 bytes [entry] [rendered]
Note the vendor bundle has reduced half a Megabyte!
Point is it is worth checking what angular standard packages can do even if you are already familiar with an external lib.
android listview item height
Here is my solutions;
It is my getView() in BaseAdapter subclass:
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView==null)
{
convertView=inflater.inflate(R.layout.list_view, parent,false);
System.out.println("In");
}
convertView.setMinimumHeight(100);
return convertView;
}
Here i have set ListItem's minimum height to 100;
Linq on DataTable: select specific column into datatable, not whole table
LINQ is very effective and easy to use on Lists rather than DataTable. I can see the above answers have a loop(for, foreach), which I will not prefer.
So the best thing to select a perticular column from a DataTable is just use a DataView to filter the column and use it as you want.
Find it here how to do this.
DataView dtView = new DataView(dtYourDataTable);
DataTable dtTableWithOneColumn= dtView .ToTable(true, "ColumnA");
Now the DataTable dtTableWithOneColumn contains only one column(ColumnA).
Remove a symlink to a directory
rm should remove the symbolic link.
skrall@skrall-desktop:~$ mkdir bar
skrall@skrall-desktop:~$ ln -s bar foo
skrall@skrall-desktop:~$ ls -l foo
lrwxrwxrwx 1 skrall skrall 3 2008-10-16 16:22 foo -> bar
skrall@skrall-desktop:~$ rm foo
skrall@skrall-desktop:~$ ls -l foo
ls: cannot access foo: No such file or directory
skrall@skrall-desktop:~$ ls -l bar
total 0
skrall@skrall-desktop:~$
Writing .csv files from C++
Change
Morison_File << t; //Printing to file
Morison_File << F;
To
Morison_File << t << ";" << F << endl; //Printing to file
a , would also do instead of ;
Is there a way to only install the mysql client (Linux)?
there are two ways to install mysql client on centOS.
1. First method (download rpm package)
download rpm package from mysql website https://downloads.mysql.com/archives/community/
if you download this rpm package like picture, it's filename like mysql-community-client-8.0.21-1.el8.x86_64.rpm.
then execute sudo rpm -ivh --nodeps --force mysql-community-client-8.0.21-1.el8.x86_64.rpm
can install the rpm package the parameters -ivh
means install, print output, don't verify and check.
if raise error, maybe version conflict, you can execute rpm -pa | grep mysql
to find conflicting package, then execute rpm -e --nodeps <package name>
to remove them, and install once more.
finnaly, you can execute which mysql
, it's success if print /usr/bin/mysql.
2.Second method (Set repo of yum)
Please refer to this official website:
MySQL Yum Repository
A Quick Guide to Using the MySQL Yum Repository
Use .corr to get the correlation between two columns
I ran into the same issue.
It appeared Citable Documents per Person
was a float, and python skips it somehow by default. All the other columns of my dataframe were in numpy-formats, so I solved it by converting the columnt to np.float64
Top15['Citable Documents per Person']=np.float64(Top15['Citable Documents per Person'])
Remember it's exactly the column you calculated yourself
'invalid value encountered in double_scalars' warning, possibly numpy
Zero-size array passed to numpy.mean
raises this warning (as indicated in several comments).
For some other candidates:
median
also raises this warning on zero-sized array.
other candidates do not raise this warning:
min,argmin
both raise ValueError
on empty array
randn
takes *arg
; using randn(*[])
returns a single random number
std,var
return nan
on an empty array
Triangle Draw Method
Use a line algorithm to connect point A with point C, and in an outer loop, let point A wander towards point B with the same line algorithm and with the wandering coordinates, repeat drawing that line. You can probably also include a z delta with which is also incremented iteratively. For the line algorithm, just calculate two or three slopes for the delta change of each coordinate and set one slope to 1 after changing the two others proportionally so they are below 1. This is very important for drawing closed geometrical areas between connected mesh particles. Take a look at the Qt Elastic Nodes example and now imagine drawing triangles between the nodes after stretching this over a skeleton.
As long as it will remain online
How can I set the opacity or transparency of a Panel in WinForms?
Yes, opacity can only work on top-level windows. It uses a hardware feature of the video adapter, that doesn't support child windows, like Panel. The only top-level Control derived class in Winforms is Form.
Several of the 'pure' Winform controls, the ones that do their own painting instead of letting a native Windows control do the job, do however support a transparent BackColor. Panel is one of them. It uses a trick, it asks the Parent to draw itself to produce the background pixels. One side-effect of this trick is that overlapping controls doesn't work, you only see the parent pixels, not the overlapped controls.
This sample form shows it at work:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.BackColor = Color.White;
panel1.BackColor = Color.FromArgb(25, Color.Black);
}
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.DrawLine(Pens.Yellow, 0, 0, 100, 100);
}
}
If that's not good enough then you need to consider stacking forms on top of each other. Like this.
Notable perhaps is that this restriction is lifted in Windows 8. It no longer uses the video adapter overlay feature and DWM (aka Aero) cannot be turned off anymore. Which makes opacity/transparency on child windows easy to implement. Relying on this is of course future-music for a while to come. Windows 7 will be the next XP :)
How to convert an array of strings to an array of floats in numpy?
Another option might be numpy.asarray:
import numpy as np
a = ["1.1", "2.2", "3.2"]
b = np.asarray(a, dtype=np.float64, order='C')
For Python 2*:
print a, type(a), type(a[0])
print b, type(b), type(b[0])
resulting in:
['1.1', '2.2', '3.2'] <type 'list'> <type 'str'>
[1.1 2.2 3.2] <type 'numpy.ndarray'> <type 'numpy.float64'>
SVN: Is there a way to mark a file as "do not commit"?
Conflicted files are not allowed to be committed. You can take advantage of this to keep your private changes out of the repository. This works best with a small number of files.
To get a conflict for a-file
, your working copy (WC) does not have the up to date a-file
from the repository, and that the a-file
in your WC has changes that are in the same location as changes in the repository (changes that you didn't update to yet). If you don't want to wait for the conditions above you can create a conflict for a-file
like this:
In working copy 1 (WC1), add a line of text to the top of a-file
, such as "make a conflict here". Use the necessary syntax so that you don't break the repository. Commit a-file
from WC1. In WC2, add a different line of text to the top of a-file
, like "i want a conflict". Update from WC2, and now a-file should be in conflict.
how to convert a string to an array in php
There is a function in PHP specifically designed for that purpose, str_word_count()
. By default it does not take into account the numbers and multibyte characters, but they can be added as a list of additional characters in the charlist
parameter. Charlist parameter also accepts a range of characters as in the example.
One benefit of this function over explode()
is that the punctuation marks, spaces and new lines are avoided.
$str = "1st example:
Alte Füchse gehen schwer in die Falle. ";
print_r( str_word_count( $str, 1, '1..9ü' ) );
/* output:
Array
(
[0] => 1st
[1] => example
[2] => Alte
[3] => Füchse
[4] => gehen
[5] => schwer
[6] => in
[7] => die
[8] => Falle
)
*/
SQL Insert into table only if record doesn't exist
This might be a simple solution to achieve this:
INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
FROM dual
WHERE NOT EXISTS (SELECT 1
FROM funds
WHERE ID = 23
AND date = DATE('2013-02-12'));
p.s. alternatively (if ID
a primary key):
INSERT INTO funds (ID, date, price)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need
see this Fiddle.
Using Linq to group a list of objects into a new grouped list of list of objects
Your group statement will group by group ID. For example, if you then write:
foreach (var group in groupedCustomerList)
{
Console.WriteLine("Group {0}", group.Key);
foreach (var user in group)
{
Console.WriteLine(" {0}", user.UserName);
}
}
that should work fine. Each group has a key, but also contains an IGrouping<TKey, TElement>
which is a collection that allows you to iterate over the members of the group. As Lee mentions, you can convert each group to a list if you really want to, but if you're just going to iterate over them as per the code above, there's no real benefit in doing so.
How do I print out the value of this boolean? (Java)
There are several problems.
One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.
Secondly, the line
System.out.println(boolean isLeapYear);
is a syntax error. Delete it.
Thirdly.
You never call the function from your main routine. That is why you never see any reply
to the input.
Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
This will work:
The problem may happen when you're trying to read a list with a single element as a JsonArray rather than a JsonNode or vice versa.
Since you can't know for sure if the returned list contains a single element (so the json looks like this {...}) or multiple elements (and the json looks like this [{...},{...}]) -
you'll have to check in runtime the type of the element.
It should look like this:
(Note: in this code sample I'm using com.fasterxml.jackson)
String jsonStr = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
// Start by checking if this is a list -> the order is important here:
if (rootNode instanceof ArrayNode) {
// Read the json as a list:
myObjClass[] objects = mapper.readValue(rootNode.toString(), myObjClass[].class);
...
} else if (rootNode instanceof JsonNode) {
// Read the json as a single object:
myObjClass object = mapper.readValue(rootNode.toString(), myObjClass.class);
...
} else {
...
}
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
CSS vertical-align: text-bottom;
Vertical align only works in some select cases. The easiest way to make it function is to set display: table
in the parent element's CSS and display: table-cell;
to the child element and then apply your vertical align attribute.
How do you set, clear, and toggle a single bit?
Here's my favorite bit arithmetic macro, which works for any type of unsigned integer array from unsigned char
up to size_t
(which is the biggest type that should be efficient to work with):
#define BITOP(a,b,op) \
((a)[(size_t)(b)/(8*sizeof *(a))] op ((size_t)1<<((size_t)(b)%(8*sizeof *(a)))))
To set a bit:
BITOP(array, bit, |=);
To clear a bit:
BITOP(array, bit, &=~);
To toggle a bit:
BITOP(array, bit, ^=);
To test a bit:
if (BITOP(array, bit, &)) ...
etc.
Prefer composition over inheritance?
With all the undeniable benefits provided by inheritance, here's some of its disadvantages.
Disadvantages of Inheritance:
- You can't change the implementation inherited from super classes at runtime (obviously because inheritance is defined at compile time).
- Inheritance exposes a subclass to details of its parent class implementation, that's why it's often said that inheritance breaks encapsulation (in a sense that you really need to focus on interfaces only not implementation, so reusing by sub classing is not always preferred).
- The tight coupling provided by inheritance makes the implementation of a subclass very bound up with the implementation of a super class that any change in the parent implementation will force the sub class to change.
- Excessive reusing by sub-classing can make the inheritance stack very deep and very confusing too.
On the other hand Object composition is defined at runtime through objects acquiring references to other objects. In such a case these objects will never be able to reach each-other's protected data (no encapsulation break) and will be forced to respect each other's interface. And in this case also, implementation dependencies will be a lot less than in case of inheritance.
Adding a JAR to an Eclipse Java library
You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.
How to check if android checkbox is checked within its onClick method (declared in XML)?
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fees Paid Rs100:"
android:textColor="#276ca4"
android:checked="false"
android:onClick="checkbox_clicked" />
Main Activity from here
public class RegistA extends Activity {
CheckBox fee_checkbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regist);
fee_checkbox = (CheckBox)findViewById(R.id.checkBox1);// Fee Payment Check box
}
checkbox clicked
public void checkbox_clicked(View v)
{
if(fee_checkbox.isChecked())
{
// true,do the task
}
else
{
}
}
TypeScript add Object to array with push
If your example represents your real code, the problem is not in the push
, it's that your constructor doesn't do anything.
You need to declare and initialize the x
and y
members.
Explicitly:
export class Pixel {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
Or implicitly:
export class Pixel {
constructor(public x: number, public y: number) {}
}
Reading tab-delimited file with Pandas - works on Windows, but not on Mac
The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.
You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \r
rather than the linux standard \n
or better still the suspenders and belt approach of windows with \r\n
.
pandas.read_csv(filename, sep='\t', lineterminator='\r')
You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.
import codecs
doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set
df = pandas.read_csv(doc, sep='\t')
iOS Detection of Screenshot?
Swift 4 Examples
Example #1 using closure
NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot,
object: nil,
queue: OperationQueue.main) { notification in
print("\(notification) that a screenshot was taken!")
}
Example #2 with selector
NotificationCenter.default.addObserver(self,
selector: #selector(screenshotTaken),
name: .UIApplicationUserDidTakeScreenshot,
object: nil)
@objc func screenshotTaken() {
print("Screenshot taken!")
}
Simplest way to restart service on a remote computer
As of Windows XP, you can use sc.exe
to interact with local and remote services. Schedule a task to run a batch file similar to this:
sc \\server stop service
sc \\server start service
Make sure the task runs under a user account privileged on the target server.
psservice.exe
from the Sysinternals PSTools would also be doing the job:
psservice \\server restart service
Changing Node.js listening port
I usually manually set the port that I am listening on in the app.js
file (assuming you are using express.js
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
This will log Ready on port 8080
to your console.
How can I use jQuery in Greasemonkey?
If you want to use jQuery on a site where it is already included, this is the way to go (inspired by BrunoLM):
var $ = unsafeWindow.jQuery;
I know this wasn't the original intent of the question, but it is increasingly becoming a common case and you didn't explicitly exclude this case. ;)
How to download all dependencies and packages to directory
This will download all packages and dependencies (no already installed) to a directory of your choice:
sudo apt-get install -d -o Dir::Cache=/path-to/directory/apt/cache -o Dir::State::Lists=/path-to/directory/apt/lists packages
Make sure /path-to/directory/apt/cache
and /path-to/directory/apt/lists
exist.
If you don't set -o Dir::Cache
it points to /var/cache/apt
,
Dir::State::Lists
points to /var/lib/apt/lists
(which keeps the index files of available packages)
Both -o
options can be used with update and upgrade instead of install.
On different machine run the same command without '-d
'
Stripping non printable characters from a string in python
The best I've come up with now is (thanks to the python-izers above)
def filter_non_printable(str):
return ''.join([c for c in str if ord(c) > 31 or ord(c) == 9])
This is the only way I've found out that works with Unicode characters/strings
Any better options?
How do I compile a .cpp file on Linux?
You'll need to compile it using:
g++ inputfile.cpp -o outputbinary
The file you are referring has a missing #include <cstdlib>
directive, if you also include that in your file, everything shall compile fine.
How to scroll page in flutter
You can try CustomScrollView
. Put your CustomScrollView inside Column Widget.
Just for example -
class App extends StatelessWidget {
App({Key key}): super(key: key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: const Text('AppBar'),
),
body: new Container(
constraints: BoxConstraints.expand(),
decoration: new BoxDecoration(
image: new DecorationImage(
alignment: Alignment.topLeft,
image: new AssetImage('images/main-bg.png'),
fit: BoxFit.cover,
)
),
child: new Column(
children: <Widget>[
Expanded(
child: new CustomScrollView(
scrollDirection: Axis.vertical,
shrinkWrap: false,
slivers: <Widget>[
new SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 0.0),
sliver: new SliverList(
delegate: new SliverChildBuilderDelegate(
(context, index) => new YourRowWidget(),
childCount: 5,
),
),
),
],
),
),
],
)),
);
}
}
In above code I am displaying a list of items ( total 5) in CustomScrollView.
YourRowWidget
widget gets rendered 5 times as list item. Generally you should render each row based on some data.
You can remove decoration property of Container widget, it is just for providing background image.
How to get the current logged in user Id in ASP.NET Core
I included using System.Security.Claims and I could access the GetUserId() extension method
NB: I had the using Microsoft.AspNet.Identity already but couldn't get the extension method. So I guess both of them have to be used in conjunction with one another
using Microsoft.AspNet.Identity;
using System.Security.Claims;
EDIT:
This answer is now outdated. Look at Soren's or Adrien's answer for a dated way of achieving this in CORE 1.0
How to check if any Checkbox is checked in Angular
I've a sample for multiple data with their subnode
3 list , each list has attribute and child attribute:
var list1 = {
name: "Role A",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
var list2 = {
name: "Role B",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}],
};
var list3 = {
name: "Role B",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
Add these to Array :
newArr.push(list1);
newArr.push(list2);
newArr.push(list3);
$scope.itemDisplayed = newArr;
Show them in html:
<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
<div>
<ul>
<input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)" />
<span>{{item.name}}</span>
<div>
<li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
<input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
</li>
</div>
</ul>
</div>
</li>
And here is the solution to check them:
$scope.toggleAll = function(item) {
var toogleStatus = !item.name_selected;
console.log(toogleStatus);
angular.forEach(item, function() {
angular.forEach(item.subs, function(sub) {
sub.selected = toogleStatus;
});
});
};
$scope.optionToggled = function(item, subs) {
item.name_selected = subs.every(function(itm) {
return itm.selected;
})
}
jsfiddle demo