I've made a plugin vim-textobj-quotes
: https://github.com/beloglazov/vim-textobj-quotes
It provides text objects for the closest pairs of quotes of any type. Using only iq
or aq
it allows you to operate on the content of single ('), double ("), or back (`) quotes that currently surround the cursor, are in front of the cursor, or behind (in that order of preference). In other words, it jumps forward or backwards when needed to reach the quotes.
It's easier to understand by looking at examples (the cursor is shown with |
):
foo '1, |2, 3' bar
; after pressing diq
: foo '|' bar
foo| '1, 2, 3' bar
; after pressing diq
: foo '|' bar
foo '1, 2, 3' |bar
; after pressing diq
: foo '|' bar
foo '1, |2, 3' bar
; after pressing daq
: foo | bar
foo| '1, 2, 3' bar
; after pressing daq
: foo | bar
foo '1, 2, 3' |bar
; after pressing daq
: foo | bar
The examples above are given for single quotes, the plugin works exactly the same way for double (") and back (`) quotes.
You can also use any other operators: ciq
, diq
, yiq
, viq
, etc.
Please have a look at the github page linked above for more details.
I received such an error in a Python-based web API's response .text
, but it led me here, so this may help others with a similar issue (it's very difficult to filter response and request issues in a search when using requests
..)
Using json.dumps()
on the request data
arg to create a correctly-escaped string of JSON before POSTing fixed the issue for me
requests.post(url, data=json.dumps(data))
If you want to install a bunch of dependencies from, say a requirements.txt, you would do:
mkdir dependencies
pip download -r requirements.txt -d "./dependencies"
tar cvfz dependencies.tar.gz dependencies
And, once you transfer the dependencies.tar.gz to the machine which does not have internet you would do:
tar zxvf dependencies.tar.gz
cd dependencies
pip install * -f ./ --no-index
Please use Like below.
<a style="cursor: pointer" **(click)="yourFunctionComponent()"** >
<i class="fa fa-dribbble fa-4x"></i>
</a>
The above can be used so that the fa icon will be shown and also on the click function you could write your logic.
Swift 4.2 / Xcode 10.1:
Just uncheck behavior Enabled in your storyboard -> attributes inspector.
kw=(EditText)findViewById(R.id.kw);
btn=(Button)findViewById(R.id.btn);
cost=(TextView )findViewById(R.id.cost);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { cst = Double.valueOf(kw.getText().toString());
cst = cst*0.551;
cost.setText(cst.toString());
}
});
Try this:
private string GetJArrayValue(JObject yourJArray, string key)
{
foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
{
if (key == keyValuePair.Key)
{
return keyValuePair.Value.ToString();
}
}
}
I added the DLLs manually. Right clicked on References in the project, select Add Reference and then in the dialog pressed the Browse button. The NuGet DLLs where in the packages directory of the solution. To get the names of them you can right click on references in another project that's working properly and select properties and look in the path property.
The Popup class might be better than the Stage class, depending on what you want. Stage is either modal (you can't click on anything else in your app) or it vanishes if you click elsewhere in your app (because it's a separate window). Popup stays on top but is not modal.
See this Popup Window example.
The default for ResultSet.getInt
when the field value is NULL
is to return 0
, which is also the default value for your iVal
declaration. In which case your test is completely redundant.
If you actually want to do something different if the field value is NULL, I suggest:
int iVal = 0;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
iVal = rs.getInt("ID_PARENT");
if (rs.wasNull()) {
// handle NULL field value
}
}
(Edited as @martin comments below; the OP code as written would not compile because iVal
is not initialised)
I have the same problem. Mine is caused by a vmware installation. It is vmware worstation v8 on windows 7 and was a default installation.
Running netstat -aon | find ":80" | find "LISTENING" from cmd showed PID of the service causing the problem, this related to vmware. Going to services, I manually stopped all of the running vmware services (did not change their start up type, just a manual stop - I want them to work again after the next reboot) I could immediately test my webservice, glassfish 4 started as it should.
Hope it helps
On Mac OS X El Capitan I had to run these two commands to fix this error:
xcode-select --install
pip install lxml
Which ended up installing lxml-3.5.0
When you run the xcode-select command you may have to sign a EULA (so have an X-Term handy for the UI if you're doing this on a headless machine).
http://joda-time.sourceforge.net/quickstart.html
Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:
* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class
5 Jan 2021: link update thanks to @Sadap's comment.
Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.
For example, you can see that _WIN32
is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).
Anyway, I found the tables quite informative and thought I'd share here.
You need to download log4j and add in your classpath.
Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.
I also think that throwing checked exceptions can be OK1, assuming that the checked exception is 1) declared, 2) specific to the problem you are reporting, and 3) it is reasonable to expect the caller to deal with a checked exception for this2.
However explicitly declaring or throwing java.lang.Exception
is almost always bad practice.
You should pick an exception class that matches the exceptional condition that has occurred. If you throw Exception
it is difficult for the caller to separate this exception from any number of other possible declared and undeclared exceptions. This makes error recovery difficult, and if the caller chooses to propagate the Exception, the problem just spreads.
1 - Some people may disagree, but IMO there is no substantive difference between this case and the case of throwing exceptions in methods. The standard checked vs unchecked advice applies equally to both cases.
2 - For example, the existing FileInputStream
constructors will throw FileNotFoundException
if you try to open a file that does not exist. Assuming that it is reasonable for FileNotFoundException
to be a checked exception3, then the constructor is the most appropriate place for that exception to be thrown. If we threw the FileNotFoundException
the first time that (say) a read
or write
call was made, that is liable to make application logic more complicated.
3 - Given that this is one of the motivating examples for checked exceptions, if you don't accept this you are basically saying that all exceptions should be unchecked. That is not practical ... if you are going to use Java.
Someone suggested using assert
for checking arguments. The problem with this is that checking of assert
assertions can be turned on and off via a JVM command-line setting. Using assertions to check internal invariants is OK, but using them to implement argument checking that is specified in your javadoc is not a good idea ... because it means your method will only strictly implement the specification when assertion checking is enabled.
The second problem with assert
is that if an assertion fails, then AssertionError
will be thrown, and received wisdom is that it is a bad idea to attempt to catch Error
and any of its subtypes.
I'm new to flutter. I found that one can also achieve it this way.
tabs: [
for (var title in movieTitles) Tab(text: title)
]
Note: It requires dart sdk version to be >= 2.3.0, see here
Simply put, numpy.newaxis
is used to increase the dimension of the existing array by one more dimension, when used once. Thus,
1D array will become 2D array
2D array will become 3D array
3D array will become 4D array
4D array will become 5D array
and so on..
Here is a visual illustration which depicts promotion of 1D array to 2D arrays.
Scenario-1: np.newaxis
might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector, as depicted in the above picture.
Example:
# 1D array
In [7]: arr = np.arange(4)
In [8]: arr.shape
Out[8]: (4,)
# make it as row vector by inserting an axis along first dimension
In [9]: row_vec = arr[np.newaxis, :] # arr[None, :]
In [10]: row_vec.shape
Out[10]: (1, 4)
# make it as column vector by inserting an axis along second dimension
In [11]: col_vec = arr[:, np.newaxis] # arr[:, None]
In [12]: col_vec.shape
Out[12]: (4, 1)
Scenario-2: When we want to make use of numpy broadcasting as part of some operation, for instance while doing addition of some arrays.
Example:
Let's say you want to add the following two arrays:
x1 = np.array([1, 2, 3, 4, 5])
x2 = np.array([5, 4, 3])
If you try to add these just like that, NumPy will raise the following ValueError
:
ValueError: operands could not be broadcast together with shapes (5,) (3,)
In this situation, you can use np.newaxis
to increase the dimension of one of the arrays so that NumPy can broadcast.
In [2]: x1_new = x1[:, np.newaxis] # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
# [2],
# [3],
# [4],
# [5]])
Now, add:
In [3]: x1_new + x2
Out[3]:
array([[ 6, 5, 4],
[ 7, 6, 5],
[ 8, 7, 6],
[ 9, 8, 7],
[10, 9, 8]])
Alternatively, you can also add new axis to the array x2
:
In [6]: x2_new = x2[:, np.newaxis] # x2[:, None]
In [7]: x2_new # shape is (3, 1)
Out[7]:
array([[5],
[4],
[3]])
Now, add:
In [8]: x1 + x2_new
Out[8]:
array([[ 6, 7, 8, 9, 10],
[ 5, 6, 7, 8, 9],
[ 4, 5, 6, 7, 8]])
Note: Observe that we get the same result in both cases (but one being the transpose of the other).
Scenario-3: This is similar to scenario-1. But, you can use np.newaxis
more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).
Example:
In [124]: arr = np.arange(5*5).reshape(5,5)
In [125]: arr.shape
Out[125]: (5, 5)
# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis] # arr[None, ..., None, None]
In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)
As an alternative, you can use numpy.expand_dims
that has an intuitive axis
kwarg.
# adding new axes at 1st, 4th, and last dimension of the resulting array
In [131]: newaxes = (0, 3, -1)
In [132]: arr_5D = np.expand_dims(arr, axis=newaxes)
In [133]: arr_5D.shape
Out[133]: (1, 5, 5, 1, 1)
More background on np.newaxis vs np.reshape
newaxis
is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.
np.newaxis
uses the slicing operator to recreate the array while numpy.reshape
reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape
to happen).
Example
In [13]: A = np.ones((3,4,5,6))
In [14]: B = np.ones((4,6))
In [15]: (A + B[:, np.newaxis, :]).shape # B[:, None, :]
Out[15]: (3, 4, 5, 6)
In the above example, we inserted a temporary axis between the first and second axes of B
(to use broadcasting). A missing axis is filled-in here using np.newaxis
to make the broadcasting operation work.
General Tip: You can also use None
in place of np.newaxis
; These are in fact the same objects.
In [13]: np.newaxis is None
Out[13]: True
P.S. Also see this great answer: newaxis vs reshape to add dimensions
You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL
If selection is not important, it is better to use an ItemsControl wrapped in a ScrollViewer. This combination is more light-weight than the Listbox (which actually is derived from ItemsControl already) and using it would eliminate the need to use a cheap hack to override behavior that is already absent from the ItemsControl.
In cases where the selection behavior IS actually important, then this obviously will not work. However, if you want to change the color of the Selected Item Background in such a way that it is not visible to the user, then that would only serve to confuse them. In cases where your intention is to change some other characteristic to indicate that the item is selected, then some of the other answers to this question may still be more relevant.
Here is a skeleton of how the markup should look:
<ScrollViewer>
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.
With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.
http://www.dba-oracle.com/t_with_clause.htm
It requires some effort though. Don't be afraid to post a concrete example.
Using simple pseudo table DUAL helps too.
Yes, you can use Type.InvokeMember()
:
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
This will throw an exception if obj
doesn't have a property called Name
, or it can't be set.
Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
You can simply pass the functions as a list:
In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:
mean sum
dummy
1 0.036901 0.369012
or as a dictionary:
In [21]: df.groupby('dummy').agg({'returns':
{'Mean': np.mean, 'Sum': np.sum}})
Out[21]:
returns
Mean Sum
dummy
1 0.036901 0.369012
If you're comparing them in unit test, a handy alternative is EqualValues function in testify.
I wanted to note that the fourth part of Accepted Answer is wrong .
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
The above code as @Karl Zilles wrote will fail because obj
will always be returned before it receives data (thus the value will always be null
) and this is because we are making an Asynchronous call.
The details of similar questions are discussed in this post
In Angular, use $promise
to deal with the fetched data when you want to make an asynchronous call.
The simplest version is
theApp.factory('mainInfo', function($http) {
return {
get: function(){
$http.get('content.json'); // this will return a promise to controller
}
});
// and in controller
mainInfo.get().then(function(response) {
$scope.foo = response.data.contentItem;
});
The reason I don't use success
and error
is I just found out from the doc, these two methods are deprecated.
The
$http
legacy promise methods success and error have been deprecated. Use the standardthen
method instead.
I had to create new db on my local for testing & i had a back up from my prod. I created the db first and tried to run the BAK on top of the new db which produced this error for me. I deleted the db and restored it while sourcing the new db name in the restore screen itself. The db was automatically created on restore.
function dupData() {
var arr = [{ comment: ["a", "a", "bbb", "xyz", "bbb"] }];
let newData = [];
comment.forEach(function (val, index) {
if (comment.indexOf(val, index + 1) > -1) {
if (newData.indexOf(val) === -1) { newData.push(val) }
}
})
}
In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:
var startTimeout = function(timeout, i){
setTimeout(function() {
myAsyncFunc(i).then(function(data){
console.log(data);
})
}, timeout);
}
var myFunc = function(){
timeout = 0;
i = 0;
while(i < 10){
// By calling a function, the i-value is going to be 1.. 10 and not always 10
startTimeout(timeout, i);
// Increase timeout by 1 sec after each call
timeout += 1000;
i++;
}
}
This examples waits 1 second after each request before sending the next one.
This worked for me!
To run projects like http://localhost/projectName
<VirtualHost localhost:80>
ServerAdmin localhost
DocumentRoot path/to/htdocs/
ServerName localhost
</VirtualHost>
To run projects like http://somewebsite.com
locally
<VirtualHost somewebsite.com:80>
ServerAdmin [email protected]
DocumentRoot /path/to/htdocs/somewebsiteFolder
ServerName www.somewebsite.com
ServerAlias somewebsite.com
</VirtualHost>
Same for other websites
<VirtualHost anothersite.local:80>
ServerAdmin [email protected]
DocumentRoot /path/to/htdocs/anotherSiteFolder
ServerName www.anothersite.local
ServerAlias anothersite.com
</VirtualHost>
^\w{0,10}$ # allows words of up to 10 characters.
^\w{5,}$ # allows words of more than 4 characters.
^\w{5,10}$ # allows words of between 5 and 10 characters.
From the doc :
Capturing groups</a> are indexed from left
* to right, starting at one. Group zero denotes the entire pattern, so
* the expression m.group(0) is equivalent to m.group().
So capture group 0 send the whole line.
For the record:
"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".
I also noticed that the query
SELECT * FROM tablename;
gives an error on the psql command prompt and
SELECT * FROM "tablename";
runs fine, really strange, so don't forget the double quotes. I always liked databases :-(
Using an in
can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:
SELECT *
FROM (SELECT msisdn
,callid
,Change_color
,play_file_name
,date_played
FROM insert_log
WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
ORDER BY callid ASC) t1
JOIN (SELECT MAX(date_played) AS date_played
FROM insert_log GROUP BY callid) t2
ON t1.date_played = t2.date_played
I have found a blog article by Deborah Kurata with a nice trick how to show variable number of columns in a DataGrid:
Populating a DataGrid with Dynamic Columns in a Silverlight Application using MVVM
Basically, she creates a DataGridTemplateColumn
and puts ItemsControl
inside that displays multiple columns.
This answer is based on the question and title of this book: http://www.packtpub.com/angularjs-web-application-development/book
This worked for me best for all navigation changes including hash navigation
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this._sub = this.route.fragment.subscribe((hash: string) => {
if (hash) {
const cmp = document.getElementById(hash);
if (cmp) {
cmp.scrollIntoView();
}
} else {
window.scrollTo(0, 0);
}
});
}
Like this:
String versionRelease = BuildConfig.VERSION_NAME;
versionRelease :- 2.1.17
Please make sure your import package is correct ( import package your_application_package_name
, otherwise it will not work properly).
If you are using SQL Server (starting with 2008), choose one of this:
I like using ls
options, for sample:
-l
use a long listing format-t
sort by modification time, newest first-r
reverse order while sorting-F
,--classify
append indicator (one of */=>@|) to entries-h
,--human-readable
with -l and -s, print sizes like 1K 234M 2G etc...
Sometime --color
and all others. (See ls --help
)
This will show files, symlinks, devices, pipe, sockets etc.
so
find /some/path -maxdepth 1 ! -type d
could be sorted by date easily:
find /some/path -maxdepth 1 ! -type d -exec ls -hltrF {} +
or
find /some/path -maxdepth 1 -type f
sorted by size:
find /some/path -maxdepth 1 -type f -exec ls -lSF --color {} +
To not show hidden entries, where name begin by a dot, you could add ! -name '.*'
:
find /some/path -maxdepth 1 ! -type d ! -name '.*' -exec ls -hltrF {} +
Then
You could replace /some/path
by .
to list for current directory or ..
for parent directory.
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
Upload your file to Skydrive and then right click and select "Embed". They will provide iframe snippet which you can paste in your html. This works flawlessly.
Source: Office.com
I just wanted to add that "Include" is part of eager loading. It is described in Entity Framework 6 tutorial by Microsoft. Here is the link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
Excerpt from the linked page:
Here are several ways that the Entity Framework can load related data into the navigation properties of an entity:
Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. This results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved. The DbContext class enables lazy loading by default.
Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the
Include
method.Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace
Collection(x => x.Courses)
withReference(x => x.Administrator)
.) Typically you'd use explicit loading only when you've turned lazy loading off.Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.
I was finding same but lastly i found an answer. I hope this answer help you so much.
when your array is empty then you can send empty array just like
if(!empty($result))
{
echo json_encode($result);
}
else
{
echo json_encode(array('data'=>''));
}
Thank you
In certain cases, like a link spanning over multiple rows in non justified text, you can get the row count and every coordinate of each line, when you use this:
var rectCollection = object.getClientRects();
https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects
This works because each line would be different even so slightly. As long as they are, they are drawn as a different "rectangle" by the renderer.
Another method could be to split the string by ":" and then pop off the end.
var newString = string.split(":").pop();
Check out CodingBat! It really helped me learn java way back when (although it used to be JavaBat back then). It's a lot like Codecademy.
Adding on to the one mentioned by @abarnert
a better one is to catch the exception
import subprocess
try:
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)
#print('py2 said:', py2output)
print "here"
except subprocess.CalledProcessError as e:
print "Calledprocerr"
this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting
python: can't open file 'py2.py': [Errno 2] No such file or directory
Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script
function Parent() {_x000D_
const [Name, setName] = useState("");_x000D_
getChildChange = getChildChange.bind(this);_x000D_
function getChildChange(value) {_x000D_
setName(value);_x000D_
}_x000D_
_x000D_
return <div> {Name} :_x000D_
<Child getChildChange={getChildChange} ></Child>_x000D_
</div>_x000D_
}_x000D_
_x000D_
function Child(props) {_x000D_
const [Name, setName] = useState("");_x000D_
handleChange = handleChange.bind(this);_x000D_
collectState = collectState.bind(this);_x000D_
_x000D_
function handleChange(ele) {_x000D_
setName(ele.target.value);_x000D_
}_x000D_
_x000D_
function collectState() {_x000D_
return Name;_x000D_
}_x000D_
_x000D_
useEffect(() => {_x000D_
props.getChildChange(collectState());_x000D_
});_x000D_
_x000D_
return (<div>_x000D_
<input onChange={handleChange} value={Name}></input>_x000D_
</div>);_x000D_
}
_x000D_
useEffect
act as componentDidMount, componentDidUpdate, so after updating state it will work
You could try removing any alphanumeric characters and space. And then use -n
will give you the line number. Try following:
grep -vn "^[a-zA-Z0-9 ]*$" application.log
For improving accepted answer use this:
Number($(this).css('marginBottom').replace(/[^-\d\.]/g, ''));
The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<distributionManagement>
<repository>
<id>nexus-site</id>
<url>http://central_nexus/server</url>
</repository>
</distributionManagement>
</project>
This can be built, released, and deployed to your local nexus so everyone has access to its artifact.
Now for all projects which you wish to use it, simply include this section:
<parent>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0</version>
</parent>
This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.
If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.
I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.
- pom.xml (aggregator)
- project-parent
- project-module1
- project-module2
What you do with this structure is include your parent module in the aggregator and build everything with a mvn install
from the root directory.
We use this exact solution at my organization and it has stood the test of time and worked quite well for us.
You can also do this with linq if you'd like
var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);
Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate
might perform slower (probably more string concatenation operations).
Go here: https://github.com/search and enter "pattern repo:user_name/repo_name".
For example, to search for cnn_learner
in the fastai
repo of user fastai
, enter this:
cnn_learner repo:fastai/fastai
That's it. The only annoyance is you'll need an extra click. It will tell you:
We couldn’t find any repositories matching 'cnn_learner repo:fastai/fastai'
because by default it searches for repositories matching that search string...
So just click on the left on "Code" and it will display what you want.
Or get the code search results directly with a URL like this:
https://github.com/search?q=cnn_learner+repo%3Afastai%2Ffastai&type=code
I prefer approach of Tommy Carlier, but with a little change.
foreach (DataColumn column in row.Table.Columns)
if (!row.IsNull(column))
return false;
return true;
I suppose this approach looks more simple and bright.
https://github.com/nodejs/node-gyp/issues/629#issuecomment-153196245
Some npm plugins need node-gyp
to be installed.
However, node-gyp
has it's own dependencies (from the github page):
If you're using Windows you can now install all node-gyp
dependencies with single command (NOTE: Run As Admin in Windows PowerShell):
$ npm install --global --production windows-build-tools
and then install the package
$ npm install --global node-gyp
https://github.com/nodejs/node-gyp/issues/809#issuecomment-155019383
Delete your $HOME/.node-gyp directory and try again.
See full documentation here: node-gyp
Though this question already has sufficient answers, I thought somebody would want to know why this flag works in this peculiar manner, This is what I found in Android documentation
The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent.
If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().
So, Either,
1. Change the launchMode
of the Activity A to something else from standard (ie. singleTask
or something). Then your flag FLAG_ACTIVITY_CLEAR_TOP
will not restart your Activity A.
or,
2. Use Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
as your flag. Then it will work the way you desire.
That proof of concept you made was great! However I also found this jQuery plugin which seems to be working very well. Hope it helps!
Maybe useful for someone:
If you want to use plain options instead of ng-options, you could do like below:
<select ng-model="sortorder" ng-init="sortorder='publish_date'">
<option value="publish_date">Ascending</option>
<option value="-publish_date">Descending</option>
</select>
Set the model inline. Use ng-init to get rid of empty option
There is another solution that does not need modifying source code of ViewPager
and FragmentStatePagerAdapter
, and it works with the FragmentPagerAdapter
base class used by the author.
I'd like to start by answering the author's question about which ID he should use; it is ID of the container, i.e. ID of the view pager itself. However, as you probably noticed yourself, using that ID in your code causes nothing to happen. I will explain why:
First of all, to make ViewPager
repopulate the pages, you need to call notifyDataSetChanged()
that resides in the base class of your adapter.
Second, ViewPager
uses the getItemPosition()
abstract method to check which pages should be destroyed and which should be kept. The default implementation of this function always returns POSITION_UNCHANGED
, which causes ViewPager
to keep all current pages, and consequently not attaching your new page. Thus, to make fragment replacement work, getItemPosition()
needs to be overridden in your adapter and must return POSITION_NONE
when called with an old, to be hidden, fragment as argument.
This also means that your adapter always needs to be aware of which fragment that should be displayed in position 0, FirstPageFragment
or NextFragment
. One way of doing this is supplying a listener when creating FirstPageFragment
, which will be called when it is time to switch fragments. I think this is a good thing though, to let your fragment adapter handle all fragment switches and calls to ViewPager
and FragmentManager
.
Third, FragmentPagerAdapter
caches the used fragments by a name which is derived from the position, so if there was a fragment at position 0, it will not be replaced even though the class is new. There are two solutions, but the simplest is to use the remove()
function of FragmentTransaction
, which will remove its tag as well.
That was a lot of text, here is code that should work in your case:
public class MyAdapter extends FragmentPagerAdapter
{
static final int NUM_ITEMS = 2;
private final FragmentManager mFragmentManager;
private Fragment mFragmentAtPos0;
public MyAdapter(FragmentManager fm)
{
super(fm);
mFragmentManager = fm;
}
@Override
public Fragment getItem(int position)
{
if (position == 0)
{
if (mFragmentAtPos0 == null)
{
mFragmentAtPos0 = FirstPageFragment.newInstance(new FirstPageFragmentListener()
{
public void onSwitchToNextFragment()
{
mFragmentManager.beginTransaction().remove(mFragmentAtPos0).commit();
mFragmentAtPos0 = NextFragment.newInstance();
notifyDataSetChanged();
}
});
}
return mFragmentAtPos0;
}
else
return SecondPageFragment.newInstance();
}
@Override
public int getCount()
{
return NUM_ITEMS;
}
@Override
public int getItemPosition(Object object)
{
if (object instanceof FirstPageFragment && mFragmentAtPos0 instanceof NextFragment)
return POSITION_NONE;
return POSITION_UNCHANGED;
}
}
public interface FirstPageFragmentListener
{
void onSwitchToNextFragment();
}
Hope this helps anyone!
worked for me too:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parsed = null;
try {
parsed = sdf.parse("02/01/2014");
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Date data = new java.sql.Date(parsed.getTime());
contato.setDataNascimento( data);
// Contato DataNascimento era Calendar
//contato.setDataNascimento(Calendar.getInstance());
// grave nessa conexão!!!
ContatoDao dao = new ContatoDao("mysql");
// método elegante
dao.adiciona(contato);
System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());
I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:
#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;
If you can change the signature of your function to async Task
then you can use the code presented here
OK I am using the wrong syntax, I should be using
Allow from 127.0.0.1
Allow from ::1
...
The /240
error is due to illegal spaces before every code of line.
eg.
Do
printf("Anything");
instead of
printf("Anything");
This error is common when you copied and pasted the code in the IDE.
Step 1: add &html5=True
to your favorite youtube url
Step 2: Find <video/>
tag in source
Step 3: Add controls="controls"
to video tag: <video controls="controls"..../>
Example:
<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&itag=43&ipbits=0&signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&sver=3&ratebypass=yes&expire=1300417200&key=yt1&ip=0.0.0.0&id=37da319914f6616c"></video>
_x000D_
Note there seems to some expire
stuff. I don't know how long the src
string will work.
Still testing myself.
Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.
For Visual Studio Code:
launch.json
file"args": ["some argument", "another one"],
This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.
DispatchQueue.global(qos: .background).async {
// Background Thread
DispatchQueue.main.async {
// Run UI Updates
}
}
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
For anyone that is working with a directory style like this:
project
> src
> pkgA
> pkgB
...
> bin
> pkgA
> pkgB
...
The following worked very well for me. I made this myself, using the GNU make manual as my main reference; this, in particular, was extremely helpful for my last rule, which ended up being the most important one for me.
My Makefile:
PROG := sim
CC := g++
ODIR := bin
SDIR := src
MAIN_OBJ := main.o
MAIN := main.cpp
PKG_DIRS := $(shell ls $(SDIR))
CXXFLAGS = -std=c++11 -Wall $(addprefix -I$(SDIR)/,$(PKG_DIRS)) -I$(BOOST_ROOT)
FIND_SRC_FILES = $(wildcard $(SDIR)/$(pkg)/*.cpp)
SRC_FILES = $(foreach pkg,$(PKG_DIRS),$(FIND_SRC_FILES))
OBJ_FILES = $(patsubst $(SDIR)/%,$(ODIR)/%,\
$(patsubst %.cpp,%.o,$(filter-out $(SDIR)/main/$(MAIN),$(SRC_FILES))))
vpath %.h $(addprefix $(SDIR)/,$(PKG_DIRS))
vpath %.cpp $(addprefix $(SDIR)/,$(PKG_DIRS))
vpath $(MAIN) $(addprefix $(SDIR)/,main)
# main target
#$(PROG) : all
$(PROG) : $(MAIN) $(OBJ_FILES)
$(CC) $(CXXFLAGS) -o $(PROG) $(SDIR)/main/$(MAIN)
# debugging
all : ; $(info $$PKG_DIRS is [${PKG_DIRS}])@echo Hello world
%.o : %.cpp
$(CC) $(CXXFLAGS) -c $< -o $@
# This one right here, folks. This is the one.
$(OBJ_FILES) : $(ODIR)/%.o : $(SDIR)/%.h
$(CC) $(CXXFLAGS) -c $< -o $@
# for whatever reason, clean is not being called...
# any ideas why???
.PHONY: clean
clean :
@echo Build done! Cleaning object files...
@rm -r $(ODIR)/*/*.o
By using $(SDIR)/%.h
as a prerequisite for $(ODIR)/%.o
, this forced make to look in source-package directories for source code instead of looking in the same folder as the object file.
I hope this helps some people. Let me know if you see anything wrong with what I've provided.
BTW: As you may see from my last comment, clean is not being called and I am not sure why. Any ideas?
Just to add to yamen's answer, which is perfect for images but not so much for text.
If you are trying to use this to scale text, like say a Word document (which is in this case in bytes from Word Interop), you will need to make a few modifications or you will get giant bars on the side.
May not be perfect but works for me!
using (MemoryStream ms = new MemoryStream(wordBytes))
{
float width = 3840;
float height = 2160;
var brush = new SolidBrush(Color.White);
var rawImage = Image.FromStream(ms);
float scale = Math.Min(width / rawImage.Width, height / rawImage.Height);
var scaleWidth = (int)(rawImage.Width * scale);
var scaleHeight = (int)(rawImage.Height * scale);
var scaledBitmap = new Bitmap(scaleWidth, scaleHeight);
Graphics graph = Graphics.FromImage(scaledBitmap);
graph.InterpolationMode = InterpolationMode.High;
graph.CompositingQuality = CompositingQuality.HighQuality;
graph.SmoothingMode = SmoothingMode.AntiAlias;
graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(rawImage, new Rectangle(0, 0 , scaleWidth, scaleHeight));
scaledBitmap.Save(fileName, ImageFormat.Png);
return scaledBitmap;
}
As @jem suggested, it is possible to use jsoup.
With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.
import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);
It seems that in some previous release this method is not present.
Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify
table tr td:nth-child(2) {
text-align: right;
}
In cases with large tables this can save you a lot of extra markup!
here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/
you can use jQuery selectbox replacement. It's a jQuery plugin.
http://cssglobe.com/post/8802/custom-styling-of-the-select-elements
The Pure-css http://bavotasan.com/2011/style-select-box-using-only-css/
As I was annoyed by the first highly upvoted but wrong answer I found enough to write a reply there, and here the wrong answers are marked as such, here is my bit. I do not like proposed solutions as I can see no reason to make answer so complex.
I have a log where after $5 with an IP address can be more text or no text. I need everything from the IP address to the end of the line should there be anything after $5. In my case, this is actualy withn an awk program, not an awk oneliner so awk must solve the problem. When I try to remove the first 4 fields using the old nice looking and most upvoted but completely wrong answer:
echo " 7 27.10.16. Thu 11:57:18 37.244.182.218 one two three" | awk '{$1=$2=$3=$4=""; printf "[%s]\n", $0}'
it spits out wrong and useless response (I added [] to demonstrate):
[ 37.244.182.218 one two three]
Instead, if columns are fixed width until the cut point and awk is needed, the correct and quite simple answer is:
echo " 7 27.10.16. Thu 11:57:18 37.244.182.218 one two three" | awk '{printf "[%s]\n", substr($0,28)}'
which produces the desired output:
[37.244.182.218 one two three]
this does not directly answer your question (for which Naputipulu Jon and PriceHardman have fantastic replies)
However, for the purpose of a few classification tasks etc. you could use
pandas.get_dummies(input_df)
this can input dataframe with categorical data and return a dataframe with binary values. variable values are encoded into column names in the resulting dataframe. more
Bulk user creation with set_password
I you are creating several test users, bulk_create
is much faster, but we can't use create_user
with it.
set_password
is another way to generate the hashed passwords:
def users_iterator():
for i in range(nusers):
is_superuser = (i == 0)
user = User(
first_name='First' + str(i),
is_staff=is_superuser,
is_superuser=is_superuser,
last_name='Last' + str(i),
username='user' + str(i),
)
user.set_password('asdfqwer')
yield user
class Command(BaseCommand):
def handle(self, **options):
User.objects.bulk_create(iter(users_iterator()))
Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django
Tested in Django 1.9.
df['New_column_name'] = df['Column1'].map(str) + 'X' + df['Steps']
X= x is any delimiter (eg: space) by which you want to separate two merged column.
I got his error when i was trying to access UILabel
. I forgot to connect the UILabel
to IBOutlet
in Storyboard and that was causing the app to crash with this error!!
I think you should $_POST[][], i tried it and it work :)), tks
I had this same problem and I was able to solve it by implementing the IValidatableObject interface in my view model.
public class RegisterViewModel : IValidatableObject
{
/// <summary>
/// Error message for Minimum password
/// </summary>
public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";
/// <summary>
/// Minimum acceptable password length
/// </summary>
public const int PasswordMinimumLength = 8;
/// <summary>
/// Gets or sets the password provided by the user.
/// </summary>
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
/// <summary>
/// Only need to validate the minimum length
/// </summary>
/// <param name="validationContext">ValidationContext, ignored</param>
/// <returns>List of validation errors</returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errorList = new List<ValidationResult>();
if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
{
errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"}));
}
return errorList;
}
}
The markup in the Razor is then...
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
<div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case
</div>
@Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
</div>
This works really well. If I attempt to use [StringLength] instead then the rendered HTML is just not correct. The validation should render as:
<span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span>
With the StringLengthAttribute the rendered HTML shows as a ValidationSummary which is not correct. The funny thing is that when the validator fails the submit is still blocked!
create table xyz_new as select * from xyz where rownum = -1;
To avoid iterate again and again and insert nothing based on the condition where 1=2
Better to use:
DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key
From Go 1.10 there is a strings.Builder
type, please take a look at this answer for more detail.
The benchmark code of @cd1 and other answers are wrong. b.N
is not supposed to be set in benchmark function. It's set by the go test tool dynamically to determine if the execution time of the test is stable.
A benchmark function should run the same test b.N
times and the test inside the loop should be the same for each iteration. So I fix it by adding an inner loop. I also add benchmarks for some other solutions:
package main
import (
"bytes"
"strings"
"testing"
)
const (
sss = "xfoasneobfasieongasbg"
cnt = 10000
)
var (
bbb = []byte(sss)
expected = strings.Repeat(sss, cnt)
)
func BenchmarkCopyPreAllocate(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
bs := make([]byte, cnt*len(sss))
bl := 0
for i := 0; i < cnt; i++ {
bl += copy(bs[bl:], sss)
}
result = string(bs)
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkAppendPreAllocate(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
data := make([]byte, 0, cnt*len(sss))
for i := 0; i < cnt; i++ {
data = append(data, sss...)
}
result = string(data)
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkBufferPreAllocate(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
buf := bytes.NewBuffer(make([]byte, 0, cnt*len(sss)))
for i := 0; i < cnt; i++ {
buf.WriteString(sss)
}
result = buf.String()
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkCopy(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
data := make([]byte, 0, 64) // same size as bootstrap array of bytes.Buffer
for i := 0; i < cnt; i++ {
off := len(data)
if off+len(sss) > cap(data) {
temp := make([]byte, 2*cap(data)+len(sss))
copy(temp, data)
data = temp
}
data = data[0 : off+len(sss)]
copy(data[off:], sss)
}
result = string(data)
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkAppend(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
data := make([]byte, 0, 64)
for i := 0; i < cnt; i++ {
data = append(data, sss...)
}
result = string(data)
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkBufferWrite(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
var buf bytes.Buffer
for i := 0; i < cnt; i++ {
buf.Write(bbb)
}
result = buf.String()
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkBufferWriteString(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
var buf bytes.Buffer
for i := 0; i < cnt; i++ {
buf.WriteString(sss)
}
result = buf.String()
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
func BenchmarkConcat(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
var str string
for i := 0; i < cnt; i++ {
str += sss
}
result = str
}
b.StopTimer()
if result != expected {
b.Errorf("unexpected result; got=%s, want=%s", string(result), expected)
}
}
Environment is OS X 10.11.6, 2.2 GHz Intel Core i7
Test results:
BenchmarkCopyPreAllocate-8 20000 84208 ns/op 425984 B/op 2 allocs/op
BenchmarkAppendPreAllocate-8 10000 102859 ns/op 425984 B/op 2 allocs/op
BenchmarkBufferPreAllocate-8 10000 166407 ns/op 426096 B/op 3 allocs/op
BenchmarkCopy-8 10000 160923 ns/op 933152 B/op 13 allocs/op
BenchmarkAppend-8 10000 175508 ns/op 1332096 B/op 24 allocs/op
BenchmarkBufferWrite-8 10000 239886 ns/op 933266 B/op 14 allocs/op
BenchmarkBufferWriteString-8 10000 236432 ns/op 933266 B/op 14 allocs/op
BenchmarkConcat-8 10 105603419 ns/op 1086685168 B/op 10000 allocs/op
Conclusion:
CopyPreAllocate
is the fastest way; AppendPreAllocate
is pretty close to No.1, but it's easier to write the code.Concat
has really bad performance both for speed and memory usage. Don't use it.Buffer#Write
and Buffer#WriteString
are basically the same in speed, contrary to what @Dani-Br said in the comment. Considering string
is indeed []byte
in Go, it makes sense.Copy
with extra book keeping and other stuff.Copy
and Append
use a bootstrap size of 64, the same as bytes.BufferAppend
use more memory and allocs, I think it's related to the grow algorithm it use. It's not growing memory as fast as bytes.BufferSuggestion:
Append
or AppendPreAllocate
. It's fast enough and easy to use.bytes.Buffer
of course. That's what it's designed for.Since String.format
is only an extension function (see here) which internally calls java.lang.String.format
you could write your own extension function using Java's DecimalFormat if you need more flexibility:
fun Double.format(fracDigits: Int): String {
val df = DecimalFormat()
df.setMaximumFractionDigits(fracDigits)
return df.format(this)
}
println(3.14159.format(2)) // 3.14
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
According to this post this error message means:
Heap size is larger than your computer's physical memory.
Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.
Why not downsize other memory settings to free up space for the heap?
Bootstrap. Check out their awesome grid system here.
Using Bootstrap, you could make three columns like this:
<div class="container">
<div class="row">
<div class="col-md-4">.col-md-4</div>
<div class="col-md-4">.col-md-4</div>
<div class="col-md-4">.col-md-4</div>
</div>
</div>
With Package Control in Sublime Text 2, you really need to become cozy with a couple of different things to make it all work:
Prefs > Package Control
. Here you can install, remove or see a list of all installed packages.Prefs > Package Settings
. Here you'll find the settings that can be tinkered with as well as shortcut keys that are available. Make sure to make any changes in the User Settings, rather than the Default Settings. Otherwise, your settings will be overwritten when that package is updated.Try this formula:
=SUBSTITUTE(TEXT(A1/B1,"?/?"),"/",":")
Result:
A B C
33 11 3:1
25 5 5:1
6 4 3:2
Explanation:
This doesn't require any special toolkits or macros. The only downside might be that the result is considered text--not a number--so you can easily use it for further calculations.
Note: as @Robin Day suggested, increase the number of question marks (?) as desired to reduce rounding (thanks Robin!).
I am having the same problem, and I guess the way of doing this will be to remove the data-toggle attribute and have a custom handler for the links.
Something in the lines of:
$("a[data-target=#myModal]").click(function(ev) {
ev.preventDefault();
var target = $(this).attr("href");
// load the url and show modal on success
$("#myModal .modal-body").load(target, function() {
$("#myModal").modal("show");
});
});
Will try it later and post comments.
The first thing i noticed is that you have a semi colon just after your closing bracket for your if statement );
You should also try and clean up your if statement by declaring a variable for the answer separately.
function answers() {
var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;
if(answer == "To measure time"){
alert("Thats correct");
}
}
I tried fs-extra and copy-dir to copy-folder-recursively. but I want it to
So I wrote my own:
// Node.js module for Node.js 8.6+
var path = require("path");
var fs = require("fs");
function copyDirSync(src, dest, options) {
var srcPath = path.resolve(src);
var destPath = path.resolve(dest);
if(path.relative(srcPath, destPath).charAt(0) != ".")
throw new Error("dest path must be out of src path");
var settings = Object.assign(Object.create(copyDirSync.options), options);
copyDirSync0(srcPath, destPath, settings);
function copyDirSync0(srcPath, destPath, settings) {
var files = fs.readdirSync(srcPath);
if (!fs.existsSync(destPath)) {
fs.mkdirSync(destPath);
}else if(!fs.lstatSync(destPath).isDirectory()) {
if(settings.overwrite)
throw new Error(`Cannot overwrite non-directory '${destPath}' with directory '${srcPath}'.`);
return;
}
files.forEach(function(filename) {
var childSrcPath = path.join(srcPath, filename);
var childDestPath = path.join(destPath, filename);
var type = fs.lstatSync(childSrcPath).isDirectory() ? "directory" : "file";
if(!settings.filter(childSrcPath, type))
return;
if (type == "directory") {
copyDirSync0(childSrcPath, childDestPath, settings);
} else {
fs.copyFileSync(childSrcPath, childDestPath, settings.overwrite ? 0 : fs.constants.COPYFILE_EXCL);
if(!settings.preserveFileDate)
fs.futimesSync(childDestPath, Date.now(), Date.now());
}
});
}
}
copyDirSync.options = {
overwrite: true,
preserveFileDate: true,
filter: function(filepath, type) {
return true;
}
};
And a similar function, mkdirs, which is an alternative to mkdirp:
function mkdirsSync(dest) {
var destPath = path.resolve(dest);
mkdirsSync0(destPath);
function mkdirsSync0(destPath) {
var parentPath = path.dirname(destPath);
if(parentPath == destPath)
throw new Error(`cannot mkdir ${destPath}, invalid root`);
if (!fs.existsSync(destPath)) {
mkdirsSync0(parentPath);
fs.mkdirSync(destPath);
}else if(!fs.lstatSync(destPath).isDirectory()) {
throw new Error(`cannot mkdir ${destPath}, a file already exists there`);
}
}
}
Modulo arithmetic with negative operands is defined by the language designer, who might leave it to the language implementation, who might defer the definition to the CPU architecture.
I wasn't able to find a Java language definition.
Thanks Ishtar, Java Language Specification for the Remainder Operator % says that the sign of the result is the same as the sign of the numerator.
This is a mismatch between assemblies: a DLL referenced from an assembly doesn't have a method signature that's expected.
Clean the solution, rebuild everything, and try again.
Also, be careful if this is a reference to something that's in the GAC; it could be that something somewhere is pointing to an incorrect version. Make sure (through the Properties of each reference) that the correct version is chosen or that Specific Version is set false.
Using URL
:
url = new URL(window.location.href);
if (url.searchParams.get('test')) {
}
EDIT: if you're sad about compatibility, I'd highly suggest https://github.com/medialize/URI.js/.
INSERT
INTO first_table f
SELECT *
FROM second_table s
ON DUPLICATE KEY
UPDATE
s.column1 = DO_WHAT_EVER_MUST_BE_DONE_ON_KEY_CLASH(f.column1)
As of 1.9 there is no documented way to retrieve the events, other than to use the Migrate plugin to restore the old behavior. You could use the _.data() method as jps mentions, but that is an internal method. So just do the right thing and use the Migrate plugin if you need this functionality.
From the jQuery documentation on .data("events")
Prior to 1.9, .data("events") could be used to retrieve jQuery's undocumented internal event data structure for an element if no other code had defined a data element with the name "events". This special case has been removed in 1.9. There is no public interface to retrieve this internal data structure, and it remains undocumented. However, the jQuery Migrate plugin restores this behavior for code that depends upon it.
If you use the Date
property for DB Entities you will get exception:
"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."
You can use something like this:
DateTime date = DateTime.Now.Date;
var result = from client in context.clients
where client.BirthDate >= date
&& client.BirthDate < date.AddDays(1)
select client;
Moving the file to the main/resources directory worked.
Html.DisplayFor()
will render the DisplayTemplate that matches the property's type.
If it can't find any, I suppose it invokes .ToString()
.
If you don't know about display templates, they're partial views that can be put in a DisplayTemplates
folder inside the view folder associated to a controller.
Example:
If you create a view named String.cshtml
inside the DisplayTemplates
folder of your views folder (e.g Home
, or Shared
) with the following code:
@model string
@if (string.IsNullOrEmpty(Model)) {
<strong>Null string</strong>
}
else {
@Model
}
Then @Html.DisplayFor(model => model.Title)
(assuming that Title
is a string) will use the template and display <strong>Null string</strong>
if the string is null, or empty.
At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:
IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END
Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.
If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.
IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE clockDate = '08/10/2012' AND userName = 'test'
END
As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.
ffmpeg provides this functionality. All you need to do is run someting like
ffmpeg -i <inputfilename> -s 640x480 -b 512k -vcodec mpeg1video -acodec copy <outputfilename>
For newer versions of ffmpeg you need to change -b
to -b:v
:
ffmpeg -i <inputfilename> -s 640x480 -b:v 512k -vcodec mpeg1video -acodec copy <outputfilename>
to convert the input video file to a video with a size of 640 x 480 and a bitrate of 512 kilobits/sec using the MPEG 1 video codec and just copying the original audio stream. Of course, you can plug in any values you need and play around with the size and bitrate to achieve the quality/size tradeoff you are looking for. There are also a ton of other options described in the documentation
Run ffmpeg -formats
or ffmpeg -codecs
for a list of all of the available formats and codecs. If you don't have to target a specific codec for the final output, you can achieve better compression ratios with minimal quality loss using a state of the art codec like H.264.
It appears that in PHP you are obtaining the value of the submit button, not the select input. If you are using GET you will want to use $_GET['website_string']
or POST would be $_POST['website_string']
.
You will probably want the following HTML:
<select name="website_string">
<option value="" selected="selected"></option>
<option value="abc">ABC</option>
<option value="def">def</option>
<option value="hij">hij</option>
</select>
<input type="submit" />
With some PHP that looks like this:
<?php
$website_string = $_POST['website_string']; // or $_GET['website_string'];
?>
try out with this fastest JSON framework JSONKit. it's faster than normal JSON framework.
hello here is my structure for multi process
from multiprocessing import Process
import time
start = time.perf_counter()
def do_something(time_for_sleep):
print(f'Sleeping {time_for_sleep} second...')
time.sleep(time_for_sleep)
print('Done Sleeping...')
p1 = Process(target=do_something, args=[1])
p2 = Process(target=do_something, args=[2])
if
__name__ == '__main__':
p1.start()
p2.start()
p1.join()
p2.join()
finish = time.perf_counter()
print(f'Finished in {round(finish-start,2 )} second(s)')
you don't have to put imports in the name == 'main', just running the program you wish to running inside
Here is my solution:
public static boolean isPIDInUse(int pid) {
try {
String s = null;
int java_pid;
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("@")));
if (java_pid == pid) {
System.out.println("In Use\n");
return true;
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return false;
}
To follow @modocache's recommendation to avoid calling view.endEditing()
, you could keep track of the text field that became first responder, but that is messy and error-prone.
An alternative is to call resignFirstResponder()
on all text fields in the viewcontroller. Here's an example of creating a collection of all text fields (which in my case was needed for validation code anyway):
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var email: UITextField!
var allTextFields: Array<UITextField>! // Forced unwrapping so it must be initialized in viewDidLoad
override func viewDidLoad()
{
super.viewDidLoad()
self.allTextFields = [self.firstName, self.lastName, self.email]
}
With the collection available, it's a simple matter to iterate through all of them:
private func dismissKeyboard()
{
for textField in allTextFields
{
textField.resignFirstResponder()
}
}
So now you can call dismissKeyboard()
in your gesture recognizer (or wherever is appropriate for you). Drawback is that you must maintain the list of UITextField
s when you add or remove fields.
Comments welcome. If there is a problem with calling resignFirstResponder()
on controls that aren't first responder, or if there's an easy and guaranteed non-buggy way to track the current first responder, I'd love to hear about it!
Another thing not mentioned is that it depends on what OS you are using where speed is concerned. In Windows processes are costly so threads would be better in windows but in unix processes are faster than their windows variants so using processes in unix is much safer plus quick to spawn.
Java 8 way to do this:
List<Integer> list = Arrays.asList(1,2,3,4);
Comparator<Integer> comparator = Integer::compare;
list.stream().sorted(comparator.reversed()).forEach(System.out::println);
Wouldn't you just change:
numero = stmt.executeUpdate(query);
to:
numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Take a look at the documentation for the JDBC Statement
interface.
Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero
variable is completely irrelevant and its value is never read after it is set.
The easiest solution is to use margin. This will also be responsive!
<div style="margin-right: auto">left</div>
<div style="margin-left: auto; margin-right:auto">center</div>
<div style="margin-left: auto">right</div>
Try it like this:
for i in some_list:
#do a bunch of stuff.
print i/len(some_list)*100," percent complete",
(With a comma at the end.)
Update your remote if you still haven't done so:
$ git remote update
$ git branch -r
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
The user-agent
should be specified as a field in the header.
Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent
.
The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:
import requests
url = 'SOME URL'
headers = {
'User-Agent': 'My User Agent 1.0',
'From': '[email protected]' # This is another valid field
}
response = requests.get(url, headers=headers)
Older versions of requests
clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.
import requests
url = 'SOME URL'
# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()
# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
{
'User-Agent': 'My User Agent 1.0',
}
)
response = requests.get(url, headers=headers)
Based on what I see here, you have used lowercase fieldnames in your $data
array, and uppercase fieldnames in your database table.
The answer is System.exit(), but not a good thing to do as this aborts the program. Any cleaning up, destroy that you intend to do will not happen.
Conclusion,
to_char
works in its own way
So,
Always use this format YYYY-MM-DD for comparison instead of MM-DD-YY or DD-MM-YYYY or any other format
I would recommend you to use worksheet's index instead of using worksheet's name, in this way you can also loop through sheets "dynamically"
for i=1 to thisworkbook.sheets.count
sheets(i).activate
'You can add more code
with activesheet
'Code...
end with
next i
It will also, improve performance.
Actually Im agree with MikeW (+1) it's better to use profiler for this case.
Anyway, if you really need to grab all (n)varchar columns in db and make a search. See below. I suppose to use INFORMATION_SCHEMA.Tables + dynamic SQL. The plain search:
DECLARE @SearchText VARCHAR(100)
SET @SearchText = '12'
DECLARE @Tables TABLE(N INT, TableName VARCHAR(100), ColumnNamesCSV VARCHAR(2000), SQL VARCHAR(4000))
INSERT INTO @Tables (TableName, ColumnNamesCSV)
SELECT T.TABLE_NAME AS TableName,
( SELECT C.Column_Name + ','
FROM INFORMATION_SCHEMA.Columns C
WHERE T.TABLE_NAME = C.TABLE_NAME
AND C.DATA_TYPE IN ('nvarchar','varchar')
FOR XML PATH('')
)
FROM INFORMATION_SCHEMA.Tables T
DELETE FROM @Tables WHERE ColumnNamesCSV IS NULL
INSERT INTO @Tables (N, TableName, ColumnNamesCSV)
SELECT ROW_NUMBER() OVER(ORDER BY TableName), TableName, ColumnNamesCSV
FROM @Tables
DELETE FROM @Tables WHERE N IS NULL
UPDATE @Tables
SET ColumnNamesCSV = SUBSTRING(ColumnNamesCSV, 0, LEN(ColumnNamesCSV))
UPDATE @Tables
SET SQL = 'SELECT * FROM ['+TableName+'] WHERE '''+@SearchText+''' IN ('+ColumnNamesCSV+')'
DECLARE @C INT,
@I INT,
@SQL VARCHAR(4000)
SELECT @I = 1,
@C = COUNT(1)
FROM @Tables
WHILE @I <= @C BEGIN
SELECT @SQL = SQL FROM @Tables WHERE N = @I
SET @I = @I+1
EXEC(@SQL)
END
and one with LIKE clause:
DECLARE @SearchText VARCHAR(100)
SET @SearchText = '12'
DECLARE @Tables TABLE(N INT, TableName VARCHAR(100), ColumnNamesCSVLike VARCHAR(2000), LIKESQL VARCHAR(4000))
INSERT INTO @Tables (TableName, ColumnNamesCSVLike)
SELECT T.TABLE_NAME AS TableName,
( SELECT C.Column_Name + ' LIKE ''%'+@SearchText+'%'' OR '
FROM INFORMATION_SCHEMA.Columns C
WHERE T.TABLE_NAME = C.TABLE_NAME
AND C.DATA_TYPE IN ('nvarchar','varchar')
FOR XML PATH(''))
FROM INFORMATION_SCHEMA.Tables T
DELETE FROM @Tables WHERE ColumnNamesCSVLike IS NULL
INSERT INTO @Tables (N, TableName, ColumnNamesCSVLike)
SELECT ROW_NUMBER() OVER(ORDER BY TableName), TableName, ColumnNamesCSVLike
FROM @Tables
DELETE FROM @Tables WHERE N IS NULL
UPDATE @Tables
SET ColumnNamesCSVLike = SUBSTRING(ColumnNamesCSVLike, 0, LEN(ColumnNamesCSVLike)-2)
UPDATE @Tables SET LIKESQL = 'SELECT * FROM ['+TableName+'] WHERE '+ColumnNamesCSVLike
DECLARE @C INT,
@I INT,
@LIKESQL VARCHAR(4000)
SELECT @I = 1,
@C = COUNT(1)
FROM @Tables
WHILE @I <= @C BEGIN
SELECT @LIKESQL = LIKESQL FROM @Tables WHERE N = @I
SET @I = @I +1
EXEC(@LIKESQL)
END
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
The getElementsByClassName
method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName) { // use native implementation if available
return node.getElementsByClassName(classname);
} else {
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}
Usage:
function toggle_visibility(className) {
var elements = getElementsByClassName(document, className),
n = elements.length;
for (var i = 0; i < n; i++) {
var e = elements[i];
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
}
This is exactly what you need. See it in action here 8FydL/445
Example's Code below:
$(".dropdown img.flag").addClass("flagvisibility");_x000D_
$(".dropdown dt a").click(function() {_x000D_
$(".dropdown dd ul").toggle();_x000D_
});_x000D_
_x000D_
$(".dropdown dd ul li a").click(function() {_x000D_
var text = $(this).html();_x000D_
$(".dropdown dt a span").html(text);_x000D_
$(".dropdown dd ul").hide();_x000D_
$("#result").html("Selected value is: " + getSelectedValue("sample"));_x000D_
});_x000D_
_x000D_
function getSelectedValue(id) {_x000D_
return $("#" + id).find("dt a span.value").html();_x000D_
}_x000D_
_x000D_
$(document).bind('click', function(e) {_x000D_
var $clicked = $(e.target);_x000D_
if (! $clicked.parents().hasClass("dropdown"))_x000D_
$(".dropdown dd ul").hide();_x000D_
});_x000D_
_x000D_
$(".dropdown img.flag").toggleClass("flagvisibility");
_x000D_
.desc { color:#6b6b6b;}_x000D_
.desc a {color:#0092dd;}_x000D_
_x000D_
.dropdown dd, .dropdown dt, .dropdown ul { margin:0px; padding:0px; }_x000D_
.dropdown dd { position:relative; }_x000D_
.dropdown a, .dropdown a:visited { color:#816c5b; text-decoration:none; outline:none;}_x000D_
.dropdown a:hover { color:#5d4617;}_x000D_
.dropdown dt a:hover { color:#5d4617; border: 1px solid #d0c9af;}_x000D_
.dropdown dt a {background:#e4dfcb url('http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/arrow.png') no-repeat scroll right center; display:block; padding-right:20px;_x000D_
border:1px solid #d4ca9a; width:150px;}_x000D_
.dropdown dt a span {cursor:pointer; display:block; padding:5px;}_x000D_
.dropdown dd ul { background:#e4dfcb none repeat scroll 0 0; border:1px solid #d4ca9a; color:#C5C0B0; display:none;_x000D_
left:0px; padding:5px 0px; position:absolute; top:2px; width:auto; min-width:170px; list-style:none;}_x000D_
.dropdown span.value { display:none;}_x000D_
.dropdown dd ul li a { padding:5px; display:block;}_x000D_
.dropdown dd ul li a:hover { background-color:#d0c9af;}_x000D_
_x000D_
.dropdown img.flag { border:none; vertical-align:middle; margin-left:10px; }_x000D_
.flagvisibility { display:none;}
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>_x000D_
<dl id="sample" class="dropdown">_x000D_
<dt><a href="#"><span>Please select the country</span></a></dt>_x000D_
<dd>_x000D_
<ul>_x000D_
<li><a href="#">Brazil<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/br.png" alt="" /><span class="value">BR</span></a></li>_x000D_
<li><a href="#">France<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/fr.png" alt="" /><span class="value">FR</span></a></li>_x000D_
_x000D_
</ul>_x000D_
</dd>_x000D_
</dl>_x000D_
<span id="result"></span>
_x000D_
procedure SetSleep(aEnable:Boolean);
var
vFlags: integer;
begin
vFlags := TJWindowManager_LayoutParams.JavaClass.FLAG_TURN_SCREEN_ON or
TJWindowManager_LayoutParams.JavaClass.FLAG_DISMISS_KEYGUARD or
TJWindowManager_LayoutParams.JavaClass.FLAG_SHOW_WHEN_LOCKED or
TJWindowManager_LayoutParams.JavaClass.FLAG_KEEP_SCREEN_ON;
if aEnable then
begin
CallInUIThread ( // uses FMX.Helpers.Android
procedure
begin
TAndroidHelper.Activity.getWindow.setFlags (vFlags, vFlags);
end );
end
else
CallInUIThread (
procedure
begin
TAndroidHelper.Activity.getWindow.clearFlags (vFlags);
end );
end;
This may be an old/closed thread but I've search everywhere didnt find something useful, until I decided to create my own solution. If theres anyone here trying to look for answer try this one, might save you a minute of thinking
<LinearLayout
android:id="@+id/llContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/selector"
android:clickable="true"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:textStyle="bold">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="This is a text" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_image />
</LinearLayout>
Because Linear layout act as the container and the one who has the selector, when you click the entire linear layout it would look just how it should it be. if you want it to be both centered, use relative insteaf. If you want it centered horizontally change the orientation to horizontal.
Take note DO NOT forget to add android:clickable="true" to your main container (relative or linear) for the action to take place.
Again this may be old thread but may still help someone there.
-cheers hope it helps- happycodings.
For disable trigger
ALTER TABLE table_name DISABLE TRIGGER trigger_name
For enable trigger
ALTER TABLE table_name ENABLE TRIGGER trigger_name
To extend the answer above and if the case is you are using XAMPP. In the current version of the xampp you cannot locate the curl_exec in the php.ini, just try using
<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>
and save to your htdocs. Next go to your browser and paste
http://localhost/[your_filename].php
if the result looks like this
array(9) {
["version_number"]=>
int(469760)
["age"]=>
int(3)
["features"]=>
int(266141)
["ssl_version_number"]=>
int(0)
["version"]=>
string(6) "7.43.0"
["host"]=>
string(13) "i386-pc-win32"
["ssl_version"]=>
string(14) "OpenSSL/1.0.2e"
["libz_version"]=>
string(5) "1.2.8"
["protocols"]=>
array(19) {
[0]=>
string(4) "dict"
[1]=>
string(4) "file"
[2]=>
string(3) "ftp"
[3]=>
string(4) "ftps"
[4]=>
string(6) "gopher"
[5]=>
string(4) "http"
[6]=>
string(5) "https"
[7]=>
string(4) "imap"
[8]=>
string(5) "imaps"
[9]=>
string(4) "ldap"
[10]=>
string(4) "pop3"
[11]=>
string(5) "pop3s"
[12]=>
string(4) "rtsp"
[13]=>
string(3) "scp"
[14]=>
string(4) "sftp"
[15]=>
string(4) "smtp"
[16]=>
string(5) "smtps"
[17]=>
string(6) "telnet"
[18]=>
string(4) "tftp"
}
}
curl is enable
"files" in *nix type systems are very much an abstract concept.
They can be areas on disk organized by a file system, but they could equally well be a network connection, a bit of shared memory, the buffer output from another process, a screen or a keyboard.
In order for perl to be really useful it mirrors this model very closely, and does not treat files by emulating a magnetic tape as many 4gls do.
So it tried an "IOCTL" operation 'open for write' on a file handle which does not allow write operations which is an inappropriate IOCTL operation for that device/file.
The easiest thing to do is stick an " or die 'Cannot open $myfile'
statement at the end of you open and you can choose your own meaningful message.
Use strstr(const char *s , const char *t)
and include<string.h>
You can write your own function which behaves same as strstr
and you can modify according to your requirement also
char * str_str(const char *s, const char *t)
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++)
{
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return (&s[i]);
}
return NULL;
}
Fact, that ng-if
directive, unlike ng-show
, creates its own scope, leads to interesting practical difference:
angular.module('app', []).controller('ctrl', function($scope){_x000D_
$scope.delete = function(array, item){_x000D_
array.splice(array.indexOf(item), 1);_x000D_
}_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app='app' ng-controller='ctrl'>_x000D_
<h4>ng-if:</h4>_x000D_
<ul ng-init='arr1 = [1,2,3]'>_x000D_
<li ng-repeat='x in arr1'>_x000D_
{{show}}_x000D_
<button ng-if='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
<button ng-if='show' ng-click='delete(arr1, x)'>Yes {{show}}</button>_x000D_
<button ng-if='show' ng-click='show=!show'>No</button>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<h4>ng-show:</h4>_x000D_
<ul ng-init='arr2 = [1,2,3]'>_x000D_
<li ng-repeat='x in arr2'>_x000D_
{{show}}_x000D_
<button ng-show='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
<button ng-show='show' ng-click='delete(arr2, x)'>Yes {{show}}</button>_x000D_
<button ng-show='show' ng-click='show=!show'>No</button>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<h4>ng-if with $parent:</h4>_x000D_
<ul ng-init='arr3 = [1,2,3]'>_x000D_
<li ng-repeat='item in arr3'>_x000D_
{{show}}_x000D_
<button ng-if='!show' ng-click='$parent.show=!$parent.show'>Delete {{$parent.show}}</button>_x000D_
<button ng-if='show' ng-click='delete(arr3, x)'>Yes {{$parent.show}}</button>_x000D_
<button ng-if='show' ng-click='$parent.show=!$parent.show'>No</button>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
At first list, on-click
event, show
variable, from innner/own scope, is changed, but ng-if
is watching on another variable from outer scope with same name, so solution not works. At case of ng-show
we have the only one show
variable, that is why it works. To fix first attempt, we should reference to show
from parent/outer scope via $parent.show
.
The commands for what specific codes to run are listed inside your package.json file under scripts. Here is an example of mine:
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
If you are looking to run your site locally, you can test it with
npm serve
If you are looking to prep your site for production, you would use
npm build
This command will generate a dist folder that has a compressed version of your site.
DECLARE @str varchar(150)
SET @str='Hello My name is Jiyaul mustafa'
Select REPLACE(REPLACE(REPLACE(@str,' ','{}'),'}{',''),'{}',' ')
As @linusg said, one option is just import crossvalidation as follows:
from sklearn import cross_validation
X_train,X_test,y_train,y_test = cross_validation.train_test_split(X,y,test_size=0.3)
There is another way also. Try below code
$(document).ready(function(){
$("input[name='gender']").on("click", function() {
alert($(this).val());
});
});
I'm having the same problem but the Lambda function that I implement will insert an entry in DynamoDB, so my solution uses DynamoDB Triggers.
I make the DB invoke a Lambda function for every insert/update in the table, so this separates the implementation of two Lambda functions.
Documentation is here: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.html
Here is a guided walkthrough: https://aws.amazon.com/blogs/aws/dynamodb-update-triggers-streams-lambda-cross-region-replication-app/
In MS Windows the temporary directory is set by the environment variable TEMP
. In XP, the temporary directory was set per-user as Local Settings\Temp.
If you change your TEMP environment variable to C:\temp
, then you get the same when you run :
System.out.println(System.getProperty("java.io.tmpdir"));
Hi This one worked me
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /folder/index.php?/$1 [L]
as well as this
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /folder/index.php?/$1 [L]
where the folder is the name of the subfolder if this codeigniter application is hosted as a subdomain e.g domainname/folder/index.php.
Hope that works for you. Thanks.
Disclaimer :- Only for ios 9 and above (Stack View).
If you are deploying your app on ios 9 devices use a stack view. Here are the steps :-
You should sort the list:
mylist.sort()
After this, iterate through it like this:
doubles = []
for i, elem in enumerate(mylist):
if i != 0:
if elem == old:
doubles.append(elem)
old = None
continue
old = elem
You can work around this by setting the X-UA-Compatible
meta header for the specific version of IE you are debugging with. This will change the Browser Mode to the version you specify in the header.
For example:
<meta http-equiv="X-UA-Compatible" content="IE=9" />
In order for the Browser Mode to update on the Developer Tools, you must close [the Developer Tools] and reopen again. This will switch to that specific version.
Switching from a minor version to a greater version will work just fine by refreshing, but if you want to switch back from a greater version to a minor version, such as from 9 to 7, you would need to open a new tab and load the page again.
Here's a screenshot:
I assume we are talking about doing this in Bash?
I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...
DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY
you also may want to read up on the date command in linux. It can be very useful: http://unixhelp.ed.ac.uk/CGI/man-cgi?date
Hope that helps... :)
-Ryan
Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):
When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.
Note: the answer was edited on Jan 2016 to reflect most recent changes
From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:
net start > c:\netstart.txt
You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\
drive.
In Xcode 8,
An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
And in "myFile.php" :
<?
echo 'My id is : ' . $id . '!';
?>
This will output :
My id is 12345 !
Because it doesn't seem to have been mentioned, here's my preferred method, sans side effects or external dependencies:
const obj = {_x000D_
a: 1,_x000D_
b: undefined_x000D_
}_x000D_
_x000D_
const newObject = Object.keys(obj).reduce((acc, key) => {_x000D_
const _acc = acc;_x000D_
if (obj[key] !== undefined) _acc[key] = obj[key];_x000D_
return _acc;_x000D_
}, {})_x000D_
_x000D_
console.log(newObject)_x000D_
// Object {a: 1}
_x000D_
Here's a solution that uses a jQuery selector so you can easily target tags of any class, ID, type etc.
jQuery('div').on('click', function(){
var node = jQuery(this).get(0);
var range = document.createRange();
range.selectNodeContents( node );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
});
I used the following code to send HTTP POST from my android client app to C# desktop app on my server:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I worked on reading the request from a C# app on my server (something like a web server little application). I managed to read request posted data using the following code:
server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();
HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;
StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();
USE This Assembly Referance in your Project
Add a reference to System.Net.Http.Formatting.dll
Simplified example of Nicolai Ehmann's comment and wildloop's answer (works with Spring 4.3.3+), basically you can use required = false
now:
@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
if (type != null) {
// ...
}
return new TestBean();
}
1) Don't use gets
! You're introducing a buffer-overflow vulnerability. Use fgets(..., stdin)
instead.
2) In strToLower
you're returning a char
instead of a char
-array. Either return char*
as Autopulated suggested, or just return void
since you're modifying the input anyway. As a result, just write
strToLower(cString1);
strToLower(cString2);
strcasecmp
(Linux & Mac) or stricmp
(Windows).If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:
public class ThreadProvider implements CustomInterface{
...
}
Then in your controller try this:
@Controller
public class ChiusuraController {
@Autowired
private CustomInterface chiusuraProvider;
}
The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider
extend ThreadProvider
Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).
When you DID extend from ThreadProvider
assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider
type.
If you absolutely need to use ChisuraProvider
you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb
just to add another solution, particularly useful if you are using the new pandas assessors, other solutions will replace the original pandas and lose the assessors
df.drop(df.loc[df['line_race']==0].index, inplace=True)
This is a function that outputs one line per item, with indentation according to depth level. It is probably much more readable.
function GetDirs($path = $pwd, [Byte]$ToDepth = 255, [Byte]$CurrentDepth = 0)
{
$CurrentDepth++
If ($CurrentDepth -le $ToDepth) {
foreach ($item in Get-ChildItem $path)
{
if (Test-Path $item.FullName -PathType Container)
{
"." * $CurrentDepth + $item.FullName
GetDirs $item.FullName -ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
}
}
}
It is based on a blog post, Practical PowerShell: Pruning File Trees and Extending Cmdlets.
Yes, with -Xmx
you can configure more memory for your JVM.
To be sure that you don't leak or waste memory. Take a heap dump and use the Eclipse Memory Analyzer to analyze your memory consumption.
I would recommend running ThreadPool.GetMaxThreads method in debug
ThreadPool.GetMaxThreads(out int workerThreadsCount, out int ioThreadsCount);
Docs and examples: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool.getmaxthreads?view=netframework-4.8
Mozilla 'announces' object extending from ECMAScript 6.0:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends
NOTE: This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.
class Square extends Polygon {
constructor(length) {
// Here, it calls the parent class' constructor with lengths
// provided for the Polygon's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value; }
}
This technology is available in Gecko (Google Chrome / Firefox) - 03/2015 nightly builds.
This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.
Depending on what problem you're trying to solve, there might be a faster algorithm.
Consider C#'s out keyword. The compiler requires the caller of a method to apply the out keyword to any out args, even though it knows already if they are. This is intended to enhance readability. Although with modern IDEs I'm inclined to think that this is a job for syntax (or semantic) highlighting.
You might have output (maybe error/debug output) that precedes your call to
header("Content-type: text/xml");
Therefore, the content being delivered to the browser is not "xml"... that's what the error message is trying to tell you (at least that was the case for me and I had the same error message as you've described).
It because every time
void pthread_exit(void *ret);
will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().
Now at
int pthread_join(pthread_t tid, void **ret);
will be always called from where thread is created so here to accept that returned pointer you need double pointer ..
i think this code will help you to understand this
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
void* thread_function(void *ignoredInThisExample)
{
char *a = malloc(10);
strcpy(a,"hello world");
pthread_exit((void*)a);
}
int main()
{
pthread_t thread_id;
char *b;
pthread_create (&thread_id, NULL,&thread_function, NULL);
pthread_join(thread_id,(void**)&b); //here we are reciving one pointer
value so to use that we need double pointer
printf("b is %s\n",b);
free(b); // lets free the memory
}
Well it has a simple and easy solution. You can make your video easily to fit for any device and screen size. Here is the HTML and CSS code:
.yt-container {_x000D_
position:relative;_x000D_
padding-bottom:56.25%;_x000D_
padding-top:30px;_x000D_
height:0;_x000D_
overflow:hidden;_x000D_
}_x000D_
_x000D_
.yt-container iframe, .yt-container object, .yt-container embed {_x000D_
position:absolute;_x000D_
top:0;_x000D_
left:0;_x000D_
width:100%;_x000D_
height:100%;_x000D_
}
_x000D_
<div class="yt-container">_x000D_
<iframe src="https://www.youtube.com/embed/hfQdkBOxXTc" frameborder="0" allowfullscreen></iframe>_x000D_
</div>
_x000D_
Source: https://www.codespeedy.com/make-youtube-embed-video-responsive-using-css/
Given a version number MAJOR.MINOR.PATCH, increment the:
As you may know, on android you have to define two version fields for an app: the version code (android:versionCode) and the version name (android:versionName). The version code is an incremental integer value that represents the version of the application code. The version name is a string value that represents the “friendly” version name displayed to the users.
A binary search tree is a special kind of binary tree which exhibits the following property: for any node n, every descendant node's value in the left subtree of n is less than the value of n, and every descendant node's value in the right subtree is greater than the value of n.
If you like long cuts, here is another way tuple(tuple(a_m.tolist()) for a_m in a )
from numpy import array
a = array([[1, 2],
[3, 4]])
tuple(tuple(a_m.tolist()) for a_m in a )
The output is ((1, 2), (3, 4))
Note just (tuple(a_m.tolist()) for a_m in a ) will give a generator expresssion. Sort of inspired by @norok2's comment to Greg von Winckel's answer
Nested classes are cool for hiding implementation details.
List:
class List
{
public:
List(): head(nullptr), tail(nullptr) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.
Look at std::list
or std::map
they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list
.
One approach could be using find:
find /desired_location -type d -print0 | xargs -0 chmod 0755
find /desired_location -type f -print0 | xargs -0 chmod 0644
To insert a sleep command you can use Thread.sleep(2000). So the code would be:
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = someList.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.println(coord);
Thread.Sleep(2000);
}
This would output: 10 20 30 40 50
If you want the numbers after each other you could use: System.out.print(coord +" " ); and if you want to repeat the section you can put it in another while loop.
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
Iterator<Integer> myListIterator = someList.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.print(coord + " ");
Thread.Sleep(2000);
}
}
This would output: 10 20 30 40 50 10 20 30 40 50 ... and never stop until you kill the program.
Edit: You do have to put the sleep command in a try catch block
Just pass var2 as an extra argument to one of the apply functions.
mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
var1*var2
}
var2 <- 2
sapply(mylist,myfxn,var2=var2)
This passes the same var2
to every call of myfxn
. If instead you want each call of myfxn
to get the 1st/2nd/3rd/etc. element of both mylist
and var2
, then you're in mapply
's domain.
I had a similar problem, you may find that going to the top right corner of your page in Eclipse and click "Java EE" instead of "Java" will solve your problem. I had EE installed correctly like you, and this solved the issue for me. Hope I helped :)
Using jQuery jsonp request:
<script type="text/javascript">
$.ajax({
type:'GET',
url: 'http://vimeo.com/api/v2/video/' + video_id + '.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function(data){
var thumbnail_src = data[0].thumbnail_large;
$('#thumb_wrapper').append('<img src="' + thumbnail_src + '"/>');
}
});
</script>
<div id="thumb_wrapper"></div>
I had same problem and despite having jstl
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
I had to add 'standard' as well:
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
Also, as mentioned in previous post:
You can use WebClient.
Or (if you need more fine-grained control over the request) HttpWebRequest
Or, HttpClient in System.Net.Http.dll.
Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):
HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
http.Referer = referrer;
HttpWebResponse response = (HttpWebResponse )http.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string responseJson = sr.ReadToEnd();
// more stuff
}
That way you haven't installed pip, you installed just the easy_install
i.e. setuptools
.
First you should remove all the packages you installed with easy_install
using (see uninstall):
easy_install -m PackageName
This includes pip
if you installed it using easy_install pip
.
After this you remove the setuptools
following the instructions from here:
If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:
setuptools-*.egg
If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:
pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/
Here's a trick I used once: create a "dummy" directive to hold the parent scope and place it somewhere outside the desired directive. Something like:
module.directive('myDirectiveContainer', function () {
return {
controller: function ($scope) {
this.scope = $scope;
}
};
});
module.directive('myDirective', function () {
return {
require: '^myDirectiveContainer',
link: function (scope, element, attrs, containerController) {
// use containerController.scope here...
}
};
});
and then
<div my-directive-container="">
<div my-directive="">
</div>
</div>
Maybe not the most graceful solution, but it got the job done.
A modern and fast solution, for Python 3.7. May also work in some interpreters of Python 3.6.
TLDR
To sort a dictionary by keys use:
sorted_dict = {k: disordered[k] for k in sorted(disordered)}
Almost three times faster than the accepted answer; probably more when you include imports.
Comment on the accepted answer
The example in the accepted answer instead of iterating over the keys only - with key
parameter of sorted()
or the default behaviour of dict iteration - iterates over tuples (key, value)
, which suprisingly turns out to be much slower than comparing the keys only and accessing dictionary elements in a list comprehension.
How to sort by key in Python 3.7
The big change in Python 3.7 is that the dictionaries are now ordered by default.
OrderedDict
might still be preferable for the compatibility sake.sorted(d.items())
without key
.See:
disordered = {10: 'b', 3: 'a', 5: 'c'}
# sort keys, then get values from original - fast
sorted_dict = {k: disordered[k] for k in sorted(disordered)}
# key = itemgetter - slower
from operator import itemgetter
key = itemgetter(0)
sorted_dict = {k: v for k, v in sorted(disordered.items(), key=key)}
# key = lambda - the slowest
key = lambda item: item[0]
sorted_dict = {k: v for k in sorted(disordered.items(), key=key)}
Timing results:
Best for {k: d[k] for k in sorted(d)}: 7.507327548999456
Best for {k: v for k, v in sorted(d.items(), key=key_getter)}: 12.031082626002899
Best for {k: v for k, v in sorted(d.items(), key=key_lambda)}: 14.22885995300021
Best for dict(sorted(d.items(), key=key_getter)): 11.209122000000207
Best for dict(sorted(d.items(), key=key_lambda)): 13.289728325995384
Best for dict(sorted(d.items())): 14.231471302999125
Best for OrderedDict(sorted(d.items(), key=key_getter)): 16.609151654003654
Best for OrderedDict(sorted(d.items(), key=key_lambda)): 18.52622927199991
Best for OrderedDict(sorted(d.items())): 19.436101284998585
Testing code:
from timeit import repeat
setup_code = """
from operator import itemgetter
from collections import OrderedDict
import random
random.seed(0)
d = {i: chr(i) for i in [random.randint(0, 120) for repeat in range(120)]}
key_getter = itemgetter(0)
key_lambda = lambda item: item[0]
"""
cases = [
# fast
'{k: d[k] for k in sorted(d)}',
'{k: v for k, v in sorted(d.items(), key=key_getter)}',
'{k: v for k, v in sorted(d.items(), key=key_lambda)}',
# slower
'dict(sorted(d.items(), key=key_getter))',
'dict(sorted(d.items(), key=key_lambda))',
'dict(sorted(d.items()))',
# the slowest
'OrderedDict(sorted(d.items(), key=key_getter))',
'OrderedDict(sorted(d.items(), key=key_lambda))',
'OrderedDict(sorted(d.items()))',
]
for code in cases:
times = repeat(code, setup=setup_code, repeat=3)
print(f"Best for {code}: {min(times)}")
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
pip install django-truncate
settings.py
file:INSTALLED_APPS = [
...
'django_truncate',
]
python manage.py truncate --apps app_name --models table_name
In your string file use this
<string name="redeem_point"> You currently have %s points(%s points = 1 %s)</string>
And in your code use as accordingly
coinsTextTV.setText(String.format(getContext().getString(R.string.redeem_point), rewardPoints.getReward_points()
, rewardPoints.getConversion_rate(), getString(R.string.rs)));
This problem will occurred due to some unnecessary changes made in my.cnf file.
Try to diff /etc/mysql/my.cnf
with one of working mysql servers my.cnf file.
I just replaced /etc/mysql/my.cnf
file with new my.cnf file and this works for me.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
There are multiple meanings of "lock" in SVN and some of these answers that talk about "break lock" or a teammate holding a lock are not using the relevant meaning for the original question. This question is dealing with "working copy locks" (i.e. they are entirely local to the working copy on your computer and have nothing to do with you or teammates holding a lock/check-out on a file). The accepted answer by MicroEyes is referring to the correct usage and is your best option when this happens.
If a cleanup doesn't work you may need to check out a fresh working copy of the project. If you have any modified, un-commited files you will need to copy them over to the fresh working copy so you don't lose your changes.
See this page in the Tortoise SVN docs for a description of the three usages of "lock": http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-dug-locking.html
Excerpt (emphasis added):
The Three Meanings of “Lock”
In this section, and almost everywhere in this book, the words “lock” and “locking” describe a mechanism for mutual exclusion between users to avoid clashing commits. Unfortunately, there are two other sorts of “lock” with which Subversion, and therefore this book, sometimes needs to be concerned.
The second is working copy locks, used internally by Subversion to prevent clashes between multiple Subversion clients operating on the same working copy. Usually you get these locks whenever a command like update/commit/... is interrupted due to an error. These locks can be removed by running the cleanup command on the working copy, as described in the section called “Cleanup”.
...
int(limit)
returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).
Do this instead:
limit = int(limit)
Or when definiting limit
:
if 'limit' in user_data :
limit = int(user_data['limit'])
getDay()
gets the day of the week. 3
is Wednesday. You want getDate()
, that will return 18
.
Also getMonth()
starts at 0
, you need to add 1
to get 4
(April).
If the data is in an UTF-8 compatible format, you can convert the bytes to a string.
>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2
Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.
from binascii import hexlify
from codecs import encode # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337
According to this blog post you can load controller within another controller in codeigniter.
http://www.techsirius.com/2013/01/load-controller-within-another.html
First of all you need to extend CI_Loader
<?php
class MY_Loader extends CI_Loader {
public function __construct() {
parent::__construct();
}
public function controller($file_name) {
$CI = & get_instance();
$file_path = APPPATH.'controllers/' . $file_name . '.php';
$object_name = $file_name;
$class_name = ucfirst($file_name);
if (file_exists($file_path)) {
require $file_path;
$CI->$object_name = new $class_name();
}
else {
show_error('Unable to load the requested controller class: ' . $class_name);
}
}
}
then load controller within another controller.
It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).
This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.
The draft of HTML5 makes the attribute optional.
The answers above are so wrong! DO NOT add custom headers. Judging from your sample xml, it is a standard WS-Security header. WCF definitely supports it out of the box. When you add a service reference you should have basicHttpBinding binding created for you in the config file. You will have to modify it to include security element with mode TransportWithMessageCredential and message element with clientCredentialType = UserName:
<basicHttpBinding>
<binding name="usernameHttps">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
The config above is telling WCF to expect userid/password in the SOAP header over HTTPS. Then you can set id/password in your code before making a call:
var service = new MyServiceClient();
service.ClientCredentials.UserName.UserName = "username";
service.ClientCredentials.UserName.Password = "password";
Unless this particular service provider deviated from the standard, it should work.
Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager.
If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start. In some cases above state can stop though TCP connection to port 1433 is assigned.
Since the hosts is blocked. try connect it from other host and execute the mysqladmin flush-hosts command.
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
You can use -b to specify a cookie file to read the cookies from as well.
In many situations using -c and -b to the same file is what you want:
curl -b cookies.txt -c cookies.txt http://example.com
Further
Using only -c will make curl start with no cookies but still parse and understand cookies and if redirects or multiple URLs are used, it will then use the received cookies within the single invoke before it writes them all to the output file in the end.
The -b option feeds a set of initial cookies into curl so that it knows about them at start, and it activates curl's cookie parser so that it'll parse and use incoming cookies as well.
See Also
The cookies chapter in the Everything curl book.
Please take a look at jpa-metamodels-with-maven-example.
org.hibernate.org:hibernate-jpamodelgen
.org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor
. <dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${version.hibernate-jpamodelgen}</version>
<scope>provided</scope>
</dependency>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<compilerArguments>-AaddGeneratedAnnotation=false</compilerArguments> <!-- suppress java.annotation -->
<processors>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${version.hibernate-jpamodelgen}</version>
</dependency>
</dependencies>
</plugin>
org.apache.openjpa:openjpa
.org.apache.openjpa.persistence.meta.AnnotationProcessor6
.<openjpa.metamodel>true<openjpa.metamodel>
. <dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>-Aopenjpa.metamodel=true</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>org.apache.openjpa.persistence.meta.AnnotationProcessor6</processor>
</processors>
<optionMap>
<openjpa.metamodel>true</openjpa.metamodel>
</optionMap>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>${version.openjpa}</version>
</dependency>
</dependencies>
</plugin>
org.eclipse.persistence:org.eclipse.persistence.jpa.modelgen.processor
.org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor
.persistence.xml
. <dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<scope>provided</scope>
</dependency>
<plugins>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
</processors>
<compilerArguments>-Aeclipselink.persistencexml=src/main/resources-${environment.id}/META-INF/persistence.xml</compilerArguments>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>${version.eclipselink}</version>
</dependency>
</dependencies>
</plugin>
org.datanucleus:datanucleus-jpa-query
.org.datanucleus.jpa.query.JPACriteriaProcessor
. <dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-jpa-query</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>org.datanucleus.jpa.query.JPACriteriaProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-jpa-query</artifactId>
<version>${version.datanucleus}</version>
</dependency>
</dependencies>
</plugin>
The original, and standard, implementation of Python is usually called CPython
when
you want to contrast it with the other options (and just plain “Python” otherwise). This
name comes from the fact that it is coded in portable ANSI C language code
. This is
the Python that you fetch from http://www.python.org, get with the ActivePython and
Enthought distributions, and have automatically on most Linux and Mac OS X machines.
If you’ve found a preinstalled version of Python on your machine, it’s probably
CPython
, unless your company or organization is using Python in more specialized
ways.
Unless you want to script
Java
or.NET
applications with Python or find the benefits ofStackless
orPyPy
compelling, you probably want to use the standardCPython
system. Because it is the reference implementation of the language, it tends to run the fastest, be the most complete, and be more up-to-date and robust than the alternative systems.
This should work:
start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2
The start
command interprets the first argument as a window title if it contains spaces. In this case, that means start
considers your whole argument a title and sees no command. Passing ""
(an empty title) as the first argument to start
fixes the problem.
According to this post, it's much better now:
// pick out one album
JObject jalbum = albums[0] as JObject;
// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();
Documentation: Convert JSON to a Type