I have faced the same issue. I have changed the maven-assembly-plugin
to 3.1.1
from 2.5.3
in POM.xml
Proposed version should be done under plugin section. enter code here artifact Id for maven-assembly-plugin
Create an xml file any name (say progressBar.xml) in drawable
and add <color name="silverGrey">#C0C0C0</color>
in color.xml.
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="720" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="6"
android:useLevel="false" >
<size
android:height="200dip"
android:width="300dip" />
<gradient
android:angle="0"
android:endColor="@color/silverGrey"
android:startColor="@android:color/transparent"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Now in your xml file where you have your listView add this code:
<ListView
android:id="@+id/list_form_statusMain"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<ProgressBar
android:id="@+id/progressBar"
style="@style/CustomAlertDialogStyle"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:indeterminateDrawable="@drawable/circularprogress"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
In AsyncTask in the method:
@Override
protected void onPreExecute()
{
progressbar_view.setVisibility(View.VISIBLE);
// your code
}
And in onPostExecute:
@Override
protected void onPostExecute(String s)
{
progressbar_view.setVisibility(View.GONE);
//your code
}
In simple class declare context and get data from file from res folder
public class FileData
{
private Context context;
public FileData(Context current){
this.context = current;
}
void getData()
{
InputStream in = context.getResources().openRawResource(R.raw.file11);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//write stuff to get Data
}
}
In the activity class declare like this
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileData fileData=new FileData(this);
}
}
Even this works.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:drawable="@android:color/white" />
</selector>
I added the android:drawable
attribute to each item, and their values are colors.
By the way, why do they say that color
is one of the attributes of selector
? They don't write that android:drawable
is required.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="hex_color"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>
This usually happens to me after either eclipse has been running for a long time or after I have built a signed apk successfully.
As far as my experience with this is concerned, the fix it I just restart eclipse.
Ctrl + P (Win, Linux), Cmd + P (Mac) – Quick open, Go to file
If your problem persist with all those answers, try to change the file attribute to:
File.SetAttributes(yourfile, FileAttributes.Normal);
I found it strangely difficult to locate the python docs for __enter__
and __exit__
methods by Googling, so to help others here is the link:
https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers
https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers
(detail is the same for both versions)
object.__enter__(self)
Enter the runtime context related to this object. Thewith
statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.
object.__exit__(self, exc_type, exc_value, traceback)
Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will beNone
.If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.
Note that
__exit__()
methods should not reraise the passed-in exception; this is the caller’s responsibility.
I was hoping for a clear description of the __exit__
method arguments. This is lacking but we can deduce them...
Presumably exc_type
is the class of the exception.
It says you should not re-raise the passed-in exception. This suggests to us that one of the arguments might be an actual Exception instance ...or maybe you're supposed to instantiate it yourself from the type and value?
We can answer by looking at this article:
http://effbot.org/zone/python-with-statement.htm
For example, the following
__exit__
method swallows any TypeError, but lets all other exceptions through:
def __exit__(self, type, value, traceback):
return isinstance(value, TypeError)
...so clearly value
is an Exception instance.
And presumably traceback
is a Python traceback object.
You can do it like the other people before me told you using a look:
A.) Use .data of the button element to share a look variable (or a just global variable)
if ($('#buttonId').data('locked') == 1)
return
$('#buttonId').data('locked') = 1;
// Do your thing
$('#buttonId').data('locked') = 0;
B.) Disable mouse signals
$("#buttonId").css("pointer-events", "none");
// Do your thing
$("#buttonId").css("pointer-events", "auto");
C.) If it is a HTML button you can disable it (input [type=submit] or button)
$("#buttonId").attr("disabled", "true");
// Do your thing
$("#buttonId").attr("disabled", "false");
But watch out for other threads! I failed many times because my animation (fading in or out) took one second.
E.g. fadeIn/fadeOut supports a callback function as second parameter.
If there is no other way just do it using setTimeout(callback, delay)
.
Greets, Thomas
One way is to put all the nested loops into a function and return from the inner most loop incase of a need to break out of all loops.
function()
{
for(int i=0; i<1000; i++)
{
for(int j=0; j<1000;j++)
{
if (condition)
return;
}
}
}
select * from test;
a1 a2 a3
1 1 2
1 2 2
2 1 2
select t1.a3 from test t1, test t2 where t1.a1 = t2.a1 and t2.a2 = t1.a2 and t1.a1 = t2.a2
a3
1
You can try same thing using Joins too..
public boolean isInternetConnection()
{
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else {
return false;
}
}
Actually, passing a bitmap as a Parcelable will result in a "JAVA BINDER FAILURE" error. Try passing the bitmap as a byte array and building it for display in the next activity.
I shared my solution here:
how do you pass images (bitmaps) between android activities using bundles?
The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time
These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x)
to ask the question you want to ask with respect to the type of x:
js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false
Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html' apparently extensions can and will use the response header to alter the content prior to further processing by the browser. Changing the content-type fixed the issue.
var query = from a in d.tbl_Usuarios
from b in d.tblComidaPreferidas
from c in d.tblLugarNacimientoes
select new
{
_nombre = a.Nombre,
_comida = b.ComidaPreferida,
_lNacimiento = c.Ciudad
};
foreach (var i in query)
{
Console.WriteLine($"{i._nombre } le gusta {i._comida} y nació en {i._lNacimiento}");
}
I don't think you can both within the same jenkins job, what you need to do is to configure a new jenkins job which will have access to your github to retrieve branches and then you can choose which one to manually build.
Just mark it as a parameterized build, specify a name, and a parameter configured as git parameter
and now you can configure git options:
Please use SQL Server Data Tools from SQL Server Integration Services (Transfer Database Task) as here: https://stackoverflow.com/a/27777823/2127493
Here is a solution that also takes in account if you are using Ajax requests.
using System;
using System.Web.Mvc;
using System.Web.Routing;
namespace YourNamespace{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeCustom : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext context) {
if (YourAuthorizationCheckGoesHere) {
string area = "";// leave empty if not using area's
string controller = "ControllerName";
string action = "ActionName";
var urlHelper = new UrlHelper(context.RequestContext);
if (context.HttpContext.Request.IsAjaxRequest()){ // Check if Ajax
if(area == string.Empty)
context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(controller, action))}');</script>");
else
context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(area, controller, action))}');</script>");
} else // Non Ajax Request
context.Result = new RedirectToRouteResult(new RouteValueDictionary( new{ area, controller, action }));
}
base.OnActionExecuting(context);
}
}
}
Exit an app other way than the home button is really non-iOS-esque approach.
I did this helper, though, that use no private stuff:
void crash()
{ [[NSMutableArray new] addObject:NSStringFromClass(nil)]; }
But still not meant for production in my case. It is for testing crash reportings, or to fast restart after a Core Data reset. Just made it safe not to be rejected if function left in the production code.
@Vigril Disgr4ce
When it comes to multi field forms, it makes sense to use React's key feature: components.
In my projects, I create TextField components, that take a value prop at minimum, and it takes care of handling common behaviors of an input text field. This way you don't have to worry about keeping track of field names when updating the value state.
[...]
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
var value = this.state.value;
return <input type="text" value={value} onChange={this.handleChange} />;
}
[...]
import json
with open('result.json', 'w') as fp:
json.dump(sample, fp)
This is an easier way to do it.
In the second line of code the file result.json
gets created and opened as the variable fp
.
In the third line your dict sample
gets written into the result.json
!
According to the latest document when state is set to be directory, you don't need to use parameter recurse to create parent directories, file module will take care of it.
- name: create directory with parent directories
file:
path: /data/test/foo
state: directory
this is fare enough to create the parent directories data and test with foo
please refer the parameter description - "state" http://docs.ansible.com/ansible/latest/modules/file_module.html
I had win10 SDK and I only had to do retarget and then I stopped getting this error. The idea was that the project needs to upgrade its target Windows SDK.
write a cloud function to and update the node count.
// below function to get the given node count.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.userscount = functions.database.ref('/users/')
.onWrite(event => {
console.log('users number : ', event.data.numChildren());
return event.data.ref.parent.child('count/users').set(event.data.numChildren());
});
Refer :https://firebase.google.com/docs/functions/database-events
root--|
|-users ( this node contains all users list)
|
|-count
|-userscount :
(this node added dynamically by cloud function with the user count)
The message above means that you're running so many programs on your PC that there is no memory left to run one more. This isn't a Java problem and no Java option is going to change this.
Use the Task Manager of Windows to see how much of your 4GB RAM is actually free. My guess is that somewhere, you have a program that eats all the memory. Find it and kill it.
EDIT You need to understand that there are two types of "out of memory" errors.
The first one is the OutOfMemoryException which you get when Java code is running and the Java heap is not large enough. This means Java code asks the Java runtime for memory. You can fix those with -Xmx...
The other error is when the Java runtime runs out of memory. This isn't related to the Java heap at all. This is an error when Java asks the OS for more memory and the OS says: "Sorry, I don't have any."
To fix the latter, close applications or reboot (to clean up memory fragmentation).
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
Below are the steps I followed to install python34 and pip
yum update -y
yum -y install yum-utils
yum -y groupinstall development
yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum makecache
yum -y install python34u python34u-pip
python3.6 -v
echo "alias python=/usr/bin/python3.4" >> ~/.bash_profile
source ~/.bash_profile
pip3 install --upgrade pip
# if yum install python34u-pip doesnt work, try
curl https://bootstrap.pypa.io/get-pip.py | python
You could create a user form:
use the text and value attributes instead of the id
driver.findElementByXpath("//input[@value='cancel'][@title='cancel']").click();
similarly for Next.
As vim's own help on set background
says, "Setting this option does not change the background color, it tells Vim what the background color looks like. For changing the background color, see |:hi-normal|."
For example
:highlight Normal ctermfg=grey ctermbg=darkblue
will write in white on blue on your color terminal.
The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g"
, containing way too many slashes.
Since sed
can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:
replacement="/my/path"
sed --expression "s@pattern@$replacement@"
Note that this is not bullet proof: if the replacement string later contains @
it will break for the same reason, and any backslash sequences like \1
will still be interpreted according to sed
rules. Using |
as a delimiter is also a nice option as it is similar in readability to /
.
Use PowerShell:
$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"
# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath
In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.
Beware false negatives from the trim()
function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[]
could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
You can solve it by using the useRef
hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.
See this example:
var [state,setState,ref]=useStateRef(0)
It works exactly like useState
but in addition, it gives you the current state under ref.current
Learn more:
Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.
So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.
There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.
Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example
class MyInput
{
String str1;
String str2;
public MyInput() { }
// getters, setters
}
@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}
Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.
The last option is to construct a POST body that looks like:
str1=value1&str2=value2
then add some additional annotations to your server method:
public void create(@QueryParam("str1") String str1,
@QueryParam("str2") String str2)
@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).
If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.
Just use an explicit comparison with undefined.
function read_file(file, delete_after)
{
if(delete_after === undefined) { delete_after = false; }
}
1 - right click the highlight whose color you want to change
2 - select "Properties" in the popup menu
3 - choose the new color (as coobird suggested)
This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.
The problem here is that you have defined ID as a field in your data file when what you want is to just use an expression without any data from the data file. You can fix this by defining ID as an expression (or a sequence in this case)
ID EXPRESSION "ID_SEQ.nextval"
or
ID SEQUENCE(count)
See: http://docs.oracle.com/cd/B28359_01/server.111/b28319/ldr_field_list.htm#i1008234 for all options
Your change may well be working. Does your application need a lot of memory - the stack trace shows some Image related features.
I'm guessing that the error either happens right away, with a large file, or happens later after several requests.
If the error happens right away, then you can increase memory still further, or investigate find out why so much memory is needed for one file.
If the error happens after several requests, then you could have a memory leak - where objects are not being reclaimed by the garbage collector. Using a tool like JProfiler can help you monitor how much memory is being used by your VM and can help you see what is using that memory and why objects are not being reclaimed by the garbage collector.
You could also write your own IFormatProvider, though I suppose eventually you'd have to think of a way to do the actual truncation.
The .NET Framework also supports custom formatting. This typically involves the creation of a formatting class that implements both IFormatProvider and ICustomFormatter. (msdn)
At least it would be easily reusable.
There is an article about how to implement your own IFormatProvider/ICustomFormatter here at CodeProject. In this case, "extending" an existing numeric format might be the best bet. It doesn't look too hard.
I like rest-client a lot for the purposes you described. It's a Java application to test REST-based web services.
If the forked repo is protected so you can't push directly into it, and your goal is to make changes to their foo, then you need to get their branch foo into your repo like so:
git remote add protected_repo https://github.com/theirusername/their_repo.git
git fetch protected_repo
git checkout --no-track protected_repo/foo
Now you have a local copy of foo with no upstream associated to it. You can commit changes to it (or not) and then push your foo to your own remote repo.
git push --set-upstream origin foo
Now foo is in your repo on GitHub and your local foo is tracking it. If they continue to make changes to foo you can fetch theirs and merge into your foo.
git checkout foo
git fetch protected_repo
git merge protected_repo/foo
Use the double-star (aka double-splat?) operator:
func(**{'type':'Event'})
is equivalent to
func(type='Event')
From Java 8 API
It could be easier to take actual implementation from API doc https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#longs-long-long-long- they are using it to generate longs stream. And your origin can be "0" like in the question.
long nextLong(long origin, long bound) {
long r = nextLong();
long n = bound - origin, m = n - 1;
if ((n & m) == 0L) // power of two
r = (r & m) + origin;
else if (n > 0L) { // reject over-represented candidates
for (long u = r >>> 1; // ensure nonnegative
u + m - (r = u % n) < 0L; // rejection check
u = nextLong() >>> 1) // retry
;
r += origin;
}
else { // range not representable as long
while (r < origin || r >= bound)
r = nextLong();
}
return r;
}
Since the quickest, shortest answer is in a comment (from Jeff) and has a typo, here it is corrected and in full:
sales['time_hour'] = pd.DatetimeIndex(sales['timestamp']).hour
Follow the steps below in Oracle VM VirtualBox Manager:
To verify, start the Virtual device from Oracle VM VirtualBox. If all has gone well, the device boots up.
Close this device and open it from Genymotion.
There are always problems with Googles "oh so great" support libs. If you want to check an item without downgrading your support libs version, just set checkable before setting checked state.
MenuItem item = drawer.getMenu().findItem(R.id.action_something);
item.setCheckable(true);
item.setChecked(true);
It might also work if you set checkable in the menu xml files
Neither is better than the other, they do exactly the same thing. However, using .encode()
and .decode()
is the more common way to do it. It is also compatible with Python 2.
If your Manifest file has this line -
android:sharedUserId="android.uid.system"
is causing this error! just comment this line and you are good to go!!
(Neither IN
nor ANY
is an "operator". A "construct" or "syntax element".)
Logically, quoting the manual:
IN
is equivalent to= ANY
.
But there are two syntax variants of IN
and two variants of ANY
. Details:
IN
taking a set is equivalent to = ANY
taking a set, as demonstrated here:
But the second variant of each is not equivalent to the other. The second variant of the ANY
construct takes an array (must be an actual array type), while the second variant of IN
takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:
ANY
is more versatileThe ANY
construct is far more versatile, as it can be combined with various operators, not just =
. Example:
SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');
For a big number of values, providing a set scales better for each:
Related:
"Find rows where id
is in the given array":
SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);
Inversion: "Find rows where id
is not in the array":
SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}'); -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));
All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[]
.
Rows with id IS NULL
do not pass either of these expressions. To include NULL
values additionally:
SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;
All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long
is at least 32 bits, so %lu
together with (unsigned long)k
is always correct:
uint32_t k;
printf("%lu\n", (unsigned long)k);
size_t
is trickier, which is why %zu
was added in C99. If you can't use that, then treat it just like k
(long
is the biggest type in C89, size_t
is very unlikely to be larger).
size_t sz;
printf("%zu\n", sz); /* C99 version */
printf("%lu\n", (unsigned long)sz); /* common C89 version */
If you don't get the format specifiers correct for the type you are passing, then printf
will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.
If you could use List
as a data structure to store your data, instead of using Map
to store the result in the value of the Map, you can use following snippet and store the result in the same object.
Here is a Node class:
private class Node {
public int row, col, distance;
public Node(int row, int col, int distance) {
this.row = row;
this.col = col;
this.distance = distance;
}
public boolean equals(Object o) {
return (o instanceof Node &&
row == ((Node) o).row &&
col == ((Node) o).col);
}
}
If you store your result in distance variable and the items in the list are checked based on their coordinates, you can use the following to change the distance to a new one with the help of lastIndexOf method as long as you only need to store one element for each data:
List<Node> nodeList;
nodeList = new ArrayList<>(Arrays.asList(new Node(1, 2, 1), new Node(3, 4, 5)));
Node tempNode = new Node(1, 2, 10);
if(nodeList.contains(tempNode))
nodeList.get(nodeList.lastIndexOf(tempNode)).distance += tempNode.distance;
It is basically reimplementing Set
whose items can be accessed and changed.
As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)
Duration column = End - Start
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).
See http://api.jquery.com/on/#direct-and-delegated-events
Change your code to
$(document.body).on('click', '.update' ,function(){
The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live
, the jQuery set elements must exist when you execute the code.
As this answers receives a lot of attention, here are two supplementary advises :
1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.
That is, if you're adding an element of class b
to an existing element of id a
, then don't use
$(document.body).on('click', '#a .b', function(){
but use
$('#a').on('click', '.b', function(){
2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c"
would retrieve only one element with this id.
WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:
using (var client = new WebClient())
{
var json = client.DownloadString("http://example.com/json");
var serializer = new JavaScriptSerializer();
SomeModel model = serializer.Deserialize<SomeModel>(json);
// TODO: do something with the model
}
There are also some REST client frameworks you may checkout such as RestSharp.
^((localhost)|((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,253})$
Thank you @mkyong for the basis for my answer. I've modified it to support longer acceptable labels.
Also, "localhost" is technically a valid domain name. I will modify this answer to accommodate internationalized domain names.
It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:
ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;
The simplest solution is to select the second cell, and press =
. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1
) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.
To read up more on different options for referencing see - This Article.
Ajax forms work asynchronously using Javascript. So it is required, to load the script files for execution. Even though it's a small performance compromise, the execution happens without postback.
We need to understand the difference between the behaviours of both Html and Ajax forms.
Ajax:
Won't redirect the form, even you do a RedirectAction().
Will perform save, update and any modification operations asynchronously.
Html:
Will redirect the form.
Will perform operations both Synchronously and Asynchronously (With some extra code and care).
Demonstrated the differences with a POC in below link. Link
Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.
(Get-WmiObject -Class CIM_DataFile -Filter "Name='C:\\Windows\\explorer.exe'" | Select-Object Version).Version
I think it is possible but only for a short time
What you have to do is set the Access Control List of the file to Public Read-Only (or Public Read/Write). You can do that programmatically using the Google Document List API, or manually through the "Share" button on the Drive image viewer.
Then you can get the URL to the image programmatically by either using the Google Document List API or using the Google Drive API (i.e. file.getDownloadUrl() in Java). You can also easily get a link to the image manually by right clicking on the image in the Google Drive default image viewer.
The problem is that this link has a limited time to live, so it will work for a little while and then stop working.
Basically the URL of the image file stored in Drive should be accessible without any authentication once it has been set shared publicly but that URL is going to change at some point. We might find a solution to this in the future like providing a permanent URL that will redirect to these changing URL but no promises...
On my Windows instance - and I do not fully understand my environment - using pip3 to install the kaggle-cli package worked - whereas pip did not. I was working in a conda environment and the environments appear to be different.
(fastai) C:\Users\redact\Downloads\fast.ai\deeplearning1\nbs>pip --version
pip 9.0.1 from C:\ProgramData\Anaconda3\envs\fastai\lib\site-packages (python 3.6)
(fastai) C:\Users\redact\Downloads\fast.ai\deeplearning1\nbs>pip3 --version
pip 9.0.1 from c:\users\redact\appdata\local\programs\python\python36\lib\site-packages (python 3.6)
Would this work better?
import java.util.Scanner;
public class Work {
public static void main(String[] args){
System.out.println("Please enter the following information");
String name = "0";
String num = "0";
String address = "0";
int i = 0;
Scanner input = new Scanner(System.in);
//The Arrays
String [] contactName = new String [7];
String [] contactNum = new String [7];
String [] contactAdd = new String [7];
//I set these as the Array titles
contactName[0] = "Name";
contactNum[0] = "Phone Number";
contactAdd[0] = "Address";
//This asks for the information and builds an Array for each
//i -= i resets i back to 0 so the arrays are not 7,14,21+
while (i < 6){
i++;
System.out.println("Enter contact name." + i);
name = input.nextLine();
contactName[i] = name;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact number." + i);
num = input.nextLine();
contactNum[i] = num;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact address." + i);
num = input.nextLine();
contactAdd[i] = num;
}
//Now lets print out the Arrays
i -= i;
while(i < 6){
i++;
System.out.print( i + " " + contactName[i] + " / " );
}
//These are set to print the array on one line so println will skip a line
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactNum[i] + " / " );
}
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactAdd[i] + " / " );
}
System.out.println();
System.out.println("End of program");
}
}
Either one should work OK. In fact, System.Threading.Timer uses System.Timers.Timer internally.
Having said that, it's easy to misuse System.Timers.Timer. If you don't store the Timer object in a variable somewhere, then it is liable to be garbage collected. If that happens, your timer will no longer fire. Call the Dispose method to stop the timer, or use the System.Threading.Timer class, which is a slightly nicer wrapper.
What problems have you seen so far?
This article is clearly explained, how to install MySqli with EachApache. This works for me too.
To install mysqli using EachApache:
Login to WHM as 'root' user.
Either search for "EasyApache" or go to Software > EasyApache
Scroll down and select a build option (Previously Saved Config)
Click Start "Start customizing based on profile"
Select the version of Apache and click "Next Step".
Select the version of PHP and click "Next Step".
Chose additional options within the "Short Options List"
Select "Exhaustive Options List" and look for "MySQL Improved extension"
Click "Save and Build"
This is being described in this article. Think about forEach
of Collections.
List<?> list = …
list.forEach(…);
The forEach isn’t declared by
java.util.List
nor thejava.util.Collection
interface yet. One obvious solution would be to just add the new method to the existing interface and provide the implementation where required in the JDK. However, once published, it is impossible to add methods to an interface without breaking the existing implementation.The benefit that default methods bring is that now it’s possible to add a new default method to the interface and it doesn’t break the implementations.
Better Way -
double value = 10.567;
int result = (int)((value - (int)value) * 100);
Console.WriteLine(result);
Output -
56
How to get the first date of the current month correctly?
LocalDate.now()
.with( TemporalAdjusters.firstDayOfMonth() )
Or…
YearMonth.now().atDay( 1 )
Or…
LocalDate.now().with ( ChronoField.DAY_OF_MONTH , 1 )
The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.
The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.
LocalDate
For a date-only value, without time-of-day, use the LocalDate
class. While LocalDate
has no assigned time zone, we must specify a time zone in order to determine a date such as “today”. For example, a new day dawns earlier in Paris than in Montréal.
Time zone is crucial in determining today's date. For any given moment, the date varies around the world by zone. Omitting the time zone means the JVM’s current time zone is automatically applied in determining the current date. Any code in the JVM can change the default at runtime, so you are walking on shifting sands. Better to specify your desired/expected time zone explicitly than rely implicitly on the current default.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
LocalDate today = LocalDate.now ( zoneId );
LocalDate firstOfCurrentMonth = today.with ( ChronoField.DAY_OF_MONTH , 1 );
Dump to console.
System.out.println ( "For zoneId: " + zoneId + " today is: " + today + " and first of this month is " + firstOfCurrentMonth );
For zoneId: America/Montreal today is: 2015-11-08 and first of this month is 2015-11-01
Alternatively, use a TemporalAdjuster
. For your purpose, you will find handy implementations in the TemporalAdjusters
class (note plural s
), specifically firstDayOfMonth
.
LocalDate firstOfCurrentMonth = today.with( TemporalAdjusters.firstDayOfMonth() ) ;
ZonedDateTime
If you need a time of day, remember that 00:00:00.000
is not always the first moment of the day because of Daylight Saving Time (DST) and perhaps other anomalies. So let java.time determine the correct time of the first moment of the day.
ZonedDateTime zdt = firstOfCurrentMonth.atStartOfDay ( zoneId );
2015-11-01T00:00-04:00[America/Montreal]
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html
This is the greatest thing ever for learning VIM.
Solution for Windows:
.box
filevagrant box add --name name_of_my_box 'name_of_my_box.box'
vagrant box list
should show the new box in the listSolution for MAC:
.box
filevagrant box add --name name_of_my_box "./name_of_my_box.box"
vagrant box list
should show the new box in the listUse DATE()
function:
select * from follow_queue group by DATE(follow_date)
very simple
<img onload="loaded(this, 'success')" onerror="error(this,
'error')" src="someurl" alt="" />
function loaded(_this, status){
console.log(_this, status)
// do your work in load
}
function error(_this, status){
console.log(_this, status)
// do your work in error
}
Tried all the above solutions, but none of them worked. This issue comes when trying to add table to a class.
npm i react-native-table-component and then run App.js.
./node_modules/react-native-table-component/components/cell.js SyntaxError: C:\Users\Dileep\finaltest\node_modules\react-native-table-component\components\cell.js: Support for the experimental syntax 'classProperties' isn't currently enabled (5:20):
Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.
There's no Java collection in the standard library to do this. LinkedHashSet<E>
preserves ordering similarly to a List
, though, so if you wrap your set in a List
when you want to use it as a List
you'll get the semantics you want.
Alternatively, the Commons Collections (or commons-collections4
, for the generic version) has a List
which does what you want already: SetUniqueList
/ SetUniqueList<E>
.
CodeIgniter User Guide says:
$this->uri->segment(n)
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this: http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1. news 2. local 3. metro 4. crime_is_up
So segment
refers to your url structure segment. By the above example, $this->uri->segment(3)
would be 'metro'
, while $this->uri->segment(4)
would be 'crime_is_up'
.
One of your conditions is failing. Check the value of mime-type for your files.
Try using application/pdf, not text/pdf. Refer to Proper MIME media type for PDF files
Apart from accepted answer, following is also valid
Model.find()
can accept array of ids, and will return all records which matches.
Model.find_by_id(123)
also accept array but will only process first id value present in array
Model.find([1,2,3])
Model.find_by_id([1,2,3])
The following worked for me against a SQL Azure backend (using SQL Server Management Studio), so YMMV, but, if it works for you, it's waaaaay simpler than the other solutions.
ALTER TABLE MyTable
DROP CONSTRAINT FK_MyColumn
CONSTRAINT DK_MyColumn
-- etc...
COLUMN MyColumn
GO
myList[0]
gets the first item in the list. Since the list is empty there is no item to get and you get the IndexOutOfRangeException
instead.
As other answers here have shown, in order to check if the list is empty you need to get the number of elements in the list (myList.Count
) or use the LINQ method .Any()
which will return true if there are any elements in the list.
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
The compatibility table given in the tensorflow site does not contain specific minor versions for cuda and cuDNN. However, if the specific versions are not met, there will be an error when you try to use tensorflow.
For tensorflow-gpu==1.12.0
and cuda==9.0
, the compatible cuDNN
version is 7.1.4
, which can be downloaded from here after registration.
You can check your cuda version using
nvcc --version
cuDNN version using
cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2
tensorflow-gpu version using
pip freeze | grep tensorflow-gpu
UPDATE: Since tensorflow 2.0, has been released, I will share the compatible cuda and cuDNN versions for it as well (for Ubuntu 18.04).
tensorflow-gpu
= 2.0.0cuda
= 10.0cuDNN
= 7.6.0You have two choices here. The first is to have two result sets which will set 'Test1' or 'Test2' based on the condition in the WHERE
clause, and then UNION
them together:
select
'Test1', *
from
TABLE
Where
CCC='D' AND DDD='X' AND exists(select ...)
UNION
select
'Test2', *
from
TABLE
Where
CCC<>'D' AND DDD='X' AND exists(select ...)
This might be an issue, because you are going to effectively scan/seek on TABLE twice.
The other solution would be to select from the table once, and set 'Test1' or 'Test2' based on the conditions in TABLE:
select
case
when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1'
when CCC<>'D' AND DDD='X' AND exists(select ...) then 'Test2'
end,
*
from
TABLE
Where
(CCC='D' AND DDD='X' AND exists(select ...)) or
(CCC<>'D' AND DDD='X' AND exists(select ...))
The catch here being that you will have to duplicate the filter conditions in the CASE
statement and the WHERE
statement.
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
Different solution, webkit based. As mentioned already, anytime Chrome finds a password field it autocompletes the email. AFAIK, this is regardless of autocomplete = [whatever].
To circumvent this change the input type to text and apply the webkit security font in whatever form you want.
.secure-font{
-webkit-text-security:disc;}
<input type ="text" class="secure-font">
From what I can see this is at least as secure as input type=password, it's copy and paste secure. However it is vulnerable by removing the style which will remove asterisks, of course input type = password can easily be changed to input type = text in the console to reveal any autofilled passwords so it's much the same really.
I am having the same issue; Intellisense randomly will stop showing in some files, but not others. I just had it happen to me again. Hitting Ctrl + Space won't show anything in Form1
, switching to Form2
or any other class will pop up the list as expected. Restarting Visual Studio usually does the trick, though it's highly annoying and ridiculous for such a basic feature to be broken...
Why do you want to call cmd.exe
? cmd.exe
is a command line (shell). If you want to change directory, use os.chdir("C:\\")
. Try not to call external commands if Python can provide it. In fact, most operating system commands are provide through the os
module (and sys). I suggest you take a look at os
module documentation to see the various methods available.
I would use liquibase for updating your db. hibernate's schema update feature is really only o.k. for a developer while they are developing new features. In a production situation, the db upgrade needs to be handled more carefully.
On a side note. If you are using @media queries (such as @media screen (max-width:500px
)) pay particular attention to applying @media query AFTER you are done with normal styles. Because @media query will be crossed out (even though it is more specific) if followed by css that manipulates the same elements. Example:
@media (max-width:750px){
#buy-box {width: 300px;}
}
#buy-box{
width:500px;
}
** width will be 500px and 300px will be crossed out in Developer Tools. **
#buy-box{
width:500px;
}
@media (max-width:750px){
#buy-box {width: 300px;}
}
** width will be 300px and 500px will be crossed out **
for (int i = 0; i != 5; ++i, ++j)
do_something(i, j);
In your sendMail()
function, add an ajax call to your backend, where you can implement this on the server side.
You could opt for a pure CSS solution:
#hfont1 {
transition: color 1s ease-in-out;
-moz-transition: color 1s ease-in-out; /* FF 4 */
-webkit-transition: color 1s ease-in-out; /* Safari & Chrome */
-o-transition: color 1s ease-in-out; /* Opera */
}
Most likely both tables have a column with the same name. Alias each table, and call each column with the table alias.
Maybe you mean
select x
from some_table
where some_column is null or some_column = ''
but I can't tell since you didn't really ask a question.
shadowing = maintains two definitions at derived class and in order to project the base class definition it shadowes(hides)derived class definition and vice versa.
On Android, you can use the Uri.parse static method of the android.net.Uri class to do the heavy lifting. If you're doing anything with URIs and Intents you'll want to use it anyways.
The javascript is a weakly typed language i.e. without any data-types as there in C,c++ eg. int, boolean, float etc. thus a variable can hold any type of value, that why these special comparison operators are there
Eg
var i = 20;var j = "20";
if we apply comparison operators these variables result will be
i==j //result is true
or
j != i//result is false
for that we need a special comparison operators which checks for the value as well as for the data type of the variable
if we do
i===j //result is false
log2j now has support to delete old logs.
Take a look at DefaultRolloverStrategy tag and at a snippet below.
It
creates up to 10 archives on the same day,
will parse the ${baseDir} directory that you define under the Properties tag at max depth of 2 with log filename matching "app-*.log.gz"
delete logs older than 7 days but keep the most recent 5 logs if your most recent 5 logs are older than 7 days.
<DefaultRolloverStrategy max="10">
<Delete basePath="${baseDir}" maxDepth="2">
<IfFileName glob="*/app-*.log.gz">
<IfLastModified age="7d">
<IfAny>
<IfAccumulatedFileCount exceeds="5" />
</IfAny>
</IfLastModified>
</IfFileName>
</Delete>
</DefaultRolloverStrategy>
A good debug option is if you set:
<Configuration status="trace">
and use testMode Option like this:
<DefaultRolloverStrategy>
<Delete basePath="${baseDir}" testMode="true">
<IfFileName glob="*.log" />
<IfLastModified age="7d" />
</Delete>
</DefaultRolloverStrategy>
You can see in console log what files would get deleted without deleting the files right away.
Delete unversioned files and revert any changes:
svn revert D:\tmp\sql -R
svn cleanup D:\tmp\sql --remove-unversioned
Out:
D D:\tmp\sql\update\abc.txt
A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.
Subject example (with RxJS 5 API):
const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));
Console output will be empty
BehaviorSubject example:
const subject = new Rx.BehaviorSubject(0);
subject.next(1);
subject.subscribe(x => console.log(x));
Console output: 1
In addition:
BehaviorSubject
should be created with an initial value: new Rx.BehaviorSubject(1)
ReplaySubject
if you want the subject to hold more than one valueimport io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')
# read bytes from archive
img_data = archive.read('img_01.png')
# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)
img = pygame.image.load(bytes_io)
I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.
For those doing some sklearn/numpy post processing (i.e. Deep learning) you can wrap the PIL object with np.array(). This might save you from having to Google it like I did:
from PIL import Image
import requests
import numpy as np
from StringIO import StringIO
response = requests.get(url)
img = np.array(Image.open(StringIO(response.content)))
The thing is that, when you call a function you should not write the type of the function, that means you should call the funnction just like
initializeJSP(Experiment);
I have problem with the accepted answer, so I updated it, this is working for me:
.h
@interface MaxSpacingCollectionViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic,assign) CGFloat maxCellSpacing;
@end
.m
@implementation MaxSpacingCollectionViewFlowLayout
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
if (attributes.count <= 0) return attributes;
CGFloat firstCellOriginX = ((UICollectionViewLayoutAttributes *)attributes[0]).frame.origin.x;
for(int i = 1; i < attributes.count; i++) {
UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
if (currentLayoutAttributes.frame.origin.x == firstCellOriginX) { // The first cell of a new row
continue;
}
UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
CGFloat prevOriginMaxX = CGRectGetMaxX(prevLayoutAttributes.frame);
if ((currentLayoutAttributes.frame.origin.x - prevOriginMaxX) > self.maxCellSpacing) {
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = prevOriginMaxX + self.maxCellSpacing;
currentLayoutAttributes.frame = frame;
}
}
return attributes;
}
@end
Using find
's -regex
argument:
find . -regex '.*/Robert\.\(h\|cpp\)$'
Or just using -name
:
find . -name 'Robert.*' -a \( -name '*.cpp' -o -name '*.h' \)
You can achieve this by using the following query:
EXEC sp_msforeachdb
'IF EXISTS
(
SELECT 1
FROM [?].sys.objects
WHERE name LIKE ''OBJECT_TO_SEARCH''
)
SELECT
''?'' AS DB,
name AS Name,
type_desc AS Type
FROM [?].sys.objects
WHERE name LIKE ''OBJECT_TO_SEARCH'''
Just replace OBJECT_TO_SEARCH with the actual object name you are interested in (or part of it, surrounded with %).
More details here: https://peevsvilen.blog/2019/07/30/search-for-an-object-in-sql-server/
Here's a pure VBA solution because Excel can hold joined cells:
Public Function GetIndexForColumn(Column As String) As Long
Dim astrColumn() As String
Dim Result As Long
Dim i As Integer
Dim n As Integer
Column = UCase(Column)
ReDim astrColumn(Len(Column) - 1)
For i = 0 To (Len(Column) - 1)
astrColumn(i) = Mid(Column, (i + 1), 1)
Next
n = 1
For i = UBound(astrColumn) To 0 Step -1
Result = (Result + ((Asc(astrColumn(i)) - 64) * n))
n = (n * 26)
Next
GetIndexForColumn = Result
End Function
Basically, this function does the same as any Hex to Dec function, except that it only takes alphabetical chars (A = 1, B = 2, ...). The rightmost char counts single, each char to the left counts 26 times the char right to it (which makes AA = 27 [1 + 26], AAA = 703 [1 + 26 + 676]). The use of UCase() makes this function case-insensitive.
With Husky:
{
"name": "demo-project",
"version": "0.0.3",
"husky": {
"hooks": {
"pre-commit": "npm --no-git-tag-version version patch && git add ."
}
}
}
If you are averse to boost, you can use regular old operator>>
, along with std::noskipws
:
EDIT: updates after testing.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>
void split(const std::string& str, std::vector<std::string>& v) {
std::stringstream ss(str);
ss >> std::noskipws;
std::string field;
char ws_delim;
while(1) {
if( ss >> field )
v.push_back(field);
else if (ss.eof())
break;
else
v.push_back(std::string());
ss.clear();
ss >> ws_delim;
}
}
int main() {
std::vector<std::string> v;
split("hello world how are you", v);
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "-"));
std::cout << "\n";
}
The OP's question: What is the difference between the return and exit statement in BASH functions with respect to exit codes?
Firstly, some clarification is required:
A (return|exit) statement is not required to terminate execution of a (function|shell). A (function|shell) will terminate when it reaches the end of its code list, even with no (return|exit) statement.
A (return|exit) statement is not required to pass a value back from a terminated (function|shell). Every process has a built-in variable $?
which always has a numeric value. It is a special variable that cannot be set like "?=1", but it is set only in special ways (see below *).
The value of $? after the last command to be executed in the (called function | sub shell) is the value that is passed back to the (function caller | parent shell). That is true whether the last command executed is ("return [n]"| "exit [n]") or plain ("return" or something else which happens to be the last command in the called function's code.
In the above bullet list, choose from "(x|y)" either always the first item or always the second item to get statements about functions and return, or shells and exit, respectively.
What is clear is that they both share common usage of the special variable $?
to pass values upwards after they terminate.
* Now for the special ways that $?
can be set:
$?
in the terminated function.$?
in the parent shell will be equal to the final value of $?
in the terminated sub shell.$?
depending upon their result. But some don't.$?
with argument, and terminate execution.It is worth noting that $?
can be assigned a value by calling exit in a sub shell, like this:
# (exit 259)
# echo $?
3
The previous answers are now deprecated, you need to use ContextCompat.getColor
to retrieve the color properly:
root.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.white));
What you can do is change the class of your object and define two classes with different hover properties. For example:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
And this I found on: Change an element's class with JavaScript
function changeClass(object,oldClass,newClass)
{
// remove:
//object.className = object.className.replace( /(?:^|\s)oldClass(?!\S)/g , '' );
// replace:
var regExp = new RegExp('(?:^|\\s)' + oldClass + '(?!\\S)', 'g');
object.className = object.className.replace( regExp , newClass );
// add
//object.className += " "+newClass;
}
changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");
Using Roslyn, you can dynamically create a class which inherits from an interface (or abstract class).
I use the following to create concrete classes from abstract classes.
In this example, AAnimal is an abstract class.
var personClass = typeof(AAnimal).CreateSubclass("Person");
Then you can instantiate some objects:
var person1 = Activator.CreateInstance(personClass);
var person2 = Activator.CreateInstance(personClass);
Without a doubt this won't work for every case, but it should be enough to get you started:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Publisher
{
public static class Extensions
{
public static Type CreateSubclass(this Type baseType, string newClassName, string newNamespace = "Magic")
{
//todo: handle ref, out etc.
var concreteMethods = baseType
.GetMethods()
.Where(method => method.IsAbstract)
.Select(method =>
{
var parameters = method
.GetParameters()
.Select(param => $"{param.ParameterType.FullName} {param.Name}")
.ToString(", ");
var returnTypeStr = method.ReturnParameter.ParameterType.Name;
if (returnTypeStr.Equals("Void")) returnTypeStr = "void";
var methodString = @$"
public override {returnTypeStr} {method.Name}({parameters})
{{
Console.WriteLine(""{newNamespace}.{newClassName}.{method.Name}() was called"");
}}";
return methodString.Trim();
})
.ToList();
var concreteMethodsString = concreteMethods
.ToString(Environment.NewLine + Environment.NewLine);
var classCode = @$"
using System;
namespace {newNamespace}
{{
public class {newClassName}: {baseType.FullName}
{{
public {newClassName}()
{{
}}
{concreteMethodsString}
}}
}}
".Trim();
classCode = FormatUsingRoslyn(classCode);
/*
var assemblies = new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(baseType.Assembly.Location),
};
*/
var assemblies = AppDomain
.CurrentDomain
.GetAssemblies()
.Where(a => !string.IsNullOrEmpty(a.Location))
.Select(a => MetadataReference.CreateFromFile(a.Location))
.ToArray();
var syntaxTree = CSharpSyntaxTree.ParseText(classCode);
var compilation = CSharpCompilation
.Create(newNamespace)
.AddSyntaxTrees(syntaxTree)
.AddReferences(assemblies)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
//compilation.Emit($"C:\\Temp\\{newNamespace}.dll");
if (result.Success)
{
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = Assembly.Load(ms.ToArray());
var newTypeFullName = $"{newNamespace}.{newClassName}";
var type = assembly.GetType(newTypeFullName);
return type;
}
else
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
return null;
}
}
}
public static string ToString(this IEnumerable<string> list, string separator)
{
string result = string.Join(separator, list);
return result;
}
public static string FormatUsingRoslyn(string csCode)
{
var tree = CSharpSyntaxTree.ParseText(csCode);
var root = tree.GetRoot().NormalizeWhitespace();
var result = root.ToFullString();
return result;
}
}
}
Either encode the needed XML entities or use CDATA.
<arg0>
<!--Optional:-->
<parameter1><test>like this</test></parameter1>
<!--Optional:-->
<parameter2><![CDATA[<test>or like this</test>]]></parameter2>
</arg0>
I had a problem because my canvas was inside of a container without ID so I used this jquery code below
$('.cropArea canvas').width()
Here some guide how to fix it. Go to :
cd /var/www
sudo chown www-data:www-data * -R
sudo usermod -a -G www-data username
Change userneme with your username. I hope it help.
$this->db->where_in('id', ['20','15','22','42','86']);
Reference: where_in
With VS2010+ there is a plugin solution: Line Endings Unifier.
With the plugin installed you can right click files and folders in the solution explorer and invoke the menu item Unify Line Endings in this file
Configuration for this is available via
Tools -> Options -> Line Endings Unifier.
The default file extension list that is included is pretty narrow:
.cpp; .c; .h; .hpp; .cs; .js; .vb; .txt;
Might want to use something like:
.cpp; .c; .h; .hpp; .cs; .js; .vb; .txt; .scss; .coffee; .ts; .jsx; .markdown; .config
If you aren't dynamically loading scripts or marking them as defer
or async
, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.
Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.
There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.
When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.
A script tag with async
may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async
is that it can run anytime and that time is not predictable.
A script tag with defer
waits until the entire parser is done and then runs all scripts marked with defer
in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer
. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer
like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer
or async
.
Here's a quote from that article:
script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.
The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.
A quote from the HTML5 spec:
Then, the first of the following options that describes the situation must be followed:
If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.
The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)
The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)
Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.
If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.
The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:
If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.
Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.
Remove the first element from this list of scripts that will execute in order as soon as possible.
If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.
If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.
The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.
Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.
What about Javascript module scripts, type="module"
?
Javascript now has support for module loading with syntax like this:
<script type="module">
import {addTextToBody} from './utils.mjs';
addTextToBody('Modules are pretty cool.');
</script>
Or, with src
attribute:
<script type="module" src="http://somedomain.com/somescript.mjs">
</script>
All scripts with type="module"
are automatically given the defer
attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.
Module scripts can also be given the async
attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async
script in any particular order relative to other scripts.
There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.
For triggers in general, you need to use a cursor to handle inserts or updates of multiple rows. For example:
DECLARE @Attribute;
DECLARE @ParameterValue;
DECLARE mycursor CURSOR FOR SELECT Attribute, ParameterValue FROM inserted;
OPEN mycursor;
FETCH NEXT FROM mycursor into @Attribute, @ParameterValue;
WHILE @@FETCH_STATUS = 0
BEGIN
If @Attribute LIKE 'NoHist_%'
Begin
Return
End
etc.
FETCH NEXT FROM mycursor into @Attribute, @ParameterValue;
END
Triggers, at least in SQL Server, are a big pain and I avoid using them at all.
(can't comment or I would just do that) I believe the suggestion to check locals above is not quite right. It should be:
foo = foo if 'foo' in locals() or 'foo' in globals() else 'default'
to be correct in all contexts.
However, despite its upvotes, I don't think even that is a good analog to the Ruby operator. Since the Ruby operator allows more than just a simple name on the left:
foo[12] ||= something
foo.bar ||= something
The exception method is probably closest analog.
strong is the default. An object remains “alive” as long as there is a strong pointer to it.
weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
i think this solution is shorter and simpler than older answers. This is Js Code:
const navbar = document.querySelector('.nav-fixed');
window.onscroll = () => {
if (window.scrollY > 300) {
navbar.classList.add('nav-active');
} else {
navbar.classList.remove('nav-active');
}
};
And my css:
header.nav-fixed {
width: 100%;
position: fixed;
transition: 0.3s ease-in-out;
}
.nav-active {
background-color:#fff;
box-shadow: 5px -1px 12px -5px grey;
}
This is what I did on OS X Mavericks to get this to work.
Firstly, have brew installed
Install python 3.4
brew install python3
Then I get the latest version of distribute:
wget https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip#md5=c6c59594a7b180af57af8a0cc0cf5b4a
unzip distribute-0.7.3.zip
cd distribute-0.7.3
sudo setup.py install
sudo easy_install-3.4 pip
sudo pip3.4 install virtualenv
sudo pip3.4 install virtualenvwrapper
mkvirtualenv py3
python --version
Python 3.4.1
I hope this helps.
If you still facing the issue try this:
Open your IIS Manager -> Application Pools -> select your app pool -> Advance Setting -> Under 'Process Model' set 'Load User Profile' setting as True
In my case I was having the same error and later I come to know that the 'condition' is mysql reserved keyword and I used that as field name.
First execute this
sudo apt-get install gcc binutils make linux-source
Then run again
/usr/bin/vmware-config-tools.pl
This is all you need to do. Now your system has the gcc make and the linux kernel sources.
If you want your own custom Error Logging you can easily write your own code. I'll give you a snippet from one of my projects.
public void SaveLogFile(object method, Exception exception)
{
string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
try
{
//Opens a new file stream which allows asynchronous reading and writing
using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
{
//Writes the method name with the exception and writes the exception underneath
sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
sw.WriteLine(exception.ToString()); sw.WriteLine("");
}
}
catch (IOException)
{
if (!File.Exists(location + @"log.txt"))
{
File.Create(location + @"log.txt");
}
}
}
Then to actually write to the error log just write (q
being the caught exception)
SaveLogFile(MethodBase.GetCurrentMethod(), `q`);
If the operating system is Linux then just use it will work
sudo npm run server
The JDK does not install a JVM in the default path.
Unless you need external tools to run like ant, the non-JDK is enough for Eclipse to run. The easiest way to install such a JVM is to go to http://java.com and let it install whatever it want to install.
Then double-click the Eclipse binary again.
AndroidStudio:
Go to: Tools -> Android -> Android Device Monitor
see the Device tab, under many icons, last one is drop-down arrow.
Open it.
At the bottom: RESET ADB.
IIRC Code Behind is compiled serverside and javascript is interpreted client side. This means there is no direct link between the two.
What you can do on the other hand is have the client and server communicate through a nifty tool called AJAX. http://en.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML
var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
Example: http://jsfiddle.net/e27r8/
This uses the closest()
[docs] method to get the first ancestor that has a nested h3 span b
, then does a .find()
.
Of course you could have multiple matches.
Otherwise, you're looking at doing a more direct traversal.
var link = $("#me").closest("h3 + div").prev().find('span b');
edit: This one works with your updated HTML.
Example: http://jsfiddle.net/e27r8/2/
EDIT: Updated to deal with updated question.
var link = $("#me").closest("h3 + *").prev().find('span b');
This makes the targeted element for .closest()
generic, so that even if there is no parent, it will still work.
Example: http://jsfiddle.net/e27r8/4/
I think the most simple & straightforward way is
for f in *.*; do echo "${f##*.}"; done | sort -u
It's modified on ChristopheD's 3rd way.
You can use the scales package just for this operation (without loading it with require or library)
scales::percent(m)
I had the same issue with Axios requests in a Vue-CLI App. On further checking in Network tab of Chrome, I found that the request URL of axios correctly had https
but response 'location' header was http
.
This was caused by nginx
and I fixed it by adding these 2 lines to server config for nginx:
server {
...
add_header Strict-Transport-Security "max-age=31536000" always;
add_header Content-Security-Policy upgrade-insecure-requests;
...
}
Might be irrelevant but my Vue-CLI App was served under a subpath in nginx with config as:
location ^~ /admin {
alias /home/user/apps/app_admin/dist;
index index.html;
try_files $uri $uri/ /index.html;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host;
}
Store it in a field of type long
. See Date.getTime()
and new Date(long)
Not sure from what version, but I use 1.3.14 and you can just use:
window.location.href = '/employee/1';
No need to inject $location
or $window
in the controller and no need to get the current host address.
As an additional technique, if you have the private repository cloned locally, you can do:
pip install git+file://c:/repo/directory
More modernly, you can just do this (and the -e
will mean you don't have to commit changes before they're reflected):
pip install -e C:\repo\directory
No, you don't have to include all of POI's dependencies. Maven's transitive dependency mechanism will take care of that. As noted you just have to express a dependency on the appropriate POI artifact. For example:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8-beta4</version>
</dependency>
Edit(UPDATE): I don't know about previous versions but to resolve imports to XSSFWorkbook and other classes in org.apache.poi package you need to add dependency for poi-ooxml too. The dependencies will be:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
You can simply use../your_script_name.py
For example suppose the path to your python script is trading system/trading strategies/ts1.py
. To refer to volume.csv
located in trading system/data/
. You simply need to refer to it as ../data/volume.csv
You can able to download Xcode DMG file from the
Seems that kramdown supports colors in some form.
Kramdown allows inline html:
This is <span style="color: red">written in red</span>.
Also it has another syntax for including css classes inline:
This is *red*{: style="color: red"}.
This page further explains how GitLab utilizes more compact way to apply css classes in Kramdown:
Applying
blue
class to text:This is a paragraph that for some reason we want blue. {: .blue}
Applying
blue
class to headings:#### A blue heading {: .blue}
Applying two classes:
A blue and bold paragraph. {: .blue .bold}
Applying ids:
#### A blue heading {: .blue #blue-h}
This produces:
<h4 class="blue" id="blue-h">A blue heading</h4>
There is a lot of other stuff explained at above link. You may need to check.
Also, as other answer said, Kramdown is also the default markdown renderer behind Jekyll. So if you are authoring anything on github pages, above functionality might be available out of the box.
Or, you can set a margin-top on the iframe...a bit of a hack but works in FF so far.
#frame {
margin-top:200px;
}
You can define a Headers object with a dictionary of HTTP key/value pairs, and then pass it in as an argument to http.get()
and http.post()
like this:
const headerDict = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
}
const requestOptions = {
headers: new Headers(headerDict),
};
return this.http.get(this.heroesUrl, requestOptions)
Or, if it's a POST request:
const data = JSON.stringify(heroData);
return this.http.post(this.heroesUrl, data, requestOptions);
Since Angular 7 and up you have to use HttpHeaders
class instead of Headers
:
const requestOptions = {
headers: new HttpHeaders(headerDict),
};
@bninopaul 's answer is not completely for beginners
here is the code you can "copy and run"
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[13,1,1,0,2,0],
[3,9,6,0,1,0],
[0,0,16,2,0,0],
[0,0,0,13,0,0],
[0,0,0,0,15,0],
[0,0,1,0,0,15]]
df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size
plt.show()
I was in the same situation as you, the half answers scattered throughout the Internet were quite annoying, since it seemed that many people had the same issue, but no one could be bothered to fully explain how they solved it.
The Sonar docs refer to a GitHub project with examples that are helpful. What I did to solve this was to apply the integration tests logic to regular unit tests (although proper unit tests should be submodule specific, this isn't always the case).
In the parent pom.xml, add these properties:
<properties>
<!-- Sonar -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
</properties>
This will make Sonar pick up unit testing reports for all submodules in the same place (a target folder in the parent project). It also tells Sonar to reuse reports ran manually instead of rolling its own. We just need to make jacoco-maven-plugin run for all submodules by placing this in the parent pom, inside build/plugins:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.6.0.201210061924</version>
<configuration>
<destFile>${sonar.jacoco.reportPath}</destFile>
<append>true</append>
</configuration>
<executions>
<execution>
<id>agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
destFile
places the report file in the place where Sonar will look for it and append
makes it append to the file rather than overwriting it. This will combine all JaCoCo reports for all submodules in the same file.
Sonar will look at that file for each submodule, since that's what we pointed him at above, giving us combined unit testing results for multi module files in Sonar.
This is a paragraph option. Go to Window>Paragraph then a small window will pop up. You will have two buttons on the bottom. One with a arrow on the left of P and one on the right. Select the right one.
Using split()
will be the most Pythonic way of splitting on a string.
It's also useful to remember that if you use split()
on a string that does not have a whitespace then that string will be returned to you in a list.
Example:
>>> "ark".split()
['ark']
private static byte[] charArrayToByteArray(char[] c_array) {
byte[] b_array = new byte[c_array.length];
for(int i= 0; i < c_array.length; i++) {
b_array[i] = (byte)(0xFF & (int)c_array[i]);
}
return b_array;
}
If you are Struggling with addToBackStack() & popBackStack() then simply use
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragment(), "Home");
ft.commit();`
In your Activity In OnBackPressed() find out fargment by tag and then do your stuff
Fragment home = getSupportFragmentManager().findFragmentByTag("Home");
if (home instanceof HomeFragment && home.isVisible()) {
// do you stuff
}
For more Information https://github.com/DattaHujare/NavigationDrawer I never use addToBackStack() for handling fragment.
Inverse of a matrix using python and numpy:
>>> import numpy as np
>>> b = np.array([[2,3],[4,5]])
>>> np.linalg.inv(b)
array([[-2.5, 1.5],
[ 2. , -1. ]])
Not all matrices can be inverted. For example singular matrices are not Invertable:
>>> import numpy as np
>>> b = np.array([[2,3],[4,6]])
>>> np.linalg.inv(b)
LinAlgError: Singular matrix
Solution to singular matrix problem:
try-catch the Singular Matrix exception and keep going until you find a transform that meets your prior criteria AND is also invertable.
Intuition for why matrix inversion can't always be done; like in singular matrices:
Imagine an old overhead film projector that shines a bright light through film onto a white wall. The pixels in the film are projected to the pixels on the wall.
If I stop the film projection on a single frame, you will see the pixels of the film on the wall and I ask you to regenerate the film based on what you see. That's easy, you say, just take the inverse of the matrix that performed the projection. An Inverse of a matrix is the reversal of the projection.
Now imagine if the projector was corrupted, and I put a distorted lens in front of the film. Now multiple pixels are projected to the same spot on the wall. I asked you again to "undo this operation with the matrix inverse". You say: "I can't because you destroyed information with the lens distortion, I can't get back to where we were, because the matrix is either Singular or Degenerate."
A matrix that can be used to transform some data into other data is invertable only if the process can be reversed with no loss of information. If your matrix can't be inverted, perhaps you are defining your projection using a guess-and-check methodology rather than using a process that guarantees a non-corrupting transform.
If you're using a heuristic or anything less than perfect mathematical precision, then you'll have to define another process to manage and quarantine distortions so that programming by Brownian motion can resume.
Source:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html#numpy.linalg.inv
Try replacing <%# Eval("item") %>
with <%# If(Eval("item"), "0 value") %>
(or <%# Eval("item") ?? "0 value" %>
, when using C#).
If what you want is to hide the navigation bar completely in the controller, a much cleaner solution is to, in the root controller, have something like:
@implementation MainViewController
- (void)viewDidLoad {
self.navigationController.navigationBarHidden=YES;
//...extra code on view load
}
When you push a child view in the controller, the Navigation Bar will remain hidden; if you want to display it just in the child, you'll add the code for displaying it(self.navigationController.navigationBarHidden=NO;)
in the viewWillAppear
callback, and similarly the code for hiding it on viewWillDisappear
From PowerShell version 5 onwards (included in Windows Server 2016, downloadable as part of WMF 5 for earlier versions), this is possible with remoting. The benefit of this is that it works even if, for whatever reason, you can't access shares.
For this to work, the local session where copying is initiated must have PowerShell 5 or higher installed. The remote session does not need to have PowerShell 5 installed -- it works with PowerShell versions as low as 2, and Windows Server versions as low as 2008 R2.[1]
From server A, create a session to server B:
$b = New-PSSession B
And then, still from A:
Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt
Copying items to B is done with -ToSession
. Note that local paths are used in both cases; you have to keep track of what server you're on.
[1]: when copying from or to a remote server that only has PowerShell 2, beware of this bug in PowerShell 5.1, which at the time of writing means recursive file copying doesn't work with -ToSession
, an apparently copying doesn't work at all with -FromSession
.
When I asked this question almost 2 years ago the answer really was “officially” no, but as pointed out by ekcr1's answer you can get one of the most highly anticipated features (lambdas) to work if you use retrolamba. At the time I was still using eclipse, as Android Studio was in “preview” mode, so I never did pursue this path.
Today, I think the “official” answer is still no, and while retrolamba still seems like a good way to go, there is another option for those willing to go down a somewhat “unofficial” route can take, namely Kotlin.
Today Kotlin reached 1.0.0. For those not familiar with Kotlin, more info can be found at their website found here:
or watch this utube video of a talk given by Jake Wharton
open the "edit the system environment variables". then click on "environment variables".
Under "User variables" click on "Path" then "Edit".
Find your Java path and click "Edit".
then paste the path of your java installation folder. Mostly you can find it on a path similar to this. C:\Program Files\Java\jdk-12.0.2\bin
Then click OK. now in the start menu, type cmd. open the command prompt. type java -version If you did it right,it should show something like this.
I have similar issue faced and solve with following solution: my date format is: 'Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)'
let currentDate = moment(new Date('Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)').format('DD-MM-YYYY'); // 'Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)'
let output=(moment(currentDate).isSameOrAfter('07-12-2020'));
If your package.json looks something like the following:
...
"devDependencies": {
"babel": "^6.5.2",
"babel-eslint": "^6.0.4",
"babel-polyfill": "^6.8.0",
"babel-preset-es2015": "^6.6.0",
"babelify": "^7.3.0",
...
And you get the Cannot find module 'babel/polyfill'
error message, then you probably just need to change your import statement FROM:
import "babel/polyfill";
TO:
import "babel-polyfill";
And make sure it comes before any other import
statement (not necessarily at the entry point of your application).
Reference: https://babeljs.io/docs/usage/polyfill/
To just get everything done goto Window>Preferences>General and goto theme menu and change it... Then re-start to apply...
The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.
If you set fetchType=EAGER
This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.
If you set fetchType=LAZY
the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.
You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.
For the second part of the question - how to get hibernate to generate optimised SQL?
Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.
A submodule may be marked as dirty if filemode settings is enabled and you changed file permissions in submodule subtree.
To disable filemode in a submodule, you can edit /.git/modules/path/to/your/submodule/config and add
[core]
filemode = false
If you want to ignore all dirty states, you can either set ignore = dirty
property in /.gitmodules file, but I think it's better to only disable filemode.
If a table name contains underscores or upper case, you need to surround it in double-quotes.
SELECT * from "Table_Name";
I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.
example:
linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));
see definition: http://man7.org/linux/man-pages/man7/socket.7.html
SO_LINGER
Sets or gets the SO_LINGER option. The argument is a linger
structure.
struct linger {
int l_onoff; /* linger active */
int l_linger; /* how many seconds to linger for */
};
When enabled, a close(2) or shutdown(2) will not return until
all queued messages for the socket have been successfully sent
or the linger timeout has been reached. Otherwise, the call
returns immediately and the closing is done in the background.
When the socket is closed as part of exit(2), it always
lingers in the background.
More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required
i did this:
list = [1,2,3,4,5]
tuple = (list)
and to change, just do
list[0]=6
and u can change a tuple :D
here is it copied exactly from IDLE
>>> list=[1,2,3,4,5,6,7,8,9]
>>> tuple=(list)
>>> print(tuple)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[0]=6
>>> print(tuple)
[6, 2, 3, 4, 5, 6, 7, 8, 9]
i find no reason to do this $scope.value = $rootScope.test;
$scope is already prototype inheritance from $rootScope.
Please see this example
var app = angular.module('app',[]).run(function($rootScope){
$rootScope.userName = "Rezaul Hasan";
});
now you can bind this scope variable in anywhere in app tag.
If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.
@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
}
This sets the path for the current session and prompts the user to add it permanently:
function Set-Path {
param([string]$x)
$Env:Path+= ";" + $x
Write-Output $Env:Path
$write = Read-Host 'Set PATH permanently ? (yes|no)'
if ($write -eq "yes")
{
[Environment]::SetEnvironmentVariable("Path",$env:Path, [System.EnvironmentVariableTarget]::User)
Write-Output 'PATH updated'
}
}
You can add this function to your default profile, (Microsoft.PowerShell_profile.ps1
), usually located at %USERPROFILE%\Documents\WindowsPowerShell
.
File -> Export -> Web -> WAR file
OR in Kepler follow as shown below :
If you want to use the REST end point,
$friends = $facebook->api(array('method' => 'friends.get'));
else if you are using the graph api, then use,
$friends = $facebook->api('/me/friends');
I have tried the following command and they work well.
bzip2 -t file.bz2
gunzip -t file.gz
However, we can found these two command are time-consuming. Maybe we need some more quick way to determine the intact of the compress files.
Here is a solution for React (not React Native) using TypeScript.
The same concept can be applied to React Native
import React from 'react';
type Props = {
children: string;
Wrapper?: any;
}
/**
* Automatically break lines for text
*
* Avoids relying on <br /> for every line break
*
* @example
* <Text>
* {`
* First line
*
* Another line, which will respect line break
* `}
* </Text>
* @param props
*/
export const Text: React.FunctionComponent<Props> = (props) => {
const { children, Wrapper = 'div' } = props;
return (
<Wrapper style={{ whiteSpace: 'pre-line' }}>
{children}
</Wrapper>
);
};
export default Text;
Usage:
<Text>
{`
This page uses server side rendering (SSR)
Each page refresh (either SSR or CSR) queries the GraphQL API and displays products below:
`}
</Text>
This is my function -
public function is_assoc_array($array){
if(is_array($array) !== true){
return false;
}else{
$check = json_decode(json_encode($array));
if(is_object($check) === true){
return true;
}else{
return false;
}
}
}
Some examples
print_r((is_assoc_array(['one','two','three']))===true?'Yes':'No'); \\No
print_r(is_assoc_array(['one'=>'one','two'=>'two','three'=>'three'])?'Yes':'No'); \\Yes
print_r(is_assoc_array(['1'=>'one','2'=>'two','3'=>'three'])?'Yes':'No'); \\Yes
print_r(is_assoc_array(['0'=>'one','1'=>'two','2'=>'three'])?'Yes':'No'); \\No
There was a similar solution by @devios1 in one of the answers but this was just another way using the inbuilt json related functions of PHP. I haven't checked how this solution fairs in terms of performance compared to other solutions that have been posted here. But it certainly has helped me solve this problem. Hope this helps.
I faced the same issue and got it working.
I think it is because when you import a project, build target is not set in the project properties which then default to the value used in manifest file. Most likely, you already have installed a later android API with your SDK.
The solution is to enable build target toward your installed API level (but keep the minimum api support as specified in the manifest file). TO do this, in project properties, go to android, and from "Project Build Target", pick a target name.
I don't believe you can accomplish that with css. Originally javascript was designed for this. Try this:
<div class="div1" id="div1">
<div class="div2">
Div2 starts <br /><br /><br /><br /><br /><br /><br />
Div2 ends
</div>
<div class="div3" id="div3">
Div3
</div>
</div>
and javascript function:
function adjustHeight() {
document.getElementById('div3').style.height = document.defaultView.getComputedStyle(document.getElementById('div1'), "").getPropertyValue("height");
}
call the javascript after the div1 (or whole page) is loaded.
You can also replace document.getElementById('div3').style.height with code manipulating class div3 since my code only add / change style attribute of an element.
Hope this helps.
From the composer help create-project
command
The create-project command creates a new project from a given
package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.[version]
You can also specify the version with the package name using = or : as separator.
To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev).
This command works:
composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist
This works with the * notation.
You could be lazy, and wrap it in a lambda
:
my_hash = YAML.load_file('yml')
my_lamb = lambda { |key| my_hash[key.to_s] }
my_lamb[:a] == my_hash['a'] #=> true
But this would only work for reading from the hash - not writing.
To do that, you could use Hash#merge
my_hash = Hash.new { |h,k| h[k] = h[k.to_s] }.merge(YAML.load_file('yml'))
The init block will convert the keys one time on demand, though if you update the value for the string version of the key after accessing the symbol version, the symbol version won't be updated.
irb> x = { 'a' => 1, 'b' => 2 }
#=> {"a"=>1, "b"=>2}
irb> y = Hash.new { |h,k| h[k] = h[k.to_s] }.merge(x)
#=> {"a"=>1, "b"=>2}
irb> y[:a] # the key :a doesn't exist for y, so the init block is called
#=> 1
irb> y
#=> {"a"=>1, :a=>1, "b"=>2}
irb> y[:a] # the key :a now exists for y, so the init block is isn't called
#=> 1
irb> y['a'] = 3
#=> 3
irb> y
#=> {"a"=>3, :a=>1, "b"=>2}
You could also have the init block not update the hash, which would protect you from that kind of error, but you'd still be vulnerable to the opposite - updating the symbol version wouldn't update the string version:
irb> q = { 'c' => 4, 'd' => 5 }
#=> {"c"=>4, "d"=>5}
irb> r = Hash.new { |h,k| h[k.to_s] }.merge(q)
#=> {"c"=>4, "d"=>5}
irb> r[:c] # init block is called
#=> 4
irb> r
#=> {"c"=>4, "d"=>5}
irb> r[:c] # init block is called again, since this key still isn't in r
#=> 4
irb> r[:c] = 7
#=> 7
irb> r
#=> {:c=>7, "c"=>4, "d"=>5}
So the thing to be careful of with these is switching between the two key forms. Stick with one.
i also have same problem and solve it. Please go through the link
add your site to trusted zone and change following options in ie Tools Menu -> Internet Options -> Security -> Custom level -> "Initialize and script ActiveX controls not marked as safe for scripting"
The NUMBER ONE error is having ANYTHING with the reserved word submit
as ID
or NAME
in your form.
If you plan to call .submit()
on the form AND the form has submit
as id or name on any form element, then you need to rename that form element, since the form’s submit method/handler is shadowed by the name/id attribute.
Several other things:
As mentioned, you need to submit the form using a simpler event than the jQuery one
BUT you also need to cancel the clicks on the links
Why, by the way, do you have two buttons? Since you use jQuery to submit the form, you will never know which of the two buttons were clicked unless you set a hidden field on click.
<form action="deletprofil.php" id="form_id" method="post">
<div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
<button type="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
<button type="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
</div>
</form>
$(function(){
$("#NOlink, #OKlink").on("click", function(e) {
e.preventDefault(); // cancel default action
$("#popupDialog").popup('close');
if (this.id=="OKlink") {
document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
}
});
$('#form_id').on('submit', function(e){
e.preventDefault();
$("#popupDialog").popup('open');
});
});
Judging from your comments, I think you really want to do this:
<form action="deletprofil.php" id="form_id" method="post">
<input type="hidden" id="whichdelete" name="whichdelete" value="" />
<div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input">
<button type="button" value="1" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button>
<button type="button" value="2" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button>
</div>
</form>
$(function(){
$("#NOlink, #OKlink").on("click", function(e) {
e.preventDefault(); // cancel default action
$("#popupDialog").popup('close');
if (this.id=="OKlink") {
// trigger the submit event, not the event handler
document.getElementById("form_id").submit(); // or $("#form_id")[0].submit();
}
});
$(".delete").on("click", function(e) {
$("#whichdelete").val(this.value);
});
$('#form_id').on('submit', function(e){
e.preventDefault();
$("#popupDialog").popup('open');
});
});
ubuntu and php7.1
sudo apt install php7.1-bcmath
ubuntu and php without version specification
sudo apt install php-bcmath
Basically there's a program to accomplish that, called "mail". The subject of the email can be specified with a -s and a list of address with -t. You can write the text on your own with the echo command:
echo "This will go into the body of the mail." | mail -s "Hello world" [email protected]
or get it from other files too:
mail -s "Hello world" [email protected] < /home/calvin/application.log
mail doesn't support the sending of attachments, but Mutt does:
echo "Sending an attachment." | mutt -a file.zip -s "attachment" [email protected]
Note that Mutt's much more complete than mail. You can find better explanation here
PS: thanks to @slhck who pointed out that my previous answer was awful. ;)
There is some progress for Visual studio 2013 developers :-D woot woot! See blog post Visual Studio Installer Projects Extension.
Link and information were retrieved from Brian Harry's blog post Creating installers with Visual Studio.
There is no way to retrieve localStorage, sessionStorage or cookie values via javascript in the browser after they've been deleted via javascript.
If what you're really asking is if there is some other way (from outside the browser) to recover that data, that's a different question and the answer will entirely depend upon the specific browser and how it implements the storage of each of those types of data.
For example, Firefox stores cookies as individual files. When a cookie is deleted, its file is deleted. That means that the cookie can no longer be accessed via the browser. But, we know that from outside the browser, using system tools, the contents of deleted files can sometimes be retrieved.
If you wanted to look into this further, you'd have to discover how each browser stores each data type on each platform of interest and then explore if that type of storage has any recovery strategy.
use tar to split into multiple archives
there are plenty of programs that will work with tar files on windows, including cygwin.
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
return float32(in)
}
// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
return float64(in)
}
Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference
dialog.
Be sure that the new reference has the Copy Local = True
.
The Add Reference
dialog could be opened right-clicking on the References item in your project in Solution Explorer
UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)
You should use django methods, like exists. Its there for you to use it.
if qs.exists():
return qs[0]
return None
I know this is kind of late but this plugin should work. http://remysharp.com/2009/01/26/element-in-view-event-plugin/
$('p.inview').bind('inview', function (event, visible) {
if (visible) {
$(this).text('You can see me!');
} else {
$(this).text('Hidden again');
}
I'm using this localization method and added a route parameter that sets the culture and language whenever a user visits example.com/xx-xx/
Example:
routes.MapRoute("DefaultLocalized",
"{language}-{culture}/{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = "",
language = "nl",
culture = "NL"
});
I have a filter that does the actual culture/language setting:
using System.Globalization;
using System.Threading;
using System.Web.Mvc;
public class InternationalizationAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
string language = (string)filterContext.RouteData.Values["language"] ?? "nl";
string culture = (string)filterContext.RouteData.Values["culture"] ?? "NL";
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
}
}
To activate the Internationalization attribute, simply add it to your class:
[Internationalization]
public class HomeController : Controller {
...
Now whenever a visitor goes to http://example.com/de-DE/Home/Index the German site is displayed.
I hope this answers points you in the right direction.
I also made a small MVC 5 example project which you can find here
Just go to http://{yourhost}:{port}/en-us/home/index to see the current date in English (US), or change it to http://{yourhost}:{port}/de-de/home/index for German etcetera.
Do everything suggested by ziesemer.
You may also want to :
If you have some methods which are not synchronized and are accessing and changing the instance variables. In your example:
private int a;
private int b;
any number of threads can access these non synchronized methods at the same time when other thread is in the synchronized method of the same object and can make changes to instance variables. For e.g :-
public void changeState() {
a++;
b++;
}
You need to avoid the scenario that non synchronized methods are accessing the instance variables and changing it otherwise there is no point of using synchronized methods.
In the below scenario:-
class X {
private int a;
private int b;
public synchronized void addA(){
a++;
}
public synchronized void addB(){
b++;
}
public void changeState() {
a++;
b++;
}
}
Only one of the threads can be either in addA or addB method but at the same time any number of threads can enter changeState method. No two threads can enter addA and addB at same time(because of Object level locking) but at same time any number of threads can enter changeState.
slaveOk does not work anymore. One needs to use readPreference https://docs.mongodb.com/v3.0/reference/read-preference/#primaryPreferred
e.g.
const client = new MongoClient(mongoURL + "?readPreference=primaryPreferred", { useUnifiedTopology: true, useNewUrlParser: true });
Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.
Slug can create using SlugField
Ex:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
If you want to use title as slug, django has a simple function called slugify
from django.template.defaultfilters import slugify
class Article(models.Model):
title = models.CharField(max_length=100)
def slug(self):
return slugify(self.title)
If it needs uniqueness, add unique=True
in slug field.
for instance, from the previous example:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug
Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.
com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );
That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.
An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.
It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe
and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.
this function worked for me
<?php
function everything_in_tags($string, $tagname)
{
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match($pattern, $string, $matches);
return $matches[1];
}
?>