For people still getting the issue.
I face same problem and seems some .jar file missing.
so try tar -xf apache-jmeter-5.2.1.tgz
in the console rather than just right click unzip. And also, try binary package if source package still has an issue.
this solve my issue (I am using ubuntu)
Sample: Number of requests sent.
The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.
The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.
The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.
Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.
Min and Max are the minimum and maximum response time.
An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!
Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.
The following equation show how the standard deviation (s) is calculated:
s = 1/n * v Si=1…n (xi-µ)2
For Details, see here!!
So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.
Kb/sec: The throughput measured in Kilobytes per second.
Error % : Percent of requests with errors.
An example is always better to understand!!! I think, this article will help you.
it seems to be the java SimpleDateFormat : http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
here are some tests i did around 11:30pm on the 20th of May 2015
${__time(dd-mmm-yyyy HHmmss)} 20-032-2015 233224
${__time(d-MMM-yyyy hhmmss)} 20-May-2015 113224
${__time(dd-m-yyyy hhmmss)} 20-32-2015 113224
${__time(D-M-yyyy hhmmss)} 140-5-2015 113224
${__time(DD-MM-yyyy)} 140-05-2015
Running JMeter in command line mode:
1.Navigate to JMeter’s bin directory
Now enter following command,
jmeter -n –t test.jmx
-n: specifies JMeter is to run in non-gui mode
-t: specifies name of JMX file that contains the Test Plan
You just need to create a deleter class:
struct BarDeleter {
void operator()(Bar* b) { destroy(b); }
};
and provide it as the template argument of unique_ptr
. You'll still have to initialize the unique_ptr in your constructors:
class Foo {
public:
Foo() : bar(create()), ... { ... }
private:
std::unique_ptr<Bar, BarDeleter> bar;
...
};
As far as I know, all the popular c++ libraries implement this correctly; since BarDeleter
doesn't actually have any state, it does not need to occupy any space in the unique_ptr
.
I found this little neat program for Windows called clumsy. It's in kind of alpha status, but it seem to work fine for me, and it's open source.
Edit: Others have noticed that you can't limit bandwidth with clumsy, and that's true. You can only add Latency and a couple of other network related errors. This will disqualify this answer as a valid answer to the question, however since I had good use for it when I wanted to simulate a bad network so I'll leave it here as long as it has > 0 votes or similar.
Short Answer
super(DerivedClass, self).__init__()
Long Answer
What does super()
do?
It takes specified class name, finds its base classes (Python allows multiple inheritance) and looks for the method (__init__
in this case) in each of them from left to right. As soon as it finds method available, it will call it and end the search.
How do I call init of all base classes?
Above works if you have only one base class. But Python does allow multiple inheritance and you might want to make sure all base classes are initialized properly. To do that, you should have each base class call init:
class Base1:
def __init__():
super(Base1, self).__init__()
class Base2:
def __init__():
super(Base2, self).__init__()
class Derived(Base1, Base2):
def __init__():
super(Derived, self).__init__()
What if I forget to call init for super?
The constructor (__new__
) gets invoked in a chain (like in C++ and Java). Once the instance is created, only that instance's initialiser (__init__
) is called, without any implicit chain to its superclass.
git reset --hard <tag/branch/commit id>
Notes:
git reset
without the --hard
option resets the commit history, but not the files. With the --hard
option the files in working tree are also reset. (credited user)
If you wish to commit that state so that the remote repository also points to the rolled back commit do: git push <reponame> -f
(credited user)
This is a dynamic solution which works with all value types including objects :
class Session extends Map {
set(id, value) {
if (typeof value === 'object') value = JSON.stringify(value);
sessionStorage.setItem(id, value);
}
get(id) {
const value = sessionStorage.getItem(id);
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
}
Then :
const session = new Session();
session.set('name', {first: 'Ahmed', last : 'Toumi'});
session.get('name');
That is not how the PUBLIC_URL variable is used. According to the documentation, you can use the PUBLIC_URL in your HTML:
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
Or in your JavaScript:
render() {
// Note: this is an escape hatch and should be used sparingly!
// Normally we recommend using `import` for getting asset URLs
// as described in “Adding Images and Fonts” above this section.
return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}
The PUBLIC_URL is not something you set to a value of your choosing, it is a way to store files in your deployment outside of Webpack's build system.
To view this, run your CRA app and add this to the src/index.js
file:
console.log('public url: ', process.env.PUBLIC_URL)
You'll see the URL already exists.
Read more in the CRA docs.
You can save your CSS changes from Chrome Dev Tools itself. Chrome now allows you to add local folders to your Workspace. After allowing Chrome access to the folder and adding the folder to the local workspace, you can map a web resource to a local resource.
After adding the folder, you'll have to give Chrome access to the folder.
Next, you need to map the network resource to the local resource.
CTRL + S
when editing the file.p.s.
You may have to open the mapped file(s) and start editing to get Chrome apply the local version (date 201604.12).
I appreciate this wasn't the OP's issue, but I ran into this issue recently with a different cause. For reference, I was using the Liquibase Maven plugin (liquibase-maven-plugin:3.1.1) with SQL Server.
Anyway, I'd erroneously copied and pasted a SQL Server "use" statement into one of my scripts that switches databases, so liquibase was running and updating the DATABASECHANGELOGLOCK
, acquiring the lock in the correct database, but then switching databases to apply the changes. Not only could I NOT see my changes or liquibase audit in the correct database, but of course, when I ran liquibase again, it couldn't acquire the lock, as the lock had been released in the "wrong" database, and so was still locked in the "correct" database. I'd have expected liquibase to check the lock was still applied before releasing it, and maybe that is a bug in liquibase (I haven't checked yet), but it may well be addressed in later versions! That said, I suppose it could be considered a feature!
Quite a bit of a schoolboy error, I know, but I raise it here in case anyone runs into the same problem!
Which version of IIS is your host running? One thing to try is to put a dummy default.aspx file in the root folder (this will not be used when MVC is working, but can get rid of this problem).
private void ClearBtn_Click(object sender, EventArgs e)
{
Studentpicture.Image = null;
}
This has always worked well for me:
yAxes: [{
ticks: {
display: false;
},
button1, button2 and button3 have same even handler
private void button1_Click(Object sender, EventArgs e)
{
Button btnSender = (Button)sender;
if (btnSender == button1 || btnSender == button2)
{
//some code here
}
else if (btnSender == button3)
//some code here
}
Do this:
<video style="display:block; margin: 0 auto;" controls>....</video>
Works perfect! :D
Salt is used to add an extra level of complexity to the hash, to make it harder to brute-force crack.
From an article on Sitepoint:
A hacker can still perform what's called a dictionary attack. Malicious parties may make a dictionary attack by taking, for instance, 100,000 passwords that they know people use frequently (e.g. city names, sports teams, etc.), hash them, and then compare each entry in the dictionary against each row in the database table. If the hackers find a match, bingo! They have your password. To solve this problem, however, we need only salt the hash.
To salt a hash, we simply come up with a random-looking string of text, concatenate it with the password supplied by the user, then hash both the randomly generated string and password together as one value. We then save both the hash and the salt as separate fields within the Users table.
In this scenario, not only would a hacker need to guess the password, they'd have to guess the salt as well. Adding salt to the clear text improves security: now, if a hacker tries a dictionary attack, he must hash his 100,000 entries with the salt of every user row. Although it's still possible, the chances of hacking success diminish radically.
There is no method automatically doing this in .NET, so you'll have go with the solution above.
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"
almost same as Jenish answer but a little shorter.
You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x
p <- ggplot(plot, aes(x = pred, y = value)) +
geom_point(size = 2.5) +
theme_bw()+
coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p
The OP did not exclude the starting variable, so for completeness here is how to handle the generic case of processing a supposed dictionary that may include items as dictionaries.
Also following the pure Python(3.8) recommended way to test for dictionary in the above comments.
from collections.abc import Mapping
dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
def parse_dict(in_dict):
if isinstance(in_dict, Mapping):
for k_outer, v_outer in in_dict.items():
if isinstance(v_outer, Mapping):
for k_inner, v_inner in v_outer.items():
print(k_inner, v_inner)
else:
print(k_outer, v_outer)
parse_dict(dict)
There are three ways to fetch multiple rows returned by PDO statement.
The simplest one is just to iterate over PDOStatement itself:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
echo $row['name'];
}
another one is to fetch rows using fetch() method inside a familiar while statement:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
echo $row['name'];
}
but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();
or, if you need to preprocess some data first, use the while loop and collect the data into array manually
$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
$result[] = [
'newname' => $row['oldname'],
// etc
];
}
and then output them in a template:
<ul>
<?php foreach($data as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
</ul>
Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.
As someone who is also learning pandas I found the other answers a bit implicit as pandas hides most of the work behind the scenes. Namely in how the operation works by automatically matching up column and index names. This code should be equivalent to a step by step version of @exp1orer's accepted answer
With the df
, I'll call it by the alias state_office_sales
:
sales
state office_id
AZ 2 839507
4 373917
6 347225
CA 1 798585
3 890850
5 454423
CO 1 819975
3 202969
5 614011
WA 2 163942
4 369858
6 959285
state_total_sales
is state_office_sales
grouped by total sums in index level 0
(leftmost).
In: state_total_sales = df.groupby(level=0).sum()
state_total_sales
Out:
sales
state
AZ 2448009
CA 2832270
CO 1495486
WA 595859
Because the two dataframes share an index-name and a column-name pandas will find the appropriate locations through shared indexes like:
In: state_office_sales / state_total_sales
Out:
sales
state office_id
AZ 2 0.448640
4 0.125865
6 0.425496
CA 1 0.288022
3 0.322169
5 0.389809
CO 1 0.206684
3 0.357891
5 0.435425
WA 2 0.321689
4 0.346325
6 0.331986
To illustrate this even better, here is a partial total with a XX
that has no equivalent. Pandas will match the location based on index and column names, where there is no overlap pandas will ignore it:
In: partial_total = pd.DataFrame(
data = {'sales' : [2448009, 595859, 99999]},
index = ['AZ', 'WA', 'XX' ]
)
partial_total.index.name = 'state'
Out:
sales
state
AZ 2448009
WA 595859
XX 99999
In: state_office_sales / partial_total
Out:
sales
state office_id
AZ 2 0.448640
4 0.125865
6 0.425496
CA 1 NaN
3 NaN
5 NaN
CO 1 NaN
3 NaN
5 NaN
WA 2 0.321689
4 0.346325
6 0.331986
This becomes very clear when there are no shared indexes or columns. Here missing_index_totals
is equal to state_total_sales
except that it has a no index-name.
In: missing_index_totals = state_total_sales.rename_axis("")
missing_index_totals
Out:
sales
AZ 2448009
CA 2832270
CO 1495486
WA 595859
In: state_office_sales / missing_index_totals
Out: ValueError: cannot join with no overlapping index names
It's very simple. Only add host in your database.yaml file.
You don't need a for loop in your code.
Here is how you can re implement your method
Edit:
Here is hint for you to proceed, Following code snippet gives int
values for char
s
System.out.println("a="+(int)'a');
System.out.println("z="+(int)'z');
System.out.println("A="+(int)'A');
System.out.println("Z="+(int)'Z');
Output
a=97
z=122
A=65
Z=90
Here is how you can check if a number x
exists between two numbers say a
and b
// x greater than or equal to a and x less than or equal to b
if ( x >= a && x <= b )
During comparisons char
s can be treated as numbers
If you can combine these hints, you should be able to find what you want ;)
Add the outerheight to the top and you have the bottom, relative to the parent element:
var $el = $('#bottom'); //record the elem so you don't crawl the DOM everytime
var bottom = $el.position().top + $el.outerHeight(true); // passing "true" will also include the top and bottom margin
With absolutely positioned elements or when positioning relative to the document, you will need to instead evaluate using offset:
var bottom = $el.offset().top + $el.outerHeight(true);
As pointed out by trnelson this does not work 100% of the time. To use this method for positioned elements, you also must account for offset. For an example see the following code.
var bottom = $el.position().top + $el.offset().top + $el.outerHeight(true);
In Python 3.4+ you can use the simpler pathlib
module:
from inspect import currentframe, getframeinfo
from pathlib import Path
filename = getframeinfo(currentframe()).filename
parent = Path(filename).resolve().parent
You can also use __file__
to avoid the inspect
module altogether:
from pathlib import Path
parent = Path(__file__).resolve().parent
Add an onchange event to your input element:
<input type="text" id="fName" value="" onchange="fName_Changed(this)" />
Javascript:
function fName_Changed(fName)
{
fName.style.borderColor = (fName.value != 'correct text') ? "#FF0000"; : fName.style.borderColor="";
}
the ideal way is to
{{ something|safe }}
than completely turning off auto escaping.
Both the DATETIME
and DATETIME2
map to System.DateTime
in .NET - you cannot really do a "conversion", since it's really the same .NET type.
See the MSDN doc page: http://msdn.microsoft.com/en-us/library/bb675168.aspx
There are two different values for the "SqlDbType
" for these two - can you specify those in your DataColumn
definition?
BUT: on SQL Server, the date range supported is quite different.
DATETIME
supports 1753/1/1 to "eternity" (9999/12/31), while DATETIME2
supports 0001/1/1 through eternity.
So what you really need to do is check for the year of the date - if it's before 1753, you need to change it to something AFTER 1753 in order for the DATETIME
column in SQL Server to handle it.
Marc
As far as I'm aware, you have to copy + paste the sections you want from the library .config into the applications .config file. You only get 1 app.config per executable instance.
Read Byte by Byte and check that each byte against '\n'
if it is not, then store it into buffer
if it is '\n'
add '\0'
to buffer and then use atoi()
You can read a single byte like this
char c;
read(fd,&c,1);
See read()
According to the create table statement, the default charset of the table is already utf8mb4. It seems that you have a wrong connection charset.
In Java, set the datasource url like this: jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8.
"?useUnicode=true&characterEncoding=utf-8" is necessary for using utf8mb4.
It works for my application.
Use a timer. Keep in mind that .NET comes with a number of different timers. This article covers the differences.
Yo could also set labels = FALSE
inside axis(...)
and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it
lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)
Detailed explanation here
I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")
train_set = ["president of India",doc1, doc2, doc3]
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set) #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train) #here the first element of tfidf_matrix_train is matched with other three elements
Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.
Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III
the output will be as follows :
[[ 1. 0.07102631 0.02731343 0.06348799]]
here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.
I believe what the interviewer was trying to get at was probably the difference between interface and implementation.
The interface - not a Java interface, but "interface" in more general terms - to a code module is, basically, the contract made with client code that uses the interface.
The implementation of a code module is the internal code that makes the module work. Often you can implement a particular interface in more than one different way, and even change the implementation without client code even being aware of the change.
A Java interface should only be used as an interface in the above generic sense, to define how the class behaves for the benefit of client code using the class, without specifying any implementation. Thus, an interface includes method signatures - the names, return types, and argument lists - for methods expected to be called by client code, and in principle should have plenty of Javadoc for each method describing what that method does. The most compelling reason for using an interface is if you plan to have multiple different implementations of the interface, perhaps selecting an implementation depending on deployment configuration.
A Java abstract class, in contrast, provides a partial implementation of the class, rather than having a primary purpose of specifying an interface. It should be used when multiple classes share code, but when the subclasses are also expected to provide part of the implementation. This permits the shared code to appear in only one place - the abstract class - while making it clear that parts of the implementation are not present in the abstract class and are expected to be provided by subclasses.
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
To set for x minutes we need to set x minutes in the 1st argument and then the path of your script
For 15 mins
*/15 * * * * /usr/bin/php /mydomain.in/cromail.php > /dev/null 2>&1
You can you use permalinks to include code snippets in issues, PRs, etc.
References:
https://help.github.com/en/articles/creating-a-permanent-link-to-a-code-snippet
You can use pickle
import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'wb')
pickle.dump(dict, file)
file.close()
and to read it again
file = open('dump.txt', 'rb')
dict = pickle.load(file)
EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :)
What is the resolution of the video? I had a similar problem with IE11 in Win7. The Microsoft H.264 decoder supports only 1920x1088 pixels in Windows 7. See my story: http://lars.st0ne.at/blog/html5+video+in+IE11+-+size+does+matter
How can I make two decorators in Python that would do the following?
You want the following function, when called:
@makebold @makeitalic def say(): return "Hello"
To return:
<b><i>Hello</i></b>
To most simply do this, make decorators that return lambdas (anonymous functions) that close over the function (closures) and call it:
def makeitalic(fn):
return lambda: '<i>' + fn() + '</i>'
def makebold(fn):
return lambda: '<b>' + fn() + '</b>'
Now use them as desired:
@makebold
@makeitalic
def say():
return 'Hello'
and now:
>>> say()
'<b><i>Hello</i></b>'
But we seem to have nearly lost the original function.
>>> say
<function <lambda> at 0x4ACFA070>
To find it, we'd need to dig into the closure of each lambda, one of which is buried in the other:
>>> say.__closure__[0].cell_contents
<function <lambda> at 0x4ACFA030>
>>> say.__closure__[0].cell_contents.__closure__[0].cell_contents
<function say at 0x4ACFA730>
So if we put documentation on this function, or wanted to be able to decorate functions that take more than one argument, or we just wanted to know what function we were looking at in a debugging session, we need to do a bit more with our wrapper.
We have the decorator wraps
from the functools
module in the standard library!
from functools import wraps
def makeitalic(fn):
# must assign/update attributes from wrapped function to wrapper
# __module__, __name__, __doc__, and __dict__ by default
@wraps(fn) # explicitly give function whose attributes it is applying
def wrapped(*args, **kwargs):
return '<i>' + fn(*args, **kwargs) + '</i>'
return wrapped
def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return '<b>' + fn(*args, **kwargs) + '</b>'
return wrapped
It is unfortunate that there's still some boilerplate, but this is about as simple as we can make it.
In Python 3, you also get __qualname__
and __annotations__
assigned by default.
So now:
@makebold
@makeitalic
def say():
"""This function returns a bolded, italicized 'hello'"""
return 'Hello'
And now:
>>> say
<function say at 0x14BB8F70>
>>> help(say)
Help on function say in module __main__:
say(*args, **kwargs)
This function returns a bolded, italicized 'hello'
So we see that wraps
makes the wrapping function do almost everything except tell us exactly what the function takes as arguments.
There are other modules that may attempt to tackle the problem, but the solution is not yet in the standard library.
To get rid of the outline when clicking, add outline:none
button {
background-color: Transparent;
background-repeat:no-repeat;
border: none;
cursor:pointer;
overflow: hidden;
outline:none;
}
button {_x000D_
background-color: Transparent;_x000D_
background-repeat:no-repeat;_x000D_
border: none;_x000D_
cursor:pointer;_x000D_
overflow: hidden;_x000D_
outline:none;_x000D_
}
_x000D_
<button>button</button>
_x000D_
Add -ErrorAction SilentlyContinue
to your script and you'll be good to go.
Take IISReset as a suite of commands that helps you manage IIS start / stop etc.
Which means you need to specify option (/switch
) what you want to do to carry any operation.
Default behavior OR default switch is /restart
with iisreset
so you do not need to run command twice with /start
and /stop
.
Hope this clarifies your question. For reference the output of iisreset /?
is:
IISRESET.EXE (c) Microsoft Corp. 1998-2005 Usage: iisreset [computername] /RESTART Stop and then restart all Internet services. /START Start all Internet services. /STOP Stop all Internet services. /REBOOT Reboot the computer. /REBOOTONERROR Reboot the computer if an error occurs when starting, stopping, or restarting Internet services. /NOFORCE Do not forcefully terminate Internet services if attempting to stop them gracefully fails. /TIMEOUT:val Specify the timeout value ( in seconds ) to wait for a successful stop of Internet services. On expiration of this timeout the computer can be rebooted if the /REBOOTONERROR parameter is specified. The default value is 20s for restart, 60s for stop, and 0s for reboot. /STATUS Display the status of all Internet services. /ENABLE Enable restarting of Internet Services on the local system. /DISABLE Disable restarting of Internet Services on the local system.
how does rails know that
user_id
is a foreign key referencinguser
?
Rails itself does not know that user_id
is a foreign key referencing user
. In the first command rails generate model Micropost user_id:integer
it only adds a column user_id
however rails does not know the use of the col. You need to manually put the line in the Micropost
model
class Micropost < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :microposts
end
the keywords belongs_to
and has_many
determine the relationship between these models and declare user_id
as a foreign key to User
model.
The later command rails generate model Micropost user:references
adds the line belongs_to :user
in the Micropost
model and hereby declares as a foreign key.
FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench
you find that there is no relationship threads drawn between the models. Like in the following pic
However, if you use the later method you find that you migration file looks like:
def change
create_table :microposts do |t|
t.references :user, index: true
t.timestamps null: false
end
add_foreign_key :microposts, :users
Now the foreign key is set at the database level. and you can generate proper EER
diagrams.
Create your assets directory the same as lib level
like this
projectName
-android
-ios
-lib
-assets
-pubspec.yaml
then your pubspec.yaml like
flutter:
assets:
- assets/images/
now you can use Image.asset("/assets/images/")
Don't reinvent the wheel; check out Ruby's way-cool OptionParser library.
It offers parsing of flags/switches, parameters with optional or required values, can parse lists of parameters into a single option and can generate your help for you.
Also, if any of your information being passed in is pretty static, that doesn't change between runs, put it into a YAML file that gets parsed. That way you can have things that change every time on the command-line, and things that change occasionally configured outside your code. That separation of data and code is nice for maintenance.
Here are some samples to play with:
require 'optparse'
require 'yaml'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on('-n', '--sourcename NAME', 'Source name') { |v| options[:source_name] = v }
opts.on('-h', '--sourcehost HOST', 'Source host') { |v| options[:source_host] = v }
opts.on('-p', '--sourceport PORT', 'Source port') { |v| options[:source_port] = v }
end.parse!
dest_options = YAML.load_file('destination_config.yaml')
puts dest_options['dest_name']
This is a sample YAML file if your destinations are pretty static:
---
dest_name: [email protected]
dest_host: imap.gmail.com
dest_port: 993
dest_ssl: true
dest_user: [email protected]
dest_pass: password
This will let you easily generate a YAML file:
require 'yaml'
yaml = {
'dest_name' => '[email protected]',
'dest_host' => 'imap.gmail.com',
'dest_port' => 993,
'dest_ssl' => true,
'dest_user' => '[email protected]',
'dest_pass' => 'password'
}
puts YAML.dump(yaml)
A decent alternative if you're using firefox is the XRefresh plugin. It will reload your page everytime it detect the file has been modified. So rather than just refreshing every 5 seconds, it will just refresh when you hit save in your HTML editor.
For those who're having the same problem as I was. After doing all the solutions above, still didn't work for me. I found out that, uWamp was creating the PHP.INI file in bin/apache directory. So I had to copy the PHP.INI file into php installation directory, that is, bin/php/phpXXXX directory. This should also be where the php.exe is that you selected from the composer setup.
Hope this helps.
No fancy tricks needed:
for i in *.java; do
[ -f "$i" ] || break
...
done
The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java
. In bash
(or shells supporting something similar), you can use the nullglob
option
to simply ignore a failed match and not enter the body of the loop.
shopt -s nullglob
for i in *.java; do
...
done
I've build a win 7 dark theme base on the popular windows 7 'concave 7' theme for eclipse dark juno theme. And I also create a dark theme inspired from the editor color theme 'Zenburn' created by Janni Nurmin
Here are photos of this theme: https://plus.google.com/u/0/photos/114921213517944089128/albums/5952793008016527457
All settings of this theme is available on github: https://github.com/youjenli/dark-theme-for-win7-eclipse
And feedback and suggestion is appreciated, thank you!
This is the best code to centre the div bot horizontally and vertically
div_x000D_
{_x000D_
position:absolute;_x000D_
top:50%;_x000D_
left:50%;_x000D_
transform:translate(-50%,-50%);_x000D_
}
_x000D_
A lot of people, including me, use sqlfiddle.com to test SQL.
Its in CSS you have to set font-weight: bold;
as style
Append "empty" row to data frame and fill selected cells:
Generate empty data frame (no rows just columns a
and b
):
import pandas as pd
col_names = ["a","b"]
df = pd.DataFrame(columns = col_names)
Append empty row at the end of the data frame:
df = df.append(pd.Series(), ignore_index = True)
Now fill the empty cell at the end (len(df)-1
) of the data frame in column a
:
df.loc[[len(df)-1],'a'] = 123
Result:
a b
0 123 NaN
And of course one can iterate over the rows and fill cells:
col_names = ["a","b"]
df = pd.DataFrame(columns = col_names)
for x in range(0,5):
df = df.append(pd.Series(), ignore_index = True)
df.loc[[len(df)-1],'a'] = 123
Result:
a b
0 123 NaN
1 123 NaN
2 123 NaN
3 123 NaN
4 123 NaN
If you are using an SMTP configuration for sending your email, try using PHPMailer instead. You can download the library from https://github.com/PHPMailer/PHPMailer.
I created my email sending this way:
function send_mail($email, $recipient_name, $message='')
{
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->CharSet = "utf-8";
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = "mail.example.com"; // Specify main and backup server
$mail->SMTPAuth = true; // Turn on SMTP authentication
$mail->Username = "myusername"; // SMTP username
$mail->Password = "p@ssw0rd"; // SMTP password
$mail->From = "[email protected]";
$mail->FromName = "System-Ad";
$mail->AddAddress($email, $recipient_name);
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML (true) or plain text (false)
$mail->Subject = "This is a Sampleenter code here Email";
$mail->Body = $message;
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
$mail->AddEmbeddedImage('images/logo.png', 'logo', 'logo.png');
$mail->addAttachment('files/file.xlsx');
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
}
Coworker had this exact problem today, after a BSoD while trying to push. He had to:
.hg/store/lock
(as per the accepted answer).hg/store/phaseroots
(as per this TortoiseHG bug report)Then his repo worked again.
EDIT: As per @Marmoute's comment - when dealing with lock-related issues, using hg debuglock
is a safer alternative to blindly deleting the .hg/store/lock
file.
Follow the below steps -
As I haven't seen it at serverfault yet, and the answer is quite simple:
Change:
ssh -f -L3310:remote.server:3306 [email protected] -N
To:
ssh -f -L3310:localhost:3306 [email protected] -N
And change:
mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name
To:
mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name
(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)
edit: well, to elaborate: if host is set to localhost
, a configured (or default) --socket
option is assumed. See the manual for which option files are sought / used. Under Windows, this can be a named pipe.
setInterval(function() {
updatechat();
}, 2000);
function updatechat() {
alert('hello world');
}
Swift 2.0 : Accessing Info.Plist
I have a Dictionary named CoachMarksDictionary with a boolean value in Info.Plist . I want to access the bool value and make it true.
let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]
if let CoachMarksDict = dict["CoachMarksDictionary"] {
print("Info.plist : \(CoachMarksDict)")
var dashC = CoachMarksDict["DashBoardCompleted"] as! Bool
print("DashBoardCompleted state :\(dashC) ")
}
Writing To Plist:
From a Custom Plist:- (Make from File-New-File-Resource-PropertyList. Added three strings named : DashBoard_New, DashBoard_Draft, DashBoard_Completed)
func writeToCoachMarksPlist(status:String?,keyName:String?)
{
let path1 = NSBundle.mainBundle().pathForResource("CoachMarks", ofType: "plist")
let coachMarksDICT = NSMutableDictionary(contentsOfFile: path1!)! as NSMutableDictionary
var coachMarksMine = coachMarksDICT.objectForKey(keyName!)
coachMarksMine = status
coachMarksDICT.setValue(status, forKey: keyName!)
coachMarksDICT.writeToFile(path1!, atomically: true)
}
The method can be called as
self.writeToCoachMarksPlist(" true - means user has checked the marks",keyName: "the key in the CoachMarks dictionary").
You can wrap the contents of the li
in another element such as a span
. Then, give the li
a larger font-size
, and set a normal font-size
back on the span
:
li {
font-size: 36px;
}
li span {
font-size: 18px;
}
<ul>
<li><span>Item 1</span></li>
<li><span>Item 2</span></li>
<li><span>Item 3</span></li>
</ul>
Here is another approach using getter and setter functions for the model.
@Component({
selector: 'input-language',
template: `
…
<input
type="text"
placeholder="Language"
[(ngModel)]="query"
/>
`,
})
export class InputLanguageComponent {
set query(value) {
this._query = value;
console.log('query set to :', value)
}
get query() {
return this._query;
}
}
Use some external app like sed:
<exec executable="sed" inputstring="${wersja}" outputproperty="wersjaDot">
<arg value="s/_/./g"/>
</exec>
<echo>${wersjaDot}</echo>
If you run Windows get it googling for "gnuwin32 sed".
The command s/_/./g
replaces every _
with .
This script goes well under windows. Under linux arg may need quoting.
I exported the following connection from Studio 3T:
mongodb://youn-nosql-grej-test:[email protected]:10255/admin?3t.uriVersion=2&3t.certificatePreference=RootCACert:accept_any&3t.databases=admin&3t.connectionMode=direct&3t.useClientCertPassword=false&3t.connection.name=Grej-Test&readPreference=primary&ssl=true
And I filled it in in the following screens:
What is the main difference. Like memory or performance implications
The difference between static and dynamic resources comes when the underlying object changes. If your Brush defined in the Resources collection were accessed in code and set to a different object instance, Rectangle will not detect this change.
Static Resources retrieved once by referencing element and used for the lifetime of the resources. Whereas, DynamicResources retrieve every time they are used.
The downside of Dynamic resources is that they tend to decrease application performance.
Are there rules in WPF like "brushes are always static" and "templates are always dynamic" etc.?
The best practice is to use Static Resources unless there is a specific reason like you want to change resource in the code behind dynamically. Another example of instance in which you would want t to use dynamic resoruces include when you use the SystemBrushes, SystenFonts and System Parameters.
/**
* <blockquote><pre>
* {@code
* public Foo(final Class<?> klass) {
* super();
* this.klass = klass;
* }
* }
* </pre></blockquote>
**/
<pre/>
is required for preserving lines.{@code
must has its own line<blockquote/>
is just for indentation.public Foo(final Class<?> klass) {
super();
this.klass = klass;
}
The minimum requirements for proper codes are <pre/>
and {@code}
.
/**
* test.
*
* <pre>{@code
* <T> void test(Class<? super T> type) {
* System.out.printf("hello, world\n");
* }
* }</pre>
*/
yields
<T> void test(Class<? super T> type) {
System.out.printf("hello, world\n");
}
And an optional surrounding <blockquote/>
inserts an indentation.
/**
* test.
*
* <blockquote><pre>{@code
* <T> void test(Class<? super T> type) {
* System.out.printf("hello, world\n");
* }
* }</pre></blockquote>
*/
yields
<T> void test(Class<? super T> type) {
System.out.printf("hello, world\n");
}
Inserting <p>
or surrounding with <p>
and </p>
yields warnings.
you can use git difftool
.
for example if you have meld, you can edit the branchs master
and devel
by:
git config --global diff.external meld
git difftool master..devel
if (location.protocol == 'http:')
location.href = location.href.replace(/^http:/, 'https:')
My favorite use case for read uncommited
is to debug something that is happening inside a transaction.
Start your software under a debugger, while you are stepping through the lines of code, it opens a transaction and modifies your database. While the code is stopped, you can open a query analyzer, set on the read uncommited isolation level and make queries to see what is going on.
You also can use it to see if long running procedures are stuck or correctly updating your database.
It is great if your company loves to make overly complex stored procedures.
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
This does the trick, and works for any select.
$('#baba').val($(this).find('option:first').val());
I have written a shell script to install/uninstall java on centos. You can get it done by just run the shell. The core of this shell is :
1.download the jdk rpm(RedHat Package Manager) package.
2.install java using rpm.
You can see more detail here: https://github.com/daikaixian/WaterShell/tree/master/program_installer
Hope it works for you.
I had exactly the same problem. I fixed it without rebuilding python, as follows:
Find another server with the same architecture (i386 or x86_64) and the same python version (example: 2.7.5). Yes, this is the hard part. You can try installing python from sources into another server if you can't find any server with the same python version.
In this another server, check if import ssl works. It should work.
If it works, then try to find the _ssl lilbrary as follows:
[root@myserver]# find / -iname _ssl.so
/usr/local/python27/lib/python2.7/lib-dynload/_ssl.so
Copy this file into the original server. Use the same destination folder: /usr/local/python27/lib/python2.7/lib-dynload/
Double check owner and permissions:
[root@myserver]# chown root:root _ssl.so
[root@myserver]# chmod 755 _ssl.so
Now you should be able to import ssl.
This worked for me in a CentOS 6.3 x86_64 environment with python 2.7.3. Also I had python 2.6.6 installed, but with ssl working fine.
+1 means 2 days ago. It's rounded.
It is actually a permission issue. Add these lines in your platforms/android/AndroidManifest.xml
file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Look at this code:
import PyPDF2
pdf_file = open('sample.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content.encode('utf-8')
The output is:
!"#$%#$%&%$&'()*%+,-%./01'*23%4
5'%1$#26%3/%7/))/8%&)/26%8#3"%3"*%313/9#&)
%
Using the same code to read a pdf from 201308FCR.pdf .The output is normal.
Its documentation explains why:
def extractText(self):
"""
Locate all text drawing commands, in the order they are provided in the
content stream, and extract the text. This works well for some PDF
files, but poorly for others, depending on the generator used. This will
be refined in the future. Do not rely on the order of text coming out of
this function, as it will change if this function is made more
sophisticated.
:return: a unicode string object.
"""
INTRO: This answer was written in a time when Numpy was version 1.11 and behaviour of NAT comparison was supposed to change since version 1.12. Clearly that wasn't the case and the second part of answer became wrong. The first part of answer may be not applicable for new versions of numpy. Be sure you've checked MSeifert's answers below.
import numpy as np
nat = np.datetime64('NaT')
def nat_check(nat):
return nat == np.datetime64('NaT')
nat_check(nat)
Out[4]: FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
True
nat_check(nat)
Out[5]: True
If you want to suppress the warning you can use the catch_warnings context manager:
import numpy as np
import warnings
nat = np.datetime64('NaT')
def nat_check(nat):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')
nat_check(nat)
Out[5]: True
And finally you might check numpy version to handle changed behavior since version 1.12.0:
def nat_check(nat):
if [int(x) for x in np.__version__.split('.')[:-1]] > [1, 11]:
return nat != nat
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')
isnat
function since version 1.13.
I finally found the perfect solution that solves this problem for me.
ifeq '$(findstring ;,$(PATH))' ';'
UNAME := Windows
else
UNAME := $(shell uname 2>/dev/null || echo Unknown)
UNAME := $(patsubst CYGWIN%,Cygwin,$(UNAME))
UNAME := $(patsubst MSYS%,MSYS,$(UNAME))
UNAME := $(patsubst MINGW%,MSYS,$(UNAME))
endif
The UNAME variable is set to Linux, Cygwin, MSYS, Windows, FreeBSD, NetBSD (or presumably Solaris, Darwin, OpenBSD, AIX, HP-UX), or Unknown. It can then be compared throughout the remainder of the Makefile to separate any OS-sensitive variables and commands.
The key is that Windows uses semicolons to separate paths in the PATH variable whereas everyone else uses colons. (It's possible to make a Linux directory with a ';' in the name and add it to PATH, which would break this, but who would do such a thing?) This seems to be the least risky method to detect native Windows because it doesn't need a shell call. The Cygwin and MSYS PATH use colons so uname is called for them.
Note that the OS environment variable can be used to detect Windows, but not to distinguish between Cygwin and native Windows. Testing for the echoing of quotes works, but it requires a shell call.
Unfortunately, Cygwin adds some version information to the output of uname, so I added the 'patsubst' calls to change it to just 'Cygwin'. Also, uname for MSYS actually has three possible outputs starting with MSYS or MINGW, but I use also patsubst to transform all to just 'MSYS'.
If it's important to distinguish between native Windows systems with and without some uname.exe on the path, this line can be used instead of the simple assignment:
UNAME := $(shell uname 2>NUL || echo Windows)
Of course in all cases GNU make is required, or another make which supports the functions used.
//arraylist/Pojo you can Pass using bundle like this
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
intent.putExtra("BUNDLE",args);
startActivity(intent);
Get SecondActivity like this
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");
//Happy coding
BalusC is right. Version 1.0.13 is current, but 1.0.9 appears to have the required bundles:
$ jar tf lib/jfreechart-1.0.9.jar | grep LocalizationBundle.properties org/jfree/chart/LocalizationBundle.properties org/jfree/chart/editor/LocalizationBundle.properties org/jfree/chart/plot/LocalizationBundle.properties
Actually jessehouwing
gave the solution for normal scenario.
But in my case I have enabled 2 types of session in my web.config file
It's like below.
First one :
<modules runAllManagedModulesForAllRequests="true">
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
Second one :
<sessionState mode="Custom" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PawLoyalty" applicationName="PawLoyalty"/>
</providers>
</sessionState>
So in my case I have to comment Second one.B'cos that thing for the production.When I commented out second one my problem vanished.
You can't show dialog box ON SERVER from ASP.NET application, well of course tehnically you can do that but it makes no sense since your user is using browser and it can't see messages raised on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.
Here is the example for asp.net :
The easier to read method saves humans perceptible amounts of time when looking at the code, whereas the "faster" method only wastes imperceptible and likely negligible amounts of time when people are browsing the page.
I know this post is lame, but I accidentally posted something entirely different thinking this was a different thread and I don't know how to delete posts. My bad...
This is best plugin with proper documentation and examples
Plus point: you can ask for help in its discussion forum and you will get response within a day from the author itself, really impressive.
There are two ways to add the NOT NULL Columns to the table :
ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''
ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''
You can specify the color
option as a list directly to the plot
function.
from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np # I find np.random.randint to be better
# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)
# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))
# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)
To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.
my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.
The last example yields the follow simple gradient of colors for me:
I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.
In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.
As soon as question is about dynamic array you may want not just to create array with variable size, but also to change it's size during runtime. Here is an example with memcpy
, you can use memcpy_s
or std::copy
as well. Depending on compiler, <memory.h>
or <string.h>
may be required. When using this functions you allocate new memory region, copy values of original memory regions to it and then release them.
// create desired array dynamically
size_t length;
length = 100; //for example
int *array = new int[length];
// now let's change is's size - e.g. add 50 new elements
size_t added = 50;
int *added_array = new int[added];
/*
somehow set values to given arrays
*/
// add elements to array
int* temp = new int[length + added];
memcpy(temp, array, length * sizeof(int));
memcpy(temp + length, added_array, added * sizeof(int));
delete[] array;
array = temp;
You may use constant 4 instead of sizeof(int)
.
$x = new stdClass();
A comment in the manual sums it up best:
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.
When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
open the CMD and use this command :
**
pip uninstall django
**
it will easy uninstalled .
you can edit all the columns at once by using this simple code via Foreach loop
foreach (DataGridViewColumn item in datagridview1.Columns)
{
item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
Unless your compiler is different than the one supplied with the Mac XCode Dev tools, just follow the instructions in section 5.1 of Getting Started Guide for Unix Variants. The configuration and building of the latest source couldn't be easier, and it took all about about 1 minute to configure and 10 minutes to compile.
Be more functional.
Objective-C is object-oriented language, but Cocoa framework functional-style aware, and is designed functional style in many cases.
There is separation of mutability. Use immutable classes as primary, and mutable object as secondary. For instance, use NSArray primarily, and use NSMutableArray only when you need.
There is pure functions. Not so many, buy many of framework APIs are designed like pure function. Look at functions such as CGRectMake()
or CGAffineTransformMake()
. Obviously pointer form looks more efficient. However indirect argument with pointers can't offer side-effect-free. Design structures purely as much as possible.
Separate even state objects. Use -copy
instead of -retain
when passing a value to other object. Because shared state can influence mutation to value in other object silently. So can't be side-effect-free. If you have a value from external from object, copy it. So it's also important designing shared state as minimal as possible.
However don't be afraid of using impure functions too.
There is lazy evaluation. See something like -[UIViewController view]
property. The view won't be created when the object is created. It'll be created when caller reading view
property at first time. UIImage
will not be loaded until it actually being drawn. There are many implementation like this design. This kind of designs are very helpful for resource management, but if you don't know the concept of lazy evaluation, it's not easy to understand behavior of them.
There is closure. Use C-blocks as much as possible. This will simplify your life greatly. But read once more about block-memory-management before using it.
There is semi-auto GC. NSAutoreleasePool. Use -autorelease
primary. Use manual -retain/-release
secondary when you really need. (ex: memory optimization, explicit resource deletion)
Try this on Windows:
cmdkey /delete:LegacyGeneric:target=git:https://github.com
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
I have fixed this in my matplotlib source, but it's not a pretty fix. However, if you, like me, are very particular about how the graph looks, it's worth it.
The issue seems to be in the rendering backends; they each get the correct values for linewidth, font size, etc., but that comes out slightly larger when rendered as a PDF or PNG than when rendered with show().
I added a few lines to the source for PNG generation, in the file matplotlib/backends/backend_agg.py. You could make similar changes for each backend you use, or find a way to make a more clever change in a single location ;)
Added to my matplotlib/backends/backend_agg.py file:
# The top of the file, added lines 42 - 44
42 # @warning: CHANGED FROM SOURCE to draw thinner lines
43 PATH_SCALAR = .8
44 FONT_SCALAR = .95
# In the draw_markers method, added lines 90 - 91
89 def draw_markers(self, *kl, **kw):
90 # @warning: CHANGED FROM SOURCE to draw thinner lines
91 kl[0].set_linewidth(kl[0].get_linewidth()*PATH_SCALAR)
92 return self._renderer.draw_markers(*kl, **kw)
# At the bottom of the draw_path method, added lines 131 - 132:
130 else:
131 # @warning: CHANGED FROM SOURCE to draw thinner lines
132 gc.set_linewidth(gc.get_linewidth()*PATH_SCALAR)
133 self._renderer.draw_path(gc, path, transform, rgbFace)
# At the bottom of the _get_agg_font method, added line 242 and the *FONT_SCALAR
241 font.clear()
242 # @warning: CHANGED FROM SOURCE to draw thinner lines
243 size = prop.get_size_in_points()*FONT_SCALAR
244 font.set_size(size, self.dpi)
So that suits my needs for now, but, depending on what you're doing, you may want to implement similar changes in other methods. Or find a better way to do the same without so many line changes!
Update: After posting an issue to the matplotlib project at Github, I was able to track down the source of my problem: I had changed the figure.dpi setting in the matplotlibrc file. If that value is different than the default, my savefig() images come out different, even if I set the savefig dpi to be the same as the figure dpi. So, instead of changing the source as above, I just kept the figure.dpi setting as the default 80, and was able to generate images with savefig() that looked like images from show().
Leon, had you also changed that setting?
You can simply use rotation atribute of ImageView
Below is the attribute from ImageView with details from Android source
<!-- rotation of the view, in degrees. -->
<attr name="rotation" format="float" />
The context object allows you to manipulate the canvas; you can draw rectangles for example and a lot more.
If you want to get the width and height, you can just use the standard HTML attributes width
and height
:
var canvas = document.getElementById( 'yourCanvasID' );
var ctx = canvas.getContext( '2d' );
alert( canvas.width );
alert( canvas.height );
I believe it would be like this
takedata.match(/(\[.+\])/g);
the g
at the end means global, so it doesn't stop at the first match.
Use $() to assign the output of cat
to your variable like this:
VAR=$(cat <<'END_HEREDOC'
abc'asdf"
$(dont-execute-this)
foo"bar"''
END_HEREDOC
)
# this will echo variable with new lines intact
echo "$VAR"
# this will echo variable without new lines (changed to space character)
echo $VAR
Making sure to delimit starting END_HEREDOC with single-quotes.
Note that ending heredoc delimiter END_HEREDOC
must be alone on the line (hence ending parenthesis is on the next line).
Thanks to @ephemient
for the answer.
Yes, that is supported.
Check the documentation provided here for the supported keywords inside method names.
You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:
List<Inventory> findByIdIn(List<Long> ids);
I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:
The Entity
@Entity
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
// other fields
// getters/setters
}
The Repository
@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {
List<Inventory> findByIdIn(List<Long> ids);
}
Another option is to use the built-in Command Palette, which will walk you right through cloning a Git repository to a new directory.
From Using Version Control in VS Code:
You can clone a Git repository with the Git: Clone command in the Command Palette (Windows/Linux: Ctrl + Shift + P, Mac: Command + Shift + P). You will be asked for the URL of the remote repository and the parent directory under which to put the local repository.
At the bottom of Visual Studio Code you'll get status updates to the cloning. Once that's complete an information message will display near the top, allowing you to open the folder that was created.
Note that Visual Studio Code uses your machine's Git installation, and requires 2.0.0 or higher.
If you want to be more targeted to the actual child component than you should do the follow. This way, if other child components share the same class name, they won't be affected.
Plunker: https://plnkr.co/edit/ooBRp3ROk6fbWPuToytO?p=preview
For example:
import {Component, NgModule } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>I'm the host parent</h2>
<child-component class="target1"></child-component><br/>
<child-component class="target2"></child-component><br/>
<child-component class="target3"></child-component><br/>
<child-component class="target4"></child-component><br/>
<child-component></child-component><br/>
</div>
`,
styles: [`
/deep/ child-component.target1 .child-box {
color: red !important;
border: 10px solid red !important;
}
/deep/ child-component.target2 .child-box {
color: purple !important;
border: 10px solid purple !important;
}
/deep/ child-component.target3 .child-box {
color: orange !important;
border: 10px solid orange !important;
}
/* this won't work because the target component is spelled incorrectly */
/deep/ xxxxchild-component.target4 .child-box {
color: orange !important;
border: 10px solid orange !important;
}
/* this will affect any component that has a class name called .child-box */
/deep/ .child-box {
color: blue !important;
border: 10px solid blue !important;
}
`]
})
export class App {
}
@Component({
selector: 'child-component',
template: `
<div class="child-box">
Child: This is some text in a box
</div>
`,
styles: [`
.child-box {
color: green;
border: 1px solid green;
}
`]
})
export class ChildComponent {
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, ChildComponent ],
bootstrap: [ App ]
})
export class AppModule {}
Hope this helps!
codematrix
The entire viewcontroller which show data in collecction view using two methods of json parsig
@IBOutlet weak var imagecollectionview: UICollectionView!
lazy var data = NSMutableData()
var dictdata : NSMutableDictionary = NSMutableDictionary()
override func viewDidLoad() {
super.viewDidLoad()
startConnection()
startNewConnection()
// Do any additional setup after loading the view, typically from a nib.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dictdata.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomcellCollectionViewCell", forIndexPath: indexPath) as! CustomcellCollectionViewCell
cell.name.text = dictdata.valueForKey("Data")?.valueForKey("location") as? String
let url = NSURL(string: (dictdata.valueForKey("Data")?.valueForKey("avatar_url") as? String)! )
LazyImage.showForImageView(cell.image, url:"URL
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let kWhateverHeightYouWant = 100
return CGSizeMake(self.view.bounds.size.width/2, CGFloat(kWhateverHeightYouWant))
}
func startNewConnection()
{
let url: URL = URL(string: "YOUR URL" as String)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "GET" //set the get or post according to your request
// request.cachePolicy = NSURLRequest.CachePolicy.ReloadIgnoringCacheData
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest) {
( data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("error")
return
}
let jsonString = NSString(data: data!, encoding:String.Encoding.utf8.rawValue) as! String
}
task.resume()
}
func startConnection(){
let urlPath: String = "your URL"
let url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func buttonAction(sender: UIButton!){
startConnection()
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
// put in function
return
}
print("JSONDictionary! \(JSONDictionary)")
dictdata.setObject(JSONDictionary, forKey: "Data")
imagecollectionview.reloadData()
}
catch let JSONError as NSError {
print("\(JSONError)")
} }
use UITextView instead of UITextField
Over the top obfuscation:
arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)
Shameless Plug:
Filepicker.io handles uploading for you and returns a url. It supports drag/drop, cross browser. Also, people can upload from Dropbox/Facebook/Gmail which is super handy on a mobile device.
React has a concept of components state, so if you want to Toggle, use setState:
- App.js
import React from 'react';
import TestState from './components/TestState';
class App extends React.Component {
render() {
return (
<div className="App">
<h1>React State Example</h1>
<TestState/>
</div>
);
}
}
export default App;
- components/TestState.js
import React from 'react';
class TestState extends React.Component
{
constructor()
{
super();
this.state = {
message: 'Please subscribe',
status: "Subscribe"
}
}
changeMessage()
{
if (this.state.status === 'Subscribe')
{
this.setState({message : 'Thank You For Scubscribing.', status: 'Unsubscribe'})
}
else
{
this.setState({ message: 'Please subscribe', status: 'Subscribe' })
}
}
render()
{
return (
<div>
<h1>{this.state.message}</h1>
<button onClick={()=> this.changeMessage() } >{this.state.status}</button>
</div>
)
}
}
export default TestState;
- Output
You have set the upstream of that branch
(see:
--set-upstream-to
all the time?"git branch -f --track my_local_branch origin/my_remote_branch # OR (if my_local_branch is currently checked out): $ git branch --set-upstream-to my_local_branch origin/my_remote_branch
(git branch -f --track
won't work if the branch is checked out: use the second command git branch --set-upstream-to
instead, or you would get "fatal: Cannot force update the current branch.
")
That means your branch is already configured with:
branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch
Git already has all the necessary information.
In that case:
# if you weren't already on my_local_branch branch:
git checkout my_local_branch
# then:
git pull
is enough.
If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch
', then a simple git push -u origin my_local_branch:my_remote_branch
would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull
or git push
would, again, have been enough.
Enter the submodule directory:
cd projB/projA
Pull the repo from you project A (will not update the git status of your parent, project B):
git pull origin master
Go back to the root directory & check update:
cd ..
git status
If the submodule updated before, it will show something like below:
# Not currently on any branch.
# Changed but not updated:
# (use "git add ..." to update what will be committed)
# (use "git checkout -- ..." to discard changes in working directory)
#
# modified: projB/projA (new commits)
#
Then, commit the update:
git add projB/projA
git commit -m "projA submodule updated"
UPDATE
As @paul pointed out, since git 1.8, we can use
git submodule update --remote --merge
to update the submodule to the latest remote commit. It'll be convenient in most cases.
If your jar file already has an absolute pathname as shown, it is particularly easy:
cd /where/you/want/it; jar xf /path/to/jarfile.jar
That is, you have the shell executed by Python change directory for you and then run the extraction.
If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar
can find it after the change of directory.
The only issues left to worry about are things like blanks in the path names.
I use BufferedInputStream
and BufferedOutputStream
to remove the buffering semantics from the code
try (OutputStream out = new BufferedOutputStream(...);
InputStream in = new BufferedInputStream(...))) {
int ch;
while ((ch = in.read()) != -1) {
out.write(ch);
}
}
1. First should understand the error meaning
Error not enough values to unpack (expected 3, got 2)
means:
a 2 part tuple, but assign to 3 values
and I have written demo code to show for you:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212
def notEnoughUnpack():
"""Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
# a dict, which single key's value is two part tuple
valueIsTwoPartTupleDict = {
"name1": ("lastname1", "email1"),
"name2": ("lastname2", "email2"),
}
# Test case 1: got value from key
gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
# gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)
# Test case 2: got from dict.items()
for eachKey, eachValues in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
# same as following:
# Background knowledge: each of dict.items() return (key, values)
# here above eachValues is a tuple of two parts
for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
# but following:
for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
pass
if __name__ == "__main__":
notEnoughUnpack()
using VSCode
debug effect:
2. For your code
for name, email, lastname in unpaidMembers.items():
but error
ValueError: not enough values to unpack (expected 3, got 2)
means each item(a tuple value) in unpaidMembers
, only have 1 parts:email
, which corresponding above code
unpaidMembers[name] = email
so should change code to:
for name, email in unpaidMembers.items():
to avoid error.
But obviously you expect extra lastname
, so should change your above code to
unpaidMembers[name] = (email, lastname)
and better change to better syntax:
for name, (email, lastname) in unpaidMembers.items():
then everything is OK and clear.
I got a similar failure with SMTP whenever my client machine changes network connection (e.g., home vs. office network) and somehow restarting network service (or rebooting the machine) resolves the issue for me. Not sure if this would apply to your case, but just in case.
sudo /etc/init.d/networking restart # for ubuntu
The built-in comparison operations differ as in when you compare 2 numbers with floating point, the difference in data type (i.e. float or double) may result in different outcomes.
Not sure if it was removed before, I heard it was kinda buggy in 0.5.8
but in AS 0.5.9
the settings is there:
Gradle > Global Gradle settings > Offline work
function function_one()_x000D_
{_x000D_
alert("The function called 'function_one' has been called.")_x000D_
//Here u would like to call function_two._x000D_
function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
Control Panel >> Windows Firewall
Advanced settings >> Inbound Rules >> World Wide Web Services - Enable it All or (Domain, Private, Public) as needed.
What is happening here is that database route does not accept any url methods.
I would try putting the url methods in the app route just like you have in the entry_page function:
@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
if request.method == 'POST':
date = request.form['date']
title = request.form['blog_title']
post = request.form['blog_main']
post_entry = models.BlogPost(date = date, title = title, post = post)
db.session.add(post_entry)
db.session.commit()
return redirect(url_for('database'))
else:
return render_template('entry.html')
@app.route('/database', methods=['GET', 'POST'])
def database():
query = []
for i in session.query(models.BlogPost):
query.append((i.title, i.post, i.date))
return render_template('database.html', query = query)
You can include a different jade file into your template, that to from a different directory
views/
layout.jade
static/
page.jade
To include the layout file from views dir to static/page.jade
page.jade
extends ../views/layout
You can install JavaDoc plugin from Settings->Plugin->Browse repositories.
get plugin documentation from the below link
there are different solutions to this problem but I at the first u have to check to (build.gradle) maybe it empty. this especially if u downloaded code, not u created
and u will find just this line "// Top-level build file where you can add configuration options common to all sub-projects/modules."
in this case, u need to open a new project and make copy-paste.then check the SDK and other settings.finally u have to sync
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
This is solved in my case.
JS
$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
options.async = true;
});
This answer was inserted in this link
https://stackoverflow.com/questions/28322636/synchronous-xmlhttprequest-warning-and-script
Since mysql_connect
has been deprecated, connect and query instead with mysqli:
$mysqli = new mysqli("hostname","username","password","database_name");
$sqlSelect="SELECT your_fieldname FROM your_table";
$result = $mysqli -> query ($sqlSelect);
And then, if you have more than one option list with the same values on the same page, put the values in an array:
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
And then you can loop the array multiple times on the same page:
foreach ($rows as $row) {
print "<option value='" . $row['your_fieldname'] . "'>" . $row['your_fieldname'] . "</option>";
}
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
JSONObject JObj = new JSONObject();
try {
JObj.put("Id","1");
JObj.put("Name", "abc");
} catch (Exception e) {
e.printStackTrace();
}
params.put("params", JObj.toString());
// Map.Entry<String,String>
Log.d("Parameter", params.toString());
return params;
}
Additional to nanselm2's answer, you can use 0
instead of False
:
df["col"].str.contains(word)==0
MinGW (or MinGW-w64) Cygwin
-------------------- ------
Your program written Your program written
for Unix and Linux for Unix and Linux
| |
| |
V V
Heavy modifications Almost no modifications
| |
| |
V V
Compilation Compilation
Program compiled with Cygwin ---> Compatibility layer ---> Windows API
Program compiled with MinGW (or MingGW-w64) -------------> Windows API
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
A bit late, but maybe someone finds it useful.
For me, ISNULL was out of question due to the table scan. UNION ALL would need me to repeat a complex query, and due to me selecting only the TOP X it would not have been very efficient.
If you are able to change the table design, you can:
Add another field, just for sorting, such as Next_Contact_Date_Sort.
Create a trigger that fills that field with a large (or small) value, depending on what you need:
CREATE TRIGGER FILL_SORTABLE_DATE ON YOUR_TABLE AFTER INSERT,UPDATE AS
BEGIN
SET NOCOUNT ON;
IF (update(Next_Contact_Date)) BEGIN
UPDATE YOUR_TABLE SET Next_Contact_Date_Sort=IIF(YOUR_TABLE.Next_Contact_Date IS NULL, 99/99/9999, YOUR_TABLE.Next_Contact_Date_Sort) FROM inserted i WHERE YOUR_TABLE.key1=i.key1 AND YOUR_TABLE.key2=i.key2
END
END
I managed to reproduce this error by doing the following.
CREATE DATABASE TESTING123
GO
USE TESTING123;
SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6
set lock_timeout 5;
ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
The complete list of the regexp_like and other regexp functions in Oracle 11.1:
http://66.221.222.85/reference/regexp.html
In your example:
SELECT X
FROM test
WHERE REGEXP_LIKE(X, '^[[:digit:]]$');
You can use the WebClient
Using System.Net;
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");
Alternatively you can use Minio Client aka mc. Its Open Source and compatible with AWS S3. It is available for Linux, Windows, Mac, FreeBSD.
All you have do do is to run mc ls command for listing the contents.
$ mc ls s3/kline/ [2016-04-30 13:20:47 IST] 1.1MiB 1.jpg [2016-04-30 16:03:55 IST] 7.5KiB docker.png [2016-04-30 15:16:17 IST] 50KiB pi.png [2016-05-10 14:34:39 IST] 365KiB upton.pdf
Note:
Installing Minio Client Linux Download mc for:
$ chmod 755 mc $ ./mc --help
Setting up AWS credentials with Minio Client
$ mc config host add mys3 https://s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
Note: Please replace mys3 with alias you would like for this account and ,BKIKJAA5BMMU2RHO6IBB, V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 with your AWS ACCESS-KEY and SECRET-KEY
Hope it helps.
Disclaimer: I work for Minio
Put the command
yum install php-gd
and restart the server (httpd, nginx, etc)
service httpd restart
It is related to generics in java. If I mentioned ArrayList<String>
that means I can add only String type object to that ArrayList.
The two major benefits of generics in Java are:
IUSR permissions
use on a folder if not under inetpub/wwwroot will be solution for some.
I've just asked a similar question and here's my solution based on answer received (using boost::filesystem
library):
#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int main()
{
path p("D:/AnyFolder");
for (auto i = directory_iterator(p); i != directory_iterator(); i++)
{
if (!is_directory(i->path())) //we eliminate directories in a list
{
cout << i->path().filename().string() << endl;
}
else
continue;
}
}
Output is like:
file1.txt
file2.dat
I am asking in general, how to write a compatible awk script that performs the same functionality ...
To solve the problem in your quesiton is easy. (check others' answer).
If you want to write an awk script, which portable to any awk implementations and versions (gawk/nawk/mawk...) it is really hard, even if with --posix (gawk)
for example:
\x
escape, some notFS
interpreter works differentlywell all the points above are just spoken in general. Back to your problem, you problem is only related to fundamental feature of awk. awk '{print $x}'
the line like that will work all awks.
There are two reasons why your awk line behaves differently on gawk and mawk:
your used substr()
function wrongly. this is the main cause. you have substr($0, 0, RSTART - 1)
the 0
should be 1
, no matter which awk do you use. awk array, string idx etc are 1-based.
gawk and mawk implemented substr()
differently.
Just search for "ab" in the string then negate the result:
!/ab/.test("bamboo"); // true
!/ab/.test("baobab"); // false
It seems easier and should be faster too.
For me, after trying all above solutions it ended up being a problem related to encoding. Concisely, my key was encoded using 'UTF-8 with BOM'. It should be UTF-8 instead.
To fix it, at least using VS Code follow this steps:
I suppose you can use other editors that support saving with the proper encoding.
Source: error:0906d06c:pem routines:pem_read_bio:no start line, when importing godaddy SSL certificate
P.D I did not need to set the encoding
to utf-8
option when loading the file using the fs.readFileSync
function.
Hope this helps somebody!
For simplicity's sake: newList = list(set(oldList))
But there are better options out there if you'd like to get speed/ordering/optimization instead: http://www.peterbe.com/plog/uniqifiers-benchmark
In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]
List<personClass> Getperson(string id);
In Java 11+ it's possible with variables too. The only condition is it must be a constant.
For Example:
final String LEFT = "left";
final String RIGHT = "right";
final String UP = "up";
final String DOWN = "down";
String var = ...;
switch (var) {
case LEFT:
case RIGHT:
case DOWN:
default:
return 0;
}
PS. I've not tried this with earlier jdks. So please update the answer if it's supported there too.
I don't think anyone has mentioned this: Use of alloca in a function will hinder or disable some optimizations that could otherwise be applied in the function, since the compiler cannot know the size of the function's stack frame.
For instance, a common optimization by C compilers is to eliminate use of the frame pointer within a function, frame accesses are made relative to the stack pointer instead; so there's one more register for general use. But if alloca is called within the function, the difference between sp and fp will be unknown for part of the function, so this optimization cannot be done.
Given the rarity of its use, and its shady status as a standard function, compiler designers quite possibly disable any optimization that might cause trouble with alloca, if would take more than a little effort to make it work with alloca.
UPDATE: Since variable-length local arrays have been added to C, and since these present very similar code-generation issues to the compiler as alloca, I see that 'rarity of use and shady status' does not apply to the underlying mechanism; but I would still suspect that use of either alloca or VLA tends to compromise code generation within a function that uses them. I would welcome any feedback from compiler designers.
Kotlin's way -
fun Context.bitMapFromImgUrl(imageUrl: String, callBack: (bitMap: Bitmap) -> Unit) {
GlideApp.with(this)
.asBitmap()
.load(imageUrl)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
callBack(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
// this is called when imageView is cleared on lifecycle call or for
// some other reason.
// if you are referencing the bitmap somewhere else too other than this imageView
// clear it here as you can no longer have the bitmap
}
})
}
If you want to edit and reissue a request that you have captured in Chrome Developer Tools' Network tab:
Name
of the requestCopy > Copy as cURL
I seem to have a blind spot as regards your html structure, but I think that this is what you're looking for. It should find the currently-selected option from the select
input, assign its text to the newVal
variable and then apply that variable to the value
attribute of the #costLabel
label:
$(document).ready(
function() {
$('select[name=package]').change(
function(){
var newText = $('option:selected',this).text();
$('#costLabel').text('Total price: ' + newText);
}
);
}
);
<form name="thisForm" id="thisForm" action="#" method="post">
<fieldset>
<select name="package" id="package">
<option value="standard">Standard - €55 Monthly</option>
<option value="standardAnn">Standard - €49 Monthly</option>
<option value="premium">Premium - €99 Monthly</option>
<option value="premiumAnn" selected="selected">Premium - €89 Monthly</option>
<option value="platinum">Platinum - €149 Monthly</option>
<option value="platinumAnn">Platinum - €134 Monthly</option>
</select>
</fieldset>
<fieldset>
<label id="costLabel" name="costLabel">Total price: </label>
</fieldset>
</form>
Working demo of the above at: JS Bin
You can simply use adb install command to install/update APK silently. Sample code is below
public static void InstallAPK(String filename){
File file = new File(filename);
if(file.exists()){
try {
String command;
filename = StringUtil.insertEscape(filename);
command = "adb install -r " + filename;
Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
your css file belongs into the public folder or a subfolder of it.
f.e if you put your css in
public/css/common.css
you would use
HTML::style('css/common.css');
In your blade view...
Or you could also use the Asset class http://laravel.com/docs/views/assets...
ip route | grep rmnet_data0 | cut -d" " -f1 | cut -d"/" -f1
Change rmnet_data0
to the desired nic, in my case, rmnet_data0
represents the data nic.
To get a list of the available nic's you can use ip route
follow some steps:
Clean Project
Rebuild Project
Invalidate Caches / Restart
Now run your project. Hope it will work.
It's work for me.
The information schema isn't the place to treat these things (see DDL database commands).
When you add a comment you need to change the table structure (table comments).
From MySQL 5.6 documentation:
INFORMATION_SCHEMA is a database within each MySQL instance, the place that stores information about all the other databases that the MySQL server maintains. The INFORMATION_SCHEMA database contains several read-only tables. They are actually views, not base tables, so there are no files associated with them, and you cannot set triggers on them. Also, there is no database directory with that name.
Although you can select INFORMATION_SCHEMA as the default database with a USE statement, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE operations on them.
#!/bin/bash
logPath="pinglog.txt"
while(true)
do
# refresh the timestamp before each ping attempt
theTime=$(date -Iseconds)
# refresh the ping variable
ping google.com -n 1
if [ $? -eq 0 ]
then
echo $theTime + '| connection is up' >> $logPath
else
echo $theTime + '| connection is down' >> $logPath
fi
Sleep 1
echo ' '
done
span
is an inline element that doesn't support vertical margins. Put the margin on the outer div
instead.
I found that I needed to have a default value, even if it was an empty string for it to work. So this:
this.registerForm('someName', {
firstName: new FormControl({disabled: true}),
});
...had to become this:
this.registerForm('someName', {
firstName: new FormControl({value: '', disabled: true}),
});
See my question (which I don't believe is a duplicate): Passing 'disabled' in form state object to FormControl constructor doesn't work
To count the number of different values in A2:A100 (not counting blanks):
=SUMPRODUCT((A2:A100<>"")/COUNTIF(A2:A100,A2:A100&""))
Copied from an answer by @Ulli Schmid to What is this COUNTIF() formula doing?:
=SUMPRODUCT((A1:A100<>"")/COUNTIF(A1:A100,A1:A100&""))
Counts unique cells within A1:A100, excluding blank cells and ones with an empty string ("").
How does it do that? Example:
A1:A100 = [1, 1, 2, "apple", "peach", "apple", "", "", -, -, -, ...]
then:
A1:A100&"" = ["1", "1", "2", "apple", "peach", "apple", "", "", "", "", "", ...]
so this &"" is needed to turn blank cells (-) into empty strings (""). If you were to count directly using blank cells, COUNTIF() returns 0. Using the trick, both "" and - are counted as the same:
COUNTIF(A1:A100,A1:A100) = [2, 2, 1, 2, 1, 2, 94, 94, 0, 0, 0, ...]
but:
COUNTIF(A1:A100,A1:A100&"") = [2, 2, 1, 2, 1, 2, 94, 94, 94, 94, 94, ...]
If we now want to get the count of all unique cells, excluding blanks and "", we can divide
(A1:A100<>""), which is [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, ...]
by our intermediate result, COUNTIF(A1:A100,A1:A100&""), and sum up over the values.
SUMPRODUCT((A1:A100<>"")/COUNTIF(A1:A100,A1:A100&""))
= (1/2 + 1/2 + 1/1 + 1/2 + 1/1 + 1/2 + 0/94 + 0/94 + 0/94 + 0/94 + 0/94 + ...)
= 4
Had we used COUNTIF(A1:A100,A1:A100)
instead of COUNTIF(A1:A100,A1:A100&"")
, then some of those 0/94 would have been 0/0. As division by zero is not allowed, we would have thrown an error.
to create the profile1.psl file, type in the following command:
new-item $PROFILE.CurrentUserAllHosts -ItemType file -Force
to access the file, type in the next command:
ise $PROFILE.CurrentUserAllHosts
note if you haven't done this before, you will see that you will not be able to run the script because of your execution policy, which you need to change to Unrestricted from Restricted (default).
to do that close the script and then type this command:
Set-ExecutionPolicy -Scope CurrentUser
then:
RemoteSigned
then this command again:
ise $PROFILE.CurrentUserAllHosts
then finally type your aliases in the script, save it, and they should run every time you run powershell, even after restarting your computer.
As the other answers said, it's because of the new System Integrity Protection, but I believe the other answers are overcomplicated.
If you're only gonna use that package in the current user, you should be able to install it just fine, without the need to disable the SIP, by using the --user
flag. Like this:
sudo pip install --user packagename
There is different ways to make dropdown menu using css. Here is simple code.
HTML Code
<label class="dropdown">
<div class="dd-button">
Dropdown
</div>
<input type="checkbox" class="dd-input" id="test">
<ul class="dd-menu">
<li>Dropdown 1</li>
<li>Dropdown 2</li>
</ul>
</label>
CSS Code
body {
color: #000000;
font-family: Sans-Serif;
padding: 30px;
background-color: #f6f6f6;
}
a {
text-decoration: none;
color: #000000;
}
a:hover {
color: #222222
}
/* Dropdown */
.dropdown {
display: inline-block;
position: relative;
}
.dd-button {
display: inline-block;
border: 1px solid gray;
border-radius: 4px;
padding: 10px 30px 10px 20px;
background-color: #ffffff;
cursor: pointer;
white-space: nowrap;
}
.dd-button:after {
content: '';
position: absolute;
top: 50%;
right: 15px;
transform: translateY(-50%);
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid black;
}
.dd-button:hover {
background-color: #eeeeee;
}
.dd-input {
display: none;
}
.dd-menu {
position: absolute;
top: 100%;
border: 1px solid #ccc;
border-radius: 4px;
padding: 0;
margin: 2px 0 0 0;
box-shadow: 0 0 6px 0 rgba(0,0,0,0.1);
background-color: #ffffff;
list-style-type: none;
}
.dd-input + .dd-menu {
display: none;
}
.dd-input:checked + .dd-menu {
display: block;
}
.dd-menu li {
padding: 10px 20px;
cursor: pointer;
white-space: nowrap;
}
.dd-menu li:hover {
background-color: #f6f6f6;
}
.dd-menu li a {
display: block;
margin: -10px -20px;
padding: 10px 20px;
}
.dd-menu li.divider{
padding: 0;
border-bottom: 1px solid #cccccc;
}
More css code example
Just escape your quotes:
echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
Can't we use
<properties>
<my.variable>${env.MY_VARIABLE}</my.variable>
</properties>
Here's a nice solution using Guava's com.google.common.primitives.Bytes
:
byte[] c = Bytes.concat(a, b);
The great thing about this method is that it has a varargs signature:
public static byte[] concat(byte[]... arrays)
which means that you can concatenate an arbitrary number of arrays in a single method call.
Simplify, simplify, simplify:
def p1(args):
whatever
def p2(more args):
whatever
myDict = {
"P1": p1,
"P2": p2,
...
"Pn": pn
}
def myMain(name):
myDict[name]()
That's all you need.
You might consider the use of dict.get
with a callable default if name
refers to an invalid function—
def myMain(name):
myDict.get(name, lambda: 'Invalid')()
(Picked this neat trick up from Martijn Pieters)
Or, if you're customizing the dialog using a theme defined in your style xml, put this line in your theme:
<item name="android:windowCloseOnTouchOutside">true</item>
Assuming you are trying to find if a div exists
$('div').length ? alert('div found') : alert('Div not found')
In my case Ubuntu 16.04
I have no crti.o
at all:
$ find /usr/ -name crti*
So I install developer libc6-dev package:
sudo apt-get install libc6-dev
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
That looks like Smarty to me. Smarty is a template parser written in PHP.
You can read up on how to use Smarty in the documentation.
If you can't get access to the CMS's source: To view the templates in your browser, just look at what variables Smarty is using and create a PHP file that populates the used variables with dummy data.
If I remember correctly, once Smarty is set up, you can use:
$smarty->assign('nameofvar', 'some data');
to set the variables.
Does this work?
Workbooks.Open Filename:=filepath, ReadOnly:=True
Or, as pointed out in a comment, to keep a reference to the opened workbook:
Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
Here's a simple solution, which worked well for me.
Using the moq mocking library.
// ARRANGE
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
.Protected()
// Setup the PROTECTED method to mock
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
// prepare the expected response of the mocked http call
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("[{'id':1,'value':'1'}]"),
})
.Verifiable();
// use real http client with mocked handler here
var httpClient = new HttpClient(handlerMock.Object)
{
BaseAddress = new Uri("http://test.com/"),
};
var subjectUnderTest = new MyTestClass(httpClient);
// ACT
var result = await subjectUnderTest
.GetSomethingRemoteAsync('api/test/whatever');
// ASSERT
result.Should().NotBeNull(); // this is fluent assertions here...
result.Id.Should().Be(1);
// also check the 'http' call was like we expected it
var expectedUri = new Uri("http://test.com/api/test/whatever");
handlerMock.Protected().Verify(
"SendAsync",
Times.Exactly(1), // we expected a single external request
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Get // we expected a GET request
&& req.RequestUri == expectedUri // to this uri
),
ItExpr.IsAny<CancellationToken>()
);
Source: https://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/
Use the following source code for copy multiple files on your client machine.
- name: Copy data to the client machine
hosts: hostname
become_method: sudo
become_user: root
become: true
tasks:
# Copy twice as sometimes files get skipped (mostly only one file skipped from a folder if the folder does not exist)
- name: Copy UFO-Server
copy:
src: "source files path"
dest: "destination file path"
owner: root
group: root
mode: 0644
backup: yes
ignore_errors: true
Note:
If you are passing multiple paths by using variable then
src: "/root/{{ item }}"
If you are passing path by using a variable for different items then
src: "/root/{{ item.source_path }}"
Oracle's error message should be somewhat longer. It usually looks like this:
ORA-00001: unique constraint (TABLE_UK1) violated
The name in parentheses is the constrait name. It tells you which constraint was violated.
Its because the email address which is being sent is blank. see those empty brackets? that means the email address is not being put in the $address of the swiftmailer function.
Basically it's like a DataReader, once read, data will be lost.
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TempData["T"] = "T";
return RedirectToAction("About");
}
public ActionResult About()
{
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
String str = TempData["T"]; //Output - T
return View();
}
}
If you pay attention to the above code, RedirectToAction has no impact over the TempData until TempData is read. So, once TempData is read, values will be lost.
Check the output in Action Method Test 1 and Test 2
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TempData["T"] = "T";
return RedirectToAction("About");
}
public ActionResult About()
{
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
string Str = Convert.ToString(TempData["T"]);
TempData.Keep(); // Keep TempData
return RedirectToAction("Test2");
}
public ActionResult Test2()
{
string Str = Convert.ToString(TempData["T"]); //OutPut - T
return View();
}
}
If you pay attention to the above code, data is not lost after RedirectToAction as well as after Reading the Data and the reason is, We are using TempData.Keep()
. is that
The Data will persist to the corresponding View
The gap between the (bootstrap) input field and jquery-ui autocompleter seem to occur only in jQuery versions >= 3.2
When using jQuery version 3.1.1 it seem to not happen.
Possible reason is the notable update in v3.2.0 related to a bug fix on .width()
and .height()
. Check out the jQuery release notes for further details: v3.2.0 / v3.1.1
Bootstrap version 3.4.1 and jquery-ui version 1.12.0 used
var startDate = moment(startDateVal, "DD.MM.YYYY");//Date format
var endDate = moment(endDateVal, "DD.MM.YYYY");
var isAfter = moment(startDate).isAfter(endDate);
if (isAfter) {
window.showErrorMessage("Error Message");
$(elements.endDate).focus();
return false;
}
Here is another simple way.
var es, log, logFile;
es = require('event-stream');
log = require('gulp-util').log;
logFile = function(es) {
return es.map(function(file, cb) {
log(file.path);
return cb();
});
};
gulp.task("do", function() {
return gulp.src('./examples/*.html')
.pipe(logFile(es))
.pipe(gulp.dest('./build'));
});
With Bootstrap 3, you can use the 'text-center' styling attribute.
<div class="col-md-3 text-center">
<button id="button" name="button" class="btn btn-primary">Press Me!</button>
</div>
$("button").click(function() {
alert(this.id); // or alert($(this).attr('id'));
});
The zoo
package has the function of as.yearmon
can help to convert.
require(zoo)
df$ym<-as.yearmon(df$date, "%Y %m")
Before version 1.8.2, **
didn't have any special meaning in the .gitignore
. As of 1.8.2 git supports **
to mean zero or more sub-directories (see release notes).
The way to ignore all directories called bin anywhere below the current level in a directory tree is with a .gitignore
file with the pattern:
bin/
In the man
page, there an example of ignoring a directory called foo
using an analogous pattern.
Edit:
If you already have any bin folders in your git index which you no longer wish to track then you need to remove them explicitly. Git won't stop tracking paths that are already being tracked just because they now match a new .gitignore
pattern. Execute a folder remove (rm) from index only (--cached) recursivelly (-r). Command line example for root bin folder:
git rm -r --cached bin
In my case, I did this
const eventId = event.id;
User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();
Try giving 5 ',' in every line, similar to line number 4.
you should write var element = [];
in javascript {}
is an empty object and []
is an empty array.
Moving file using kotlin. App has to have permission to write a file in destination directory.
@Throws(FileNotFoundException::class, IOError::class)
private fun moveTo(source: File, dest: File, destDirectory: File? = null) {
if (destDirectory?.exists() == false) {
destDirectory.mkdir()
}
val fis = FileInputStream(source)
val bufferLength = 1024
val buffer = ByteArray(bufferLength)
val fos = FileOutputStream(dest)
val bos = BufferedOutputStream(fos, bufferLength)
var read = fis.read(buffer, 0, read)
while (read != -1) {
bos.write(buffer, 0, read)
read = fis.read(buffer) // if read value is -1, it escapes loop.
}
fis.close()
bos.flush()
bos.close()
if (!source.delete()) {
HLog.w(TAG, klass, "failed to delete ${source.name}")
}
}
I know we have to use regex, but during an interview, I was asked to do WITHOUT USING REGEX.
@slightlytyler helped me in coming with the below approach.
const testStr = "I LOVE STACKOVERFLOW LOL";_x000D_
_x000D_
const removeSpaces = str => {_x000D_
const chars = str.split('');_x000D_
const nextChars = chars.reduce(_x000D_
(acc, c) => {_x000D_
if (c === ' ') {_x000D_
const lastChar = acc[acc.length - 1];_x000D_
if (lastChar === ' ') {_x000D_
return acc;_x000D_
}_x000D_
}_x000D_
return [...acc, c];_x000D_
},_x000D_
[],_x000D_
);_x000D_
const nextStr = nextChars.join('');_x000D_
return nextStr_x000D_
};_x000D_
_x000D_
console.log(removeSpaces(testStr));
_x000D_
The following may work with all the backends, but I tested it only on QT:
import numpy as np
import matplotlib.pyplot as plt
import time
plt.switch_backend('QT4Agg') #default on my system
print('Backend: {}'.format(plt.get_backend()))
fig = plt.figure()
ax = fig.add_axes([0,0, 1,1])
ax.axis([0,10, 0,10])
ax.plot(5, 5, 'ro')
mng = plt._pylab_helpers.Gcf.figs.get(fig.number, None)
mng.window.showMaximized() #maximize the figure
time.sleep(3)
mng.window.showMinimized() #minimize the figure
time.sleep(3)
mng.window.showNormal() #normal figure
time.sleep(3)
mng.window.hide() #hide the figure
time.sleep(3)
fig.show() #show the previously hidden figure
ax.plot(6,6, 'bo') #just to check that everything is ok
plt.show()
Strings and chars [version 1]
string.Join("", Enumerable.Repeat("text" , 2 ));
//result: texttext
Strings [version 2]:
String.Concat(Enumerable.Repeat("text", 2));
//result: texttext
Strings and chars [version 3]
new StringBuilder().Insert(0, "text", 2).ToString();
//result: texttext
Chars only:
'5' * 3;
//result: 555
(works FASTER - better for WEB)
public static class RepeatExtensions
{
public static string Repeat(this string str, int times)
{
return (new StringBuilder()).Insert(0, str, times).ToString();
}
}
usage:
var a = "Hello".Repeat(3);
//result: HelloHelloHello
You might consider adding an additional radio button to each group labeled 'none' or the like. This can create a consistent user experience without complicating the development process.
They contain byte code, which is what the Python interpreter compiles the source to. This code is then executed by Python's virtual machine.
Python's documentation explains the definition like this:
Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because of the presence of the bytecode compiler. This means that source files can be run directly without explicitly creating an executable which is then run.
docker container list -f "status=exited"
or
docker container ls -f "status=exited"
or
docker ps -f "status=exited"
to get current router in angular 8 just do this
import {ActivatedRoute} from '@angular/router';
then inject it in constructor like
constructor(private route: ActivatedRoute){}
if you want get current route then use this route.url
if you have multiply name route like /home/pages/list
and you wanna access individual then you can access each of like this route.url.value[0].path
value[0]
will give home, value[1]
will give you pages and value[2]
will give you list
As with everything that seems scarier at first than it was later, the best way to get over the initial fear is to immerse yourself into the discomfort of the unknown! It is at times like that which we learn the most, after all.
Unfortunately, there are limitations. While you're still learning to use a function, you shouldn't assume the role of a teacher, for example. I often read answers from those who seemingly don't know how to use realloc
(i.e. the currently accepted answer!) telling others how to use it incorrectly, occasionally under the guise that they've omitted error handling, even though this is a common pitfall which needs mention. Here's an answer explaining how to use realloc
correctly. Take note that the answer is storing the return value into a different variable in order to perform error checking.
Every time you call a function, and every time you use an array, you are using a pointer. The conversions are occurring implicitly, which if anything should be even scarier, as it's the things we don't see which often cause the most problems. For example, memory leaks...
Array operators are pointer operators. array[x]
is really a shortcut for *(array + x)
, which can be broken down into: *
and (array + x)
. It's most likely that the *
is what confuses you. We can further eliminate the addition from the problem by assuming x
to be 0
, thus, array[0]
becomes *array
because adding 0
won't change the value...
... and thus we can see that *array
is equivalent to array[0]
. You can use one where you want to use the other, and vice versa. Array operators are pointer operators.
malloc
, realloc
and friends don't invent the concept of a pointer which you've been using all along; they merely use this to implement some other feature, which is a different form of storage duration, most suitable when you desire drastic, dynamic changes in size.
It is a shame that the currently accepted answer also goes against the grain of some other very well-founded advice on StackOverflow, and at the same time, misses an opportunity to introduce a little-known feature which shines for exactly this usecase: flexible array members! That's actually a pretty broken answer... :(
When you define your struct
, declare your array at the end of the structure, without any upper bound. For example:
struct int_list {
size_t size;
int value[];
};
This will allow you to unite your array of int
into the same allocation as your count
, and having them bound like this can be very handy!
sizeof (struct int_list)
will act as though value
has a size of 0, so it'll tell you the size of the structure with an empty list. You still need to add to the size passed to realloc
to specify the size of your list.
Another handy tip is to remember that realloc(NULL, x)
is equivalent to malloc(x)
, and we can use this to simplify our code. For example:
int push_back(struct int_list **fubar, int value) {
size_t x = *fubar ? fubar[0]->size : 0
, y = x + 1;
if ((x & y) == 0) {
void *temp = realloc(*fubar, sizeof **fubar
+ (x + y) * sizeof fubar[0]->value[0]);
if (!temp) { return 1; }
*fubar = temp; // or, if you like, `fubar[0] = temp;`
}
fubar[0]->value[x] = value;
fubar[0]->size = y;
return 0;
}
struct int_list *array = NULL;
The reason I chose to use struct int_list **
as the first argument may not seem immediately obvious, but if you think about the second argument, any changes made to value
from within push_back
would not be visible to the function we're calling from, right? The same goes for the first argument, and we need to be able to modify our array
, not just here but possibly also in any other function/s we pass it to...
array
starts off pointing at nothing; it is an empty list. Initialising it is the same as adding to it. For example:
struct int_list *array = NULL;
if (!push_back(&array, 42)) {
// success!
}
P.S. Remember to free(array);
when you're done with it!
You could pass a Class<T>
in.
private void foo(Class<?> cls) {
if (cls == String.class) { ... }
else if (cls == int.class) { ... }
}
private void bar() {
foo(String.class);
}
Update: the OOP way depends on the functional requirement. Best bet would be an interface defining foo()
and two concrete implementations implementing foo()
and then just call foo()
on the implementation you've at hand. Another way may be a Map<Class<?>, Action>
which you could call by actions.get(cls)
. This is easily to be combined with an interface and concrete implementations: actions.get(cls).foo()
.
If you can use inline styling, you can set the left and right padding on each td
.. Or you use an extra td
between columns and set a number of non-breaking spaces as @rene kindly suggested.
Both are pretty ugly ;p css ftw
If you have to ask this question then you're probably unfamiliar with what most web applications/services do. You're probably thinking that all software do this:
user do an action
¦
v
application start processing action
+--> loop ...
+--> busy processing
end loop
+--> send result to user
However, this is not how web applications, or indeed any application with a database as the back-end, work. Web apps do this:
user do an action
¦
v
application start processing action
+--> make database request
+--> do nothing until request completes
request complete
+--> send result to user
In this scenario, the software spend most of its running time using 0% CPU time waiting for the database to return.
Multithreaded network apps handle the above workload like this:
request --> spawn thread
+--> wait for database request
+--> answer request
request --> spawn thread
+--> wait for database request
+--> answer request
request --> spawn thread
+--> wait for database request
+--> answer request
So the thread spend most of their time using 0% CPU waiting for the database to return data. While doing so they have had to allocate the memory required for a thread which includes a completely separate program stack for each thread etc. Also, they would have to start a thread which while is not as expensive as starting a full process is still not exactly cheap.
Since we spend most of our time using 0% CPU, why not run some code when we're not using CPU? That way, each request will still get the same amount of CPU time as multithreaded applications but we don't need to start a thread. So we do this:
request --> make database request
request --> make database request
request --> make database request
database request complete --> send response
database request complete --> send response
database request complete --> send response
In practice both approaches return data with roughly the same latency since it's the database response time that dominates the processing.
The main advantage here is that we don't need to spawn a new thread so we don't need to do lots and lots of malloc which would slow us down.
The seemingly mysterious thing is how both the approaches above manage to run workload in "parallel"? The answer is that the database is threaded. So our single-threaded app is actually leveraging the multi-threaded behaviour of another process: the database.
A singlethreaded app fails big if you need to do lots of CPU calculations before returning the data. Now, I don't mean a for loop processing the database result. That's still mostly O(n). What I mean is things like doing Fourier transform (mp3 encoding for example), ray tracing (3D rendering) etc.
Another pitfall of singlethreaded apps is that it will only utilise a single CPU core. So if you have a quad-core server (not uncommon nowdays) you're not using the other 3 cores.
A multithreaded app fails big if you need to allocate lots of RAM per thread. First, the RAM usage itself means you can't handle as many requests as a singlethreaded app. Worse, malloc is slow. Allocating lots and lots of objects (which is common for modern web frameworks) means we can potentially end up being slower than singlethreaded apps. This is where node.js usually win.
One use-case that end up making multithreaded worse is when you need to run another scripting language in your thread. First you usually need to malloc the entire runtime for that language, then you need to malloc the variables used by your script.
So if you're writing network apps in C or go or java then the overhead of threading will usually not be too bad. If you're writing a C web server to serve PHP or Ruby then it's very easy to write a faster server in javascript or Ruby or Python.
Some web servers use a hybrid approach. Nginx and Apache2 for example implement their network processing code as a thread pool of event loops. Each thread runs an event loop simultaneously processing requests single-threaded but requests are load-balanced among multiple threads.
Some single-threaded architectures also use a hybrid approach. Instead of launching multiple threads from a single process you can launch multiple applications - for example, 4 node.js servers on a quad-core machine. Then you use a load balancer to spread the workload amongst the processes.
In effect the two approaches are technically identical mirror-images of each other.
For Windows host, I want to highly recommend this tutorial::
Nothing more, nothing less!
Prebuilt GNU Toolchains available for Raspberry, Beaglebone, Cubieboard, AVR (Atmel) and more
It is a hard question in the C/C++ world, with so many elements beyond the standard.
I think header file order is not a serious problem as long as it compiles, like squelart said.
My ideas is: If there is no conflict of symbols in all those headers, any order is OK, and the header dependency issue can be fixed later by adding #include lines to the flawed .h.
The real hassle arises when some header changes its action (by checking #if conditions) according to what headers are above.
For example, in stddef.h in VS2005, there is:
#ifdef _WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
Now the problem: If I have a custom header ("custom.h") that needs to be used with many compilers, including some older ones that don't provide offsetof
in their system headers, I should write in my header:
#ifndef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
And be sure to tell the user to #include "custom.h"
after all system headers, otherwise, the line of offsetof
in stddef.h will assert a macro redefinition error.
We pray not to meet any more of such cases in our career.
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720