In my application,above javascript function didnt work,because i had many procrosses inside one page.so following code worked for me hope it helps you guys.
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
the difference is that max-device-width is all screen's width and max-width means the space used by the browser to show the pages. But another important difference is the support of android browsers, in fact if u're going to use max-device-width this will work only in Opera, instead I'm sure that max-width will work for every kind of mobile browser (I had test it in Chrome, firefox and opera for ANDROID).
You'll get the best performance if you forget the where clause and place all conditions in the ON expression.
I think this is because the query first has to join the tables then runs the where clause on that, so if you can reduce what is required to join then that's the fasted way to get the results/do the udpate.
You have a table of users. They can log in using their username or email or account_number. These accounts can be active (1) or inactive (0). This table has 50000 rows
You then have a table of users to disable at one go because you find out they've all done something bad. This table however, has one column with usernames, emails and account numbers mixed. It also has a "has_run" indicator which needs to be set to 1 (true) when it has been run
UPDATE users User
INNER JOIN
blacklist_users BlacklistUser
ON
(
User.username = BlacklistUser.account_ref
OR
User.email = BlacklistedUser.account_ref
OR
User.phone_number = BlacklistUser.account_ref
AND
User.is_active = 1
AND
BlacklistUser.has_run = 0
)
SET
User.is_active = 0,
BlacklistUser.has_run = 1;
If we had to join on just the OR conditions it would essentially need to check each row 4 times to see if it should join, and potentially return a lot more rows. However, by giving it more conditions it can "skip" a lot of rows if they don't meet all the conditions when joining.
It's more readable. All the conditions are in one place and the rows to update are in one place
You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"
where $val
is the data which is troubling you.
You can compare an array like the below mentioned if the array has some values
it('should check if the array are equal', function() {
var mockArr = [1, 2, 3];
expect(mockArr ).toEqual([1, 2, 3]);
});
But if the array that is returned from some function has more than 1 elements and all are zero then verify by using
expect(mockArray[0]).toBe(0);
Another tool you can use is registry-cli. For example, this command:
registry.py -l "login:password" -r https://your-registry.example.com --delete
will delete all but the last 10 images.
As all of these comments are true, you should note that as far as ICANN approved Arabic (Persian) and Chinese characters to be registered as Domain Name, all of the browser-making companies (Microsoft, Mozilla, Apple, etc.) have to support Unicode in URLs without any encoding, and those should be searchable by Google, etc.
So this issue will resolve ASAP.
I was having trouble sending plain text and found that I needed to surround the body's value with double quotes:
const request = axios.put(url, "\"" + values.guid + "\"", {
headers: {
"Accept": "application/json",
"Content-type": "application/json",
"Authorization": "Bearer " + sessionStorage.getItem('jwt')
}
})
My webapi server method signature is this:
public IActionResult UpdateModelGuid([FromRoute] string guid, [FromBody] string newGuid)
It's cleaner/safer to use the getters provided by google instead of accessing the properties like some did
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
var coordinatesArray = polygon.overlay.getPath().getArray();
});
You can simply use the #define
directive as follows:
#define TRUE 1
#define FALSE 0
#define NOT(arg) (arg == TRUE)? FALSE : TRUE
typedef int bool;
And use as follows:
bool isVisible = FALSE;
bool isWorking = TRUE;
isVisible = NOT(isVisible);
and so on
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
HEAD
is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.
master
is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).
origin
is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.
I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:
copyFactory = (() ->
resource = ->
resource.__super__.constructor.apply this, arguments
return
this.extendTo resource
resource
).call(factory)
You can use the --system-site-packages
and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.
A char
is an integral type. When you write
char ch = 'A';
you're setting the value of ch
to whatever number your compiler uses to represent the character 'A'
. That's usually the ASCII code for 'A'
these days, but that's not required. You're almost certainly using a system that uses ASCII.
Like any numeric type, you can initialize it with an ordinary number:
char ch = 13;
If you want do do arithmetic on a char
value, just do it: ch = ch + 1;
etc.
However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char
values as characters rather than numbers. There are a couple of ways to do that.
std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
Why don't you use spring's TransactionTemplate
to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional
method, but given that it's a test I would opt for programmatic control of your transactions.
Also note that the @Transactional
annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!
@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {
@Autowired
PlatformTransactionManager platformTransactionManager;
TransactionTemplate transactionTemplate;
@Before
public void setUp() throws Exception {
transactionTemplate = new TransactionTemplate(platformTransactionManager);
}
@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {
final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
@Override
public Contract doInTransaction(TransactionStatus status) {
Contract c = contractDOD.getNewTransientContract(15);
contractRepository.save(c);
return c;
}
});
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; ++i) {
executorService.execute(new Runnable() {
@Override //note that there is no @Transactional configured for the method
public void run() {
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// do whatever you want to do with c1
return null;
}
});
}
});
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// validate test results in transaction
return null;
}
});
}
}
Project -> Clean
can at least sometimes be sufficient to resolve the matter.
They are ASCII dec codes. A full table can be found here.
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json")
fixed the problem
also mimetype is important.
With the positive lookbehind technique:
(?<=\?).*
(We're searching for a text preceded by a question mark here)
Input: derpderp?mystring blahbeh
Output: mystring blahbeh
Basically the ?<=
is a group construct, that requires the escaped question-mark, before any match can be made.
They perform really well, but not all implementations support them.
In addition to Boaz's answer ....
@UniqueConstraint
allows you to name the constraint, while @Column(unique = true)
generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq
).
Sometimes it can be helpful to know what table a constraint is associated with. E.g.:
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(
columnNames = {"mask", "group"},
name="uk_product_serial_group_mask"
)
}
)
Okay, here is a solution to reduce the physical size of the transaction file, but without changing the recovery mode to simple.
Within your database, locate the file_id of the log file using the following query.
SELECT * FROM sys.database_files;
In my instance, the log file is file_id 2. Now we want to locate the virtual logs in use, and do this with the following command.
DBCC LOGINFO;
Here you can see if any virtual logs are in use by seeing if the status is 2 (in use), or 0 (free). When shrinking files, empty virtual logs are physically removed starting at the end of the file until it hits the first used status. This is why shrinking a transaction log file sometimes shrinks it part way but does not remove all free virtual logs.
If you notice a status 2's that occur after 0's, this is blocking the shrink from fully shrinking the file. To get around this do another transaction log backup, and immediately run these commands, supplying the file_id found above, and the size you would like your log file to be reduced to.
-- DBCC SHRINKFILE (file_id, LogSize_MB)
DBCC SHRINKFILE (2, 100);
DBCC LOGINFO;
This will then show the virtual log file allocation, and hopefully you'll notice that it's been reduced somewhat. Because virtual log files are not always allocated in order, you may have to backup the transaction log a couple of times and run this last query again; but I can normally shrink it down within a backup or two.
According to java,
Data Type - Default values
byte - 0
short - 0
int - 0
long - 0L
float - 0.0f
double - 0.0d
char - '\u0000'
String (or any object) - null
boolean - false
Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.
Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer>
if you need to.
TCharIntHashMap: An open addressed Map implementation for char keys and int values.
import numpy as np
import threading
def threaded_process(items_chunk):
""" Your main process which runs in thread for each chunk"""
for item in items_chunk:
try:
api.my_operation(item)
except Exception:
print('error with item')
n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
thread_list.append(thread)
thread_list[thr].start()
for thread in thread_list:
thread.join()
You can also use:
stringTest.All(char.IsDigit);
It will return true
for all Numeric Digits (not float
) and false
if input string is any sort of alphanumeric.
Please note: stringTest
should not be an empty string as this would pass the test of being numeric.
Response.write()
is used to display the normal text and Response.output.write()
is used to display the formated text.
You were close. You can do:
var element = $("#parentDiv").find(".myClassNameOfInterest");
.find()
- http://api.jquery.com/findAlternatively, you can do:
var element = $(".myClassNameOfInterest", "#parentDiv");
...which sets the context of the jQuery object to the #parentDiv
.
EDIT:
Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest
instead of just .myClassNameOfInterest
.
I used the code of this link http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html
But in browser detection I used:
if (navigator.userAgent.indexOf('MSIE') > -1) {
//Your placeholder support code here...
}
The W3C solution:
var len = document.getElementById("input1").length;
I got the same error when trying to compile a Go package on Debian 9.8:
# pkg-config --cflags -- libssl libcrypto
Package libssl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libssl.pc'
The thing is that pkg-config
searches for package meta-information in .pc
files. Such files come from the dev package. So, even though I had libssl
installed, I still got the error. It was resolved by running:
sudo apt-get install libssl-dev
The first push should be a:
git push -u origin branchname
That would make sure:
origin
',simple
'Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.
The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page.
None of the video settings posted above worked in modern browsers I tested (like Firefox) using the embed
or object
elements in HTML5. For video
or audio
elements they did stop autoplay. For embed
and object
they did not.
I tested this using the embed
and object
elements using several different media types as well as HTML attributes (like autostart and autoplay). These videos always played regardless of any combination of settings in several browsers. Again, this was not an issue using the newer HTML5 video
or audio
elements, just when using embed
and object
.
It turns out the new browser settings for video "autoplay" have changed. Firefox will now ignore the autoplay
attributes on these tags and play videos anyway unless you explicitly set to "block audio and video" autoplay in your browser settings.
To do this in Firefox I have posted the settings below:
Your videos will NOT autoplay now when displaying videos in web pages using object
or embed
elements.
You have to use the plugin manager of Notepad++ and search for the JSON plugin. There you can easily install it.
This answer explains it pretty good: How to reformat JSON in Notepad++?
This might be useful for someone who is looking for a different answer. Go to the Gradle Panel and select your module -> Task -> Verification -> Check. This will check the project for errors and will print the log where the error occurs. Most of the time this Kind of error must be a typo present in your XML file of your project
To get the form that the submit is inside why not just
this.form
Easiest & quickest path to the result.
A way to edit the .zshrc file without doing it through iTerm2 or native Terminal on macOS is to use a terminal in another application. For example, I used the terminal as part of VSCode and was able to find and edit the file.
For just a boolean match result or for a count of occurrences, you could use:
use 5.014; use strict; use warnings;
my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
my $patterns=join(',',@foo);
for my $str (qw(quux world hello hEllO)) {
my $count=map {m/^$str$/i} @foo;
if ($count) {
print "I found '$str' $count time(s) in '$patterns'\n";
} else {
print "I could not find '$str' in the pattern list\n"
};
}
Output:
I could not find 'quux' in the pattern list
I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
Does not require to use a module.
Of course it's less "expandable" and versatile as some code above.
I use this for interactive user answers to match against a predefined set of case unsensitive answers.
class A {
int i;
// Hashing Algorithm
if even number return 0 else return 1
// Equals Algorithm,
if i = this.i return true else false
}
hashCode()
to determine the
bucket and uses equals()
method to find whether the value is already
present in the Bucket. If not it will added else it will be replaced with current valuehashCode()
to find the Entry (bucket) first and
equals()
to find the value in Entryif Both are overridden,
Map<A>
Map.Entry 1 --> 1,3,5,...
Map.Entry 2 --> 2,4,6,...
if equals is not overridden
Map<A>
Map.Entry 1 --> 1,3,5,...,1,3,5,... // Duplicate values as equals not overridden
Map.Entry 2 --> 2,4,6,...,2,4,..
If hashCode is not overridden
Map<A>
Map.Entry 1 --> 1
Map.Entry 2 --> 2
Map.Entry 3 --> 3
Map.Entry 4 --> 1
Map.Entry 5 --> 2
Map.Entry 6 --> 3 // Same values are Stored in different hasCodes violates Contract 1
So on...
HashCode Equal Contract
What worked for me on Windows was (I had cloned code from a repo 1st):
eval $(ssh-agent)
ssh-add
git pull
at which time it asked me one last time for my passphrase
Credits: the solution was taken from https://unix.stackexchange.com/questions/12195/how-to-avoid-being-asked-passphrase-each-time-i-push-to-bitbucket
Json.NET does this...
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }
More examples: Serializing Collections with Json.NET
The !==
opererator tests whether values are not equal or not the same type.
i.e.
var x = 5;
var y = '5';
var 1 = y !== x; // true
var 2 = y != x; // false
Guid.NewGuid() will create one
Here is another one for converting CSV to ArrayList:
String str="string,with,comma";
ArrayList aList= new ArrayList(Arrays.asList(str.split(",")));
for(int i=0;i<aList.size();i++)
{
System.out.println(" -->"+aList.get(i));
}
Prints you
-->string
-->with
-->comma
You can use split function.
SELECT
(select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
(select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
(select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
(select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
FROM MyTbl
dictionary['key'] = dictionary.get('key', []) + list_to_append
Adding a reference to Sysem.Web.Dll did it for me.
Bootstrap 3
Yes, it's possible. This "off-canvas" example should help to get you started.
https://codeply.com/p/esYgHWB2zJ
Basically you need to wrap the layout in an outer div, and use media queries to toggle the layout on smaller screens.
/* collapsed sidebar styles */
@media screen and (max-width: 767px) {
.row-offcanvas {
position: relative;
-webkit-transition: all 0.25s ease-out;
-moz-transition: all 0.25s ease-out;
transition: all 0.25s ease-out;
}
.row-offcanvas-right
.sidebar-offcanvas {
right: -41.6%;
}
.row-offcanvas-left
.sidebar-offcanvas {
left: -41.6%;
}
.row-offcanvas-right.active {
right: 41.6%;
}
.row-offcanvas-left.active {
left: 41.6%;
}
.sidebar-offcanvas {
position: absolute;
top: 0;
width: 41.6%;
}
#sidebar {
padding-top:0;
}
}
Also, there are several more Bootstrap sidebar examples here
Bootstrap 4
The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.
This will cause the cursor to go to the start of the line after $2.
Use dos2unix or vi with :se ff=unix
to get rid of the CRs.
I think you have to do mydb.commit()
all the insert into.
Something like this
import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='mydb')
cursor = mydb.cursor()
csv_data = csv.reader(file('students.csv'))
for row in csv_data:
cursor.execute('INSERT INTO testcsv(names, \
classes, mark )' \
'VALUES("%s", "%s", "%s")',
row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.
1: @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)
will both produce
<input id="Name" name="Name" type="text" />
So what does that mean in terms of use?
Generally two things:
TextBoxFor
will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'TextBoxFor
version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.
Does your HOSTS file have an entry for localhost
? Some other situations this error is seen in seem to have this as a problem resolution.
Make sure you have 127.0.0.1 localhost
set in it...
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
Try using:
test -x filename
or
[ -x filename ]
From the Bash manpage under Conditional Expressions:
-x file True if file exists and is executable.
Here's a better option:
git remote set-head -a origin
From the documentation:
With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.
This has actually been around quite a while (since v1.6.3); not sure how I missed it!
When Python2.x sees a == b
, it tries the following.
type(b)
is a new-style class, and type(b)
is a subclass of type(a)
, and type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.type(a)
has overridden __eq__
(that is, type(a).__eq__
isn't object.__eq__
), then the result is a.__eq__(b)
.type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.__cmp__
. If it exists, the objects are equal iff it returns zero
.object.__eq__(a, b)
, which is True
iff a
and b
are the same object.If any of the special methods return NotImplemented
, Python acts as though the method didn't exist.
Note that last step carefully: if neither a
nor b
overloads ==
, then a == b
is the same as a is b
.
in a single line:
FOR /F "tokens=*" %%g IN ('*your command*') do (SET VAR=%%g)
the command output will be set in %g then in VAR.
More informations: https://ss64.com/nt/for_cmd.html
Just for reference, if you are using:
$(el).offset().top
To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:
$(el).offset({top: pos});
As opposed to the CSS methods above.
We can create a class to have multiple keys or values and the object of this class can be used as a parameter in map. You can refer to https://stackoverflow.com/a/44181931/8065321
The following complete example will read an existing server.xml
file from the current directory, append a new Server and re-write the file to server.xml
. It does not work without an existing .xml file, so you will need to modify the code to handle that case.
import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class AddXmlNode {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("server.xml");
Element root = document.getDocumentElement();
Collection<Server> servers = new ArrayList<Server>();
servers.add(new Server());
for (Server server : servers) {
// server elements
Element newServer = document.createElement("server");
Element name = document.createElement("name");
name.appendChild(document.createTextNode(server.getName()));
newServer.appendChild(name);
Element port = document.createElement("port");
port.appendChild(document.createTextNode(Integer.toString(server.getPort())));
newServer.appendChild(port);
root.appendChild(newServer);
}
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult("server.xml");
transformer.transform(source, result);
}
public static class Server {
public String getName() { return "foo"; }
public Integer getPort() { return 12345; }
}
}
Example server.xml file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Servers>
<server>
<name>something</name>
<port>port</port>
</server>
</Servers>
The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml
and then just appends a new Server element and re-writes the file.
I figured out mistake here use double quotations instead of single quotations.
change this
git commit -m 'initial commit'
to
git commit -m "initial commit"
It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore
file:
# intellij configs
.idea/
I know this post is old, but I found that this really works well:
window.onunload = function() {
window.opener.location.href = window.opener.location.href;
};
The window.onunload
part was the hint I found googling this page. Thanks, @jerjer!
Append a line "http_code:200" at the end, and then grep for the keyword "http_code:" and extract the response code.
result=$(curl -w "\nhttp_code:%{http_code}" http://localhost)
echo "result: ${result}" #the curl result with "http_code:" at the end
http_code=$(echo "${result}" | grep 'http_code:' | sed 's/http_code://g')
echo "HTTP_CODE: ${http_code}" #the http response code
In this case, you can still use the non-silent mode / verbose mode to get more information about the request such as the curl response body.
Apparently it's possible to do this in jQuery:
$("#tabs").css("cssText", "height: 650px !important;");
On GNU-compatible systems (i.e. Linux):
find . -mtime 0 -printf '%T+\t%s\t%p\n' 2>/dev/null | sort -r | more
This will list files and directories that have been modified in the last 24 hours (-mtime 0
). It will list them with the last modified time in a format that is both sortable and human-readable (%T+
), followed by the file size (%s
), followed by the full filename (%p
), each separated by tabs (\t
).
2>/dev/null
throws away any stderr output, so that error messages don't muddy the waters; sort -r
sorts the results by most recently modified first; and | more
lists one page of results at a time.
$url= 'https://example.com';
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents($url, false, stream_context_create($arrContextOptions));
This will allow you to get the content from the url whether it is a HTTPS
I just had the same problem, but none of these answers helped me. I did find the dll on my pc in the location Mostey noted: (C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll
), but this is not the one that was referenced in the project I was trying to get building.
The reference in our project in Visual Studio 2012 was pointing to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\
. This location was empty for me, but it worked fine for everyone else. It took a number of tries, but I finally tracked down a working installer. I hope this saves others the same hassle!
--> Office Tools Bundle installer for VS2012 <--
This was located on the Office Documentation and Download page. Scroll down to Tools Downloads. There's also currently one for VS2013.
In some cases you may need to move the focus to the next field manually :
focusSearch(FOCUS_DOWN).requestFocus();
You might need this if, for example, you have a text field that opens a date picker on click, and you want the focus to automatically move to the next input field once a date is selected by the user and the picker closes. There's no way to handle this in XML, it has to be done programmatically.
Found amazing simple solution - working for Chrome (Windows, not tested on Mac)
Zebra ZP 450
Review the pom.xml
file inside of target/checkout/
. Chances are, the pom.xml
in your trunk or master branch does not have the distributionManagement
tag.
I was getting the same error, and it was due to the type I was trying to deserialize not having a default parameterless constructor. I added a constructor, and it started working.
I had the same problem, and none of the above solutions worked. Actually, the file include/boost/version.hpp
could not be read (by the cmake script launched by jenkins).
I had to manually change the permission of the (boost) library (even though jenkins belongs to the group, but that is another problem linked to jenkins that I could not figure out):
chmod o+wx ${BOOST_ROOT} -R # allow reading/execution on the whole library
#chmod g+wx ${BOOST_ROOT} -R # this did not suffice, strangely, but it is another story I guess
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
I have seen this once. Are the users requesting different amounts of data? I found that even if you can configure a binding for data payloads (i.e. maxReceivedMessageSize
), the httpRuntime
maxRequestLength
trumps the WCF setting, so if IIS is trying to serve a request that exceeds that, it exhibits this behavior.
Think of it like this:
If maxReceivedMessageSize
is 12MB in your WCF behavior, and maxRequestLength
is 4MB (default), IIS wins.
You can also use this command to delete the keys:-
Suppose there are many types of keys in your redis like-
Ex- 'xyz_category_fpc' here xyz is a sitename, and these keys are related to products and categories of a E-Commerce site and generated by FPC.
If you use this command as below-
redis-cli --scan --pattern 'key*' | xargs redis-cli del
OR
redis-cli --scan --pattern 'xyz_category_fpc*' | xargs redis-cli del
It deletes all the keys like 'xyz_category_fpc' (delete 1, 2 and 3 keys). For delete other 4, 5 and 6 number keys use 'xyz_product_fpc' in above command.
If you want to Delete Everything in Redis, then follow these Commands-
With redis-cli:
For Example:- in your shell:
redis-cli flushall
redis-cli flushdb
import java.util.ArrayList;
import java.util.List;
class ArrLst{
public static void main(String args[]){
List l=new ArrayList();
l.add(10);
l.add(11);
l.add(12);
l.add(13);
l.add(14);
l.forEach((a)->System.out.println(a));
}
}
Possibly your most versatile approach is to select a templating system.
If I understand your question correctly, you're asking if you can call multiple constructors in C++?
If that's what you're looking for, then no - that is not possible.
You certainly can have multiple constructors, each with unique argument signatures, and then call the one you want when you instantiate a new object.
You can even have one constructor with defaulted arguments on the end.
But you may not have multiple constructors, and then call each of them separately.
&>out time command >/dev/null
in your case
&>out time sleep 1 >/dev/null
then
cat out
By default Maven uses the following naming conventions when looking for tests to run:
Test*
*Test
*Tests
(has been added in Maven Surefire Plugin 2.20)*TestCase
If your test class doesn't follow these conventions you should rename it or configure Maven Surefire Plugin to use another pattern for test classes.
I was having this same problem too, I while multiple canvas elements with position:absolute does the job, if you want to save the output into an image, that's not going to work.
So I went ahead and did a simple layering "system" to code as if each layer had its own code, but it all gets rendered into the same element.
https://github.com/federicojacobi/layeredCanvas
I intend to add extra capabilities, but for now it will do.
You can do multiple functions and call them in order to "fake" layers.
Just for newcomers.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Be careful if you're using a theme or something, they'll often declare img max-width at 100%. You got to make none. Test it out :)
https://jsfiddle.net/o63u8sh4/
<p>Original:</p>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
<p>Wrapped:</p>
<div>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
</div>
div{
width:150px;
height:100px;
position:relative;
overflow:hidden;
}
div img{
min-width:100%;
min-height:100%;
height:auto;
position:relative;
top:50%;
left:50%;
transform:translateY(-50%) translateX(-50%);
}
The names of the first dataframe do not match the names of the second one. Just as the error message says.
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE
If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:
> names(xd.small[[1]]) <- names(xd.small[[2]])
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE
Then things should proceed happily.
In Rails I am using this gem : https://github.com/merchii/rack-iframe Bawically it sets a set of abbreviations without a reference file: https://github.com/merchii/rack-iframe/blob/master/lib/rack/iframe.rb#L8
It is easy to install when you dont care at all about the meaning of the p3p stuff.
@Temporal
is a JPA annotation which can be used to store in the database table on of the following column items:
java.sql.Date
)java.sql.Time
)java.sql.Timestamp
)Generally when we declare a Date
field in the class and try to store it.
It will store as TIMESTAMP in the database.
@Temporal
private Date joinedDate;
Above code will store value looks like 08-07-17 04:33:35.870000000 PM
If we want to store only the DATE in the database,
We can use/define TemporalType
.
@Temporal(TemporalType.DATE)
private Date joinedDate;
This time, it would store 08-07-17 in database
There are some other attributes as well as @Temporal
which can be used based on the requirement.
For a line-by-line delta measurement, try gnonom.
It is a command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.
Piping anything to gnomon will prepend a timestamp to each line, indicating how long that line was the last line in the buffer--that is, how long it took the next line to appear. By default, gnomon will display the seconds elapsed between each line, but that is configurable.
This is how you would drop the constraint
ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO
With a script
-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)
set @database = 'dotnetnuke'
set @table = 'tabs'
DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
select @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = @database and
table_name = @table
exec sp_executesql @sql
END
Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
Right click on project >> Click on properties >> Java Build Path >> Source >> Add Folder
If your block is originally positioned as static, you may want to try this
$(window).on('scroll', function () {_x000D_
_x000D_
var $w = $(window);_x000D_
$('.position-fixed-x').css('left', $w.scrollLeft());_x000D_
$('.position-fixed-y').css('top', $w.scrollTop());_x000D_
_x000D_
});
_x000D_
.container {_x000D_
width: 1000px;_x000D_
}_x000D_
_x000D_
.position-fixed-x {_x000D_
position: relative; _x000D_
}_x000D_
_x000D_
.position-fixed-y {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.blue-box {_x000D_
background:blue;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
}_x000D_
_x000D_
.red-box {_x000D_
background: red;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
_x000D_
<div class="position-fixed-y red-box">_x000D_
_x000D_
</div>_x000D_
_x000D_
The pattern of base pairs in the DNA double helix encodes the instructions for building the proteins necessary to construct an entire organism. DNA, or deoxyribonucleic acid, is found within most cells of an organism, and most organisms have their own unique DNA code. One exception to this is cloned organisms, which have the same exact DNA code as their parents do._x000D_
_x000D_
<div class="position-fixed-x blue-box">_x000D_
_x000D_
</div>_x000D_
_x000D_
DNA strands are composed of millions of sub-units, called nucleotides. Each nucleotide contains a 5-carbon sugar, a phosphate group and a nitrogen base. There are four different variations of the nitrogen base group, responsible for all of the variation between two different DNA strands. The four different variations are called adenine, guanine, cytosine and thymine, but they are typically abbreviated and only referred to by their first letter. The sequence of these different nitrogen bases makes up the code of the DNA._x000D_
_x000D_
The DNA strand splits in two, and forms two different DNA strands during cell replication. However, sometimes this process is not perfect, and mistakes occur. These mistakes may change the way an organism is constructed or functions. When this happens, it is called a mutation. These mutations can be helpful or harmful, and they are usually passed on to the organism’s offspring._x000D_
_x000D_
The traits of a living thing depend on the complex mixture of interacting components inside it. Proteins do much of the chemical work inside cells, so they largely determine what those traits are. But those proteins owe their existence to the DNA (deoxyribonucleic acid), so that is where we must look for the answer._x000D_
The easiest way to understand how DNA is organized is to start with its basic building blocks. DNA consists of four different sugars that interact with each other in specific ways. These four sugars are called nucleotide bases and have the names adenine (A), thymine (T), cytosine (C) and guanine (G). Think of these four bases as letters in an alphabet, the alphabet of life!_x000D_
If we hook up these nucleotides into a sequence--for example, GATCATCCG--we now have a little piece of DNA, or a very short word. A much longer piece of DNA can therefore be the equivalent of different words connected to make a sentence, or gene, that describes how to build a protein. And a still longer piece of DNA could contain information about when that protein should be made. All the DNA in a cell gives us enough words and sentences to serve as a master description or blueprint for a human (or an animal, a plant, or a microorganism)._x000D_
Of course, the details are a little more complicated than that! In practice, active stretches of DNA must be copied as a similar message molecule called RNA. The words in the RNA then need to be "read" to produce the proteins, which are themselves stretches of words made up of a different alphabet, the amino acid alphabet. Nobel laureates Linus Pauling, who discerned the structure of proteins, and James Watson and Francis Crick, who later deciphered the helical structure of DNA, helped us to understand this "Central Dogma" of heredity--that the DNA code turns into an RNA message that has the ability to organize 20 amino acids into a complex protein: DNA -> RNA -> Protein._x000D_
To understand how this all comes together, consider the trait for blue eyes. DNA for a blue-eyes gene is copied as a blue-eyes RNA message. That message is then translated into the blue protein pigments found in the cells of the eye. For every trait we have--eye color, skin color and so on--there is a gene or group of genes that controls the trait by producing first the message and then the protein. Sperm cells and eggs cells are specialized to carry DNA in such a way that, at fertilization, a new individual with traits from both its mother and father is created._x000D_
</div>
_x000D_
You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees
, for example.
index.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
var data = {
"start": {
"count": "5",
"title": "start",
"priorities": [{
"txt": "Work"
}, {
"txt": "Time Sense"
}, {
"txt": "Dicipline"
}, {
"txt": "Confidence"
}, {
"txt": "CrossFunctional"
}]
}
}
The formula for German Excel:
=KLEIN(
VERKETTEN(
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;8));8);"-";
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;4));4);"-";"4";
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;3));3);"-";
DEZINHEX(ZUFALLSBEREICH(8;11));
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;3));3);"-";
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;8));8);
DEZINHEX(ZUFALLSBEREICH(0;POTENZ(16;4));
)
)
use it
ApplicationContext context = new FileSystemXmlApplicationContext("Beans.xml");
That example is pretty vague, but maybe something like this?
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]
It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)
For any type of list, you could do this (using the +
operator on all items no matter what their type is):
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]
This makes use of the reduce
function with a lambda
function that basically adds the items together using the +
operator.
Set your PRIMARY KEY as AUTO_INCREMENT.
Yes, a class can implement multiple interfaces. Each interface provides contract for some sort of behavior. I am attaching a detailed class diagram and shell interfaces and classes.
public interface Mammal {
void move();
boolean possessIntelligence();
}
public interface Animal extends Mammal {
void liveInJungle();
}
public interface Human extends Mammal, TwoLeggedMammal, Omnivore, Hunter {
void liveInCivilization();
}
public interface Carnivore {
void eatMeat();
}
public interface Herbivore {
void eatPlant();
}
public interface Omnivore extends Carnivore, Herbivore {
void eatBothMeatAndPlant();
}
public interface FourLeggedMammal {
void moveWithFourLegs();
}
public interface TwoLeggedMammal {
void moveWithTwoLegs();
}
public interface Hunter {
void huntForFood();
}
public class Kangaroo implements Animal, Herbivore, TwoLeggedMammal {
@Override
public void liveInJungle() {
System.out.println("I live in Outback country");
}
@Override
public void move() {
moveWithTwoLegs();
}
@Override
public void moveWithTwoLegs() {
System.out.println("I like to jump");
}
@Override
public void eat() {
eatPlant();
}
@Override
public void eatPlant() {
System.out.println("I like this grass");
}
@Override
public boolean possessIntelligence() {
return false;
}
}
public class Lion implements Animal, FourLeggedMammal, Hunter, Carnivore {
@Override
public void liveInJungle() {
System.out.println("I am king of the jungle!");
}
@Override
public void move() {
moveWithFourLegs();
}
@Override
public void moveWithFourLegs() {
System.out.println("I like to run sometimes.");
}
@Override
public void eat() {
eatMeat();
}
@Override
public void eatMeat() {
System.out.println("I like deer meat");
}
@Override
public boolean possessIntelligence() {
return false;
}
@Override
public void huntForFood() {
System.out.println("My females hunt often");
}
}
public class Teacher implements Human {
@Override
public void liveInCivilization() {
System.out.println("I live in an apartment");
}
@Override
public void moveWithTwoLegs() {
System.out.println("I wear shoes and walk with two legs one in front of the other");
}
@Override
public void move() {
moveWithTwoLegs();
}
@Override
public boolean possessIntelligence() {
return true;
}
@Override
public void huntForFood() {
System.out.println("My ancestors used to but now I mostly rely on cattle");
}
@Override
public void eat() {
eatBothMeatAndPlant();
}
@Override
public void eatBothMeatAndPlant() {
eatPlant();
eatMeat();
}
@Override
public void eatMeat() {
System.out.println("I like this bacon");
}
@Override
public void eatPlant() {
System.out.println("I like this broccoli");
}
}
You can see the Simulator console window, including Safari Web Inspector and all the Web Development Tools by using the Safari Technology Preview app. Open your page in Safari on the Simulator and then go to Safari Technology Preview > Develop > Simulator.
For Rails 3.x and up:
#{request.protocol}#{request.host_with_port}#{request.fullpath}
For Rails 3.2 and up:
request.original_url
Because in rails 3.2 and up:
request.original_url = request.base_url + request.original_fullpath
For more info, plese visit http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url
Another way is to use a website thumbnail/link preview service LinkPeek (even happens to show a screenshot of StackOverflow as a demo right now), URL2PNG, Browshot, Websnapr, or an alternative.
The windows equivalent to a cron job is a scheduled task.
A scheduled task can be created as described by Alex and Rudu, but it can also be done command line with schtasks
(if you for instance need to script it or add it to version control).
An example:
schtasks /create /tn calculate /tr calc /sc weekly /d MON /st 06:05 /ru "System"
Creates the task calculate, which starts the calculator(calc) every monday at 6:05 (should you ever need that.)
All available commands can be found here: http://technet.microsoft.com/en-us/library/cc772785%28WS.10%29.aspx
It works on windows server 2008 as well as windows server 2003.
The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.
File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)
I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.
var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
modal: true,
height: $("#body").height(),
width: $("#body").width()*.8
});
This is in answer to your question...
I'd also like to know how to make it open up in Sublime Text 2 instead
For Windows:
git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"
Check that the path for sublime_text.exe
is correct and adjust if needed.
For Mac/Linux:
git config --global core.editor "subl -n -w"
If you get an error message such as:
error: There was a problem with the editor 'subl -n -w'.
Create the alias for subl
sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
Again check that the path matches for your machine.
For Sublime Text simply save cmd S
and close the window cmd W
to return to git.
You can do something like this :
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" OnClientClick="document.forms[0].target = '_blank';" />
Yes. Although I use the following code.
.carousel.fade
{
opacity: 1;
.item
{
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
left: 0 !important;
opacity: 0;
top:0;
position:absolute;
width: 100%;
display:block !important;
z-index:1;
&:first-child{
top:auto;
position:relative;
}
&.active
{
opacity: 1;
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
z-index:2;
}
}
}
Then change the class on the carousel from "carousel slide" to "carousel fade". This works in safari, chrome, firefox, and IE 10. It will correctly downgrade in IE 9, however, the nice face effect doesn't happen.
Edit: Since this answer has gotten so popular I've added the following which rewritten as pure CSS instead of the above which was LESS:
.carousel.fade {
opacity: 1;
}
.carousel.fade .item {
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
left: 0 !important;
opacity: 0;
top:0;
position:absolute;
width: 100%;
display:block !important;
z-index:1;
}
.carousel.fade .item:first-child {
top:auto;
position:relative;
}
.carousel.fade .item.active {
opacity: 1;
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
z-index:2;
}
Assuming you are in a highly restricted computer env (such as myself) without root access or ability to install packages...
I had never setup a fresh/standalone/raw/non-root instance of Python+virtualenv before this post. I had do quite a bit of Googling to make this work.
python3
for python
if you are python2 user.wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-x.y.z.tar.gz
tar -xzvf virtualenv-x.y.z.tar.gz
python3 virtualenv-x.y.z/virtualenv.py --python $(which python3) /path/to/new/virtualenv
source /path/to/new/virtualenv/bin/activate
virtualenv
package includes a standalone version of pip
and setuptools
that are auto-magically installed into each new virtualenv. This solves the chicken and egg problem.which python3
should give: /path/to/new/virtualenv/bin/python3
pip
is also available in the virtualenv via which pip
... should give: /path/to/new/virtualenv/bin/pip
Then... pip, pip, pip!
Final tip to newbie Pythoneers: You don't think you need virtualenv when you start, but you will be happy to have it later. Helps with "what if" installation / upgrade scenarios for open source / shared packages.
As of Laravel 5.2, the documentation states that these kinds of event handlers should be registered in the AppServiceProvider:
<?php
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::deleting(function ($user) {
$user->photos()->delete();
});
}
I even suppose to move them to separate classes instead of closures for better application structure.
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
Have you tried using rclone.org?
With rclone
you could do something like
rclone copy "${source}/${subfolder}/" "${target}/${subfolder}/" --progress --multi-thread-streams=N
where --multi-thread-streams=N
represents the number of threads you wish to spawn.
We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.
Default @INC
Perl interpreter is compiled with a specific @INC
default value. To find out this value, run env -i perl -V
command (env -i
ignores the PERL5LIB
environmental variable - see #2) and in the output you will see something like this:
$ env -i perl -V ... @INC: /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
Note .
at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T
(taint checks enabled).
To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs
:
Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3
Environmental variable PERL5LIB
(or PERLLIB
)
Perl pre-pends @INC
with a list of directories (colon-separated) contained in PERL5LIB
(if it is not defined, PERLLIB
is used) environment variable of your shell. To see the contents of @INC
after PERL5LIB
and PERLLIB
environment variables have taken effect, run perl -V
.
$ perl -V ... %ENV: PERL5LIB="/home/myuser/test" @INC: /home/myuser/test /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
-I
command-line option
Perl pre-pends @INC
with a list of directories (colon-separated) passed as value of the -I
command-line option. This can be done in three ways, as usual with Perl options:
Pass it on command line:
perl -I /my/moduledir your_script.pl
Pass it via the first line (shebang) of your Perl script:
#!/usr/local/bin/perl -w -I /my/moduledir
Pass it as part of PERL5OPT
(or PERLOPT
) environment variable (see chapter 19.02 in Programming Perl)
Pass it via the lib
pragma
Perl pre-pends @INC
with a list of directories passed in to it via use lib
.
In a program:
use lib ("/dir1", "/dir2");
On the command line:
perl -Mlib=/dir1,/dir2
You can also remove the directories from @INC
via no lib
.
You can directly manipulate @INC
as a regular Perl array.
Note: Since @INC
is used during the compilation phase, this must be done inside of a BEGIN {}
block, which precedes the use MyModule
statement.
Add directories to the beginning via unshift @INC, $dir
.
Add directories to the end via push @INC, $dir
.
Do anything else you can do with a Perl array.
Note: The directories are unshifted onto @INC
in the order listed in this answer, e.g. default @INC
is last in the list, preceded by PERL5LIB
, preceded by -I
, preceded by use lib
and direct @INC
manipulation, the latter two mixed in whichever order they are in Perl code.
@INC
?There does not seem to be a comprehensive @INC
FAQ-type post on Stack Overflow, so this question is intended as one.
If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC
compiled into the Perl binary.
If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC
in previous use case), set the users' PERL5LIB
, usually during user login.
Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su
.
If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB
manually, or pass the -I
option to perl.
If the modules need to be used only for specific scripts, by all users using them, use use lib
/no lib
pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).
If the directories in @INC
need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib
/no lib
pragmas, then use direct @INC
manipulation inside BEGIN {}
block or inside a special purpose library designated for @INC
manipulation, which must be used by your script(s) before any other modules are used.
An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.
An additional use case for directly manipulating @INC
is to be able to add subroutine references or object references (yes, Virginia, @INC
can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
if ($_POST['action'] == 'addRunner')
I used the :not() on the selection to stop it from clearing the hidden field.
I know i am late to the party but hope this helps someone who will do the same with Class binding
var newEntry = new MyClassObject();
var bindingSource = dataGridView.DataSource as BindingSource;
var myClassObjects = bindingSource.DataSource as List<MyClassObject>;
myClassObjects.Add(newEntry);
bindingSource.DataSource = myClassObjects;
dataGridView.DataSource = null;
dataGridView.DataSource = bindingSource;
dataGridView.Update();
dataGridView.Refresh();
The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2)
, it should work
SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table
OR
SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table
Here's a fun way to do it with a decorator:
def restartable(func):
def wrapper(*args,**kwargs):
answer = 'y'
while answer == 'y':
func(*args,**kwargs)
while True:
answer = raw_input('Restart? y/n:')
if answer in ('y','n'):
break
else:
print "invalid answer"
return wrapper
@restartable
def main():
print "foo"
main()
Ultimately, I think you need 2 while loops. You need one loop bracketing the portion which prompts for the answer so that you can prompt again if the user gives bad input. You need a second which will check that the current answer is 'y'
and keep running the code until the answer isn't 'y'
.
If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su
then apt-get install -y wget
wmic product get name
Just gets the cmd stuck... still flashing _ after a couple minutes
in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
, if you can find the folder with the software name you are trying to install (not the one named with ProductCode), the UninstallString points to the application's own uninstaller C:\Program Files\Zune\ZuneSetup.exe /x
The "traditional" Windows equivalent would be the Protected Storage subsystem, used by IE (pre IE 7), Outlook Express, and a few other programs. I believe it's encrypted with your login password, which prevents some offline attacks, but once you're logged in, any program that wants to can read it. (See, for example, NirSoft's Protected Storage PassView.)
Windows also provides the CryptoAPI and Data Protection API that might help. Again, though, I don't think that Windows does anything to prevent processes running under the same account from seeing each other's passwords.
It looks like the book Mechanics of User Identification and Authentication provides more details on all of these.
Eclipse (via its Secure Storage feature) implements something like this, if you're interested in seeing how other software does it.
bar
is your static variable and you can access it using Foo.bar
.
Basically, you need to qualify your static variable with Class name.
DELETE FROM blob
WHERE fileid NOT IN
(SELECT id
FROM files
WHERE id is NOT NULL/*This line is unlikely to be needed
but using NOT IN...*/
)
If it's always going to be an even LHS/RHS split, you can also use the partition
method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS)
if the separator is found, and (original_string, '', '')
if the separator wasn't present:
>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')
>>> "shazam".partition("_")
('shazam', '', '')
I can't comment yet but following on Fellow Stranger solution you can also keep nesting in case you have keys which values are an array. Like this:
filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]
This works:
params.require(:model).permit(filters: [[:name, values: []]])
Node.js
introduced async await
in 7.6
so this makes Javascript
more beautiful.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
results.push(await search(query));
}
res.writeHead( ... );
res.end(results);
For this to work search
fucntion has to return a promise
or it has to be async
function
If it is not returning a Promise
you can help it to return a Promise
function asyncSearch(query) {
return new Promise((resolve, reject) => {
search(query,(result)=>{
resolve(result);
})
})
}
Then replace this line await search(query);
by await asyncSearch(query);
There are two parts of memory allocated for an object of reference type. One in stack and one in heap. The part in stack (aka a pointer) contains reference to the part in heap - where the actual values are stored.
When ref keyword is not use, just a copy of part in stack is created and passed to the method - reference to same part in heap. Therefore if you change something in heap part, those change will stayed. If you change the copied pointer - by assign it to refer to other place in heap - it will not affect to origin pointer outside of the method.
If performance is important to you, and your compiler supports lambdas, the stdev calculation can be made faster and simpler: In tests with VS 2012 I've found that the following code is over 10 X quicker than the Boost code given in the chosen answer; it's also 5 X quicker than the safer version of the answer using standard libraries given by musiphil.
Note I'm using sample standard deviation, so the below code gives slightly different results (Why there is a Minus One in Standard Deviations)
double sum = std::accumulate(std::begin(v), std::end(v), 0.0);
double m = sum / v.size();
double accum = 0.0;
std::for_each (std::begin(v), std::end(v), [&](const double d) {
accum += (d - m) * (d - m);
});
double stdev = sqrt(accum / (v.size()-1));
The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).
In case you have only one controller and you want to access every action on root you can skip controller name like this
routes.MapRoute(
"Default",
"{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
On macOS (El Capitan). You can simply use: brew install postgresql
cout << "Enter amount of spaces you would like (integer)" << endl;
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
cout << " " ;
}
cout <<endl;
There are several possible causes.
The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software.
More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error.
It can also be caused by closing a socket when there is unread data in the socket receive buffer.
In Windows, 'software caused connection abort', which is not the same as 'connection reset', is caused by network problems sending from your end. There's a Microsoft knowledge base article about this.
You Can use this -
Suppose we have a list, l = [1,2,3,4,5]
We want to delete last two items in a single statement
del l[3:]
We have output:
l = [1,2,3]
Keep it Simple
Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{
@Autowired
MyService service;
...
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException
{
// Do something with the context here
}
}
If you have PHP >= 5.1:
function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
otherwise:
function isWeekend($date) {
$weekDay = date('w', strtotime($date));
return ($weekDay == 0 || $weekDay == 6);
}
Set ReadTimeout or WriteTimeout property on the NetworkStream for synchronous reads/writes. Updating OP's code:
try
{
TcpClient client = new TcpClient("remotehost", this.Port);
Byte[] data = System.Text.Encoding.Unicode.GetBytes(this.Message);
NetworkStream stream = client.GetStream();
stream.WriteTimeout = 1000; // <------- 1 second timeout
stream.ReadTimeout = 1000; // <------- 1 second timeout
stream.Write(data, 0, data.Length);
data = new Byte[512];
Int32 bytes = stream.Read(data, 0, data.Length);
this.Response = System.Text.Encoding.Unicode.GetString(data, 0, bytes);
stream.Close();
client.Close();
FireSentEvent(); //Notifies of success
}
catch (Exception ex)
{
// Throws IOException on stream read/write timeout
FireFailedEvent(ex); //Notifies of failure
}
One-liner:
$valueExists = (Get-Item $regKeyPath -EA Ignore).Property -contains $regValueName
The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection
The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().
Select columns by namedata <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr [ 4]: carrier, tailnum, origin, dest
#> dbl [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#> plane year month day dep_time sched_dep_time dep_delay arr_time
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 N142… 2013 1 1 517 515 2 830
#> 2 N242… 2013 1 1 533 529 4 850
#> 3 N619… 2013 1 1 542 540 2 923
#> 4 N804… 2013 1 1 544 545 -1 1004
#> 5 N668… 2013 1 1 554 600 -6 812
#> 6 N394… 2013 1 1 554 558 -4 740
#> 7 N516… 2013 1 1 555 600 -5 913
#> 8 N829… 2013 1 1 557 600 -3 709
#> 9 N593… 2013 1 1 557 600 -3 838
#> 10 N3AL… 2013 1 1 558 600 -2 753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> # arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>
EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto
. This is my current favorite solution
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
Just use a custom comparator (it's an optional 3rd argument to std::sort
)
struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
If you're using a C++11 compiler, you can write the same using lambdas:
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
then you can do this too:
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
or even
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P
The package broom
comes in handy here (it uses the "tidy" format).
tidy(mg)
will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).
Example from broom
's github repo:
lmfit <- lm(mpg ~ wt, mtcars)
require(broom)
tidy(lmfit)
term estimate std.error statistic p.value
1 (Intercept) 37.285 1.8776 19.858 8.242e-19
2 wt -5.344 0.5591 -9.559 1.294e-10
is.data.frame(tidy(lmfit))
[1] TRUE
If you can accept Double Objects than this post is helpful: Initialization of an ArrayList in one line
List<Double> y = Arrays.asList(null, 1.0, 2.0);
Double x = y.get(1);
I do not think that is possible you have to set all the values individualling (like the first example you provided.)
The Second example you gave, will only Initialize the last varuable to "" and not the others.
Arrays.fill works with single dimensional array, so to fill two dimensional array we can do below
for (int i = 0, len = arr.length; i < len; i++)
Arrays.fill(arr[i], 0);
SELECT <column_list>
FROM TABLEA a
LEFTJOIN TABLEB b
ON a.Key = b.Key
WHERE b.Key IS NULL;
https://www.cloudways.com/blog/how-to-join-two-tables-mysql/
I agree with the accepted answer above but it is only good for known string values. For dynamic string values here is my suggestion.
// A list may come from an API JSON like
{
"names": [
"Person 1",
"Person 2",
"Person 3",
...
"Person N"
]
}
var listOfNames = mutableListOf<String>()
val stringOfNames = listOfNames.joinToString(", ")
// ", " <- a separator for the strings, could be any string that you want
// Posible result
// Person 1, Person 2, Person 3, ..., Person N
This is useful for concatenating list of strings with separator.
You can use the glob() function to do this.
Here is some documentation on it: http://php.net/manual/en/function.glob.php
To retrieve the entire querystring from the current URL, beginning with the ?
character, you can use
location.search
https://developer.mozilla.org/en-US/docs/DOM/window.location
Example:
// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123"
In regards to retrieving specific querystring parameters, while although classes like URLSearchParams
and URL
exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:
/**
* Accepts either a URL or querystring and returns an object associating
* each querystring parameter to its value.
*
* Returns an empty object if no querystring parameters found.
*/
function getUrlParams(urlOrQueryString) {
if ((i = urlOrQueryString.indexOf('?')) >= 0) {
const queryString = urlOrQueryString.substring(i+1);
if (queryString) {
return _mapUrlParams(queryString);
}
}
return {};
}
/**
* Helper function for `getUrlParams()`
* Builds the querystring parameter to value object map.
*
* @param queryString {string} - The full querystring, without the leading '?'.
*/
function _mapUrlParams(queryString) {
return queryString
.split('&')
.map(function(keyValueString) { return keyValueString.split('=') })
.reduce(function(urlParams, [key, value]) {
if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
urlParams[key] = parseInt(value);
} else {
urlParams[key] = decodeURI(value);
}
return urlParams;
}, {});
}
You can use the above like so:
// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }
// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }
// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName') {
console.log(urlParams.parameterName);
}
The top answers are correct. Please check them direct in MySQL CLI first. If this fixes the problem there, you may want to have it working in Python3 just pass it to the MySQLdb.connect
as parameter
self.connection = MySQLdb.connect(
host=host, user=settings_DB.db_config['USER'],
port=port, passwd=settings_DB.db_config['PASSWORD'],
db=settings_DB.db_config['NAME'],
local_infile=True)
tr:not(:contains(.... work for me
function busca(busca){
$("#listagem tr:not(:contains('"+busca+"'))").css("display", "none");
$("#listagem tr:contains('"+busca+"')").css("display", "");
}
In some situations you can hide the shadow by another container. Eg, if there is a DIV above and below the DIV with the shadow, you can use position: relative; z-index: 1;
on the surrounding DIVs.
This command:
iconv -f utf-8 -t utf-8 -c file.txt
will clean up your UTF-8 file, skipping all the invalid characters.
-f is the source format
-t the target format
-c skips any invalid sequence
Here's how you do it:
Getting the max heap size that the app can use:
Runtime runtime = Runtime.getRuntime();
long maxMemory=runtime.maxMemory();
Getting how much of the heap your app currently uses:
long usedMemory=runtime.totalMemory() - runtime.freeMemory();
Getting how much of the heap your app can now use (available memory) :
long availableMemory=maxMemory-usedMemory;
And, to format each of them nicely, you can use:
String formattedMemorySize=Formatter.formatShortFileSize(context,memorySize);
First off, I think mplot3D
worked a bit differently in matplotlib
version 0.99
than it does in the current version of matplotlib
.
Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")
I'm guessing you're running version 0.99
, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib
.
If you're running version 0.99
, try doing this instead of using using the projection
keyword argument:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization!
fig = plt.figure()
ax = Axes3D(fig) #<-- Note the difference from your original code...
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
This should work in matplotlib
1.0.x
, as well, not just 0.99
.
onCreate()
method gets called when activity gets created, and its called only once in whole Activity life cycle.
where as onStart()
is called when activity is stopped... I mean it has gone to background and its onStop()
method is called by the os. onStart()
may be called multiple times in Activity life cycle.More details here
Completely idempotent url that preserves path, parameters, and anchor.
<a href="javascript:"> click me </a>
it only uses a little tiny bit of JS.
EDIT: this does not reload the page. It is a link that does nothing.
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
The official position seems to be that this isn't something you'd ever "want to do". See this thread on the Android Developers list. Google envisage android running on a variety of different devices (CPUs, displays, etc). The best way to enable development is therefore to use (portable) managed code that targets the Dalvik VM. For this reason, the Android SDK doesn't support C/C++.
BUT, take a look at this page:
Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework.
The managed application framework appears to be layered on-top of these libraries. The page goes on to list the C/C++ libs: standard C library, media, 3D, SQL lite, and others.
So all you need is a compiler chain that will compile C/C++ to the appropriate CPU (ARM, in the case of the G1). Some brief instructions on how to do this are here.
What I don't know is where to find descriptions of the APIs that these libraries provide. I'd guess there may be header files buried in the SDK somewhere, but documentation may be sketchy/missing. But I think it can be done!
Hope thats useful. For the record, I haven't written any native android apps - just a few simple managed ones.
Andy
You're making an HTTP POST, but trying to pass parameters with the GET query string syntax. In a POST, the data are passed as named parameters and do not use the param=value&foo=bar
syntax. Using jQuery's ajax method lets you create a javascript object with the named parameters, like so:
$.ajax({
url: '/Home/SaveChart',
type: 'POST',
async: false,
dataType: 'text',
processData: false,
data: {
input: JSON.stringify(IVRInstant.data),
name: $("#wrkname").val()
},
success: function (data) { }
});
My case was solved with SESSION_DOMAIN
, in my local machine had to be set to xxx.localhost
. It was causing conflicts with the production SESSION_DOMAIN
, xxx.com
that was set directly in the session.php config file.
If you are using a local array for JSON - as you showed in your example in the question (test.json) then you can is the parseJSON()
method of JQuery ->
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
getJSON()
is used for getting JSON from a remote site - it will not work locally (unless you are using a local HTTP Server)
Quick and dirty - Turn it off:
USE_TZ = False
in your settings.py
You could also do this if you think it's more clear:
if (columnname != a
&& columnname != b
&& columnname != c
{
if (checkbox.checked || columnname != A2)
{
"statement 1"
}
}
If you have yum you could do:
yum remove nodesource-release* nodejs
yum clean all
And after that check if its deleted:
rpm -qa 'node|npm'
Check the NPM docs for install
With the
--production
flag (or when the NODE_ENV environment variable is set to production), npm will not install modules listed in devDependencies."The
--only={prod[uction]|dev[elopment]}
argument will cause either only devDependencies or only non-devDependencies to be installed regardless of the NODE_ENV."
Have you tried
npm install --only=dev
If you are worried that your package.json might be incorrect, best thing to do is this. Create a new folder, and run:
npm init --yes
Then:
npm install --save-dev brunch@^2.0.4
npm install --save-dev cssnano-brunch@^1.1.5
npm install --save-dev javascript-brunch@^1.8.0
npm install --save-dev sass-brunch@^1.9.2
npm install --save-dev uglify-js-brunch@^1.7.8
npm install jquery@^2.1.4 --save
And you should be good to go! Otherwise, will keep posting other options.
Check your npm configuration:
npm config list
npm gets its config settings from the command line, environment variables, and npmrc files. So check environment variables, and the npmrc file.
Still failing?
Ok, create a new folder, ideally somewhere else on your filesystem. ie. not in same folder hierarchy. For instance, C:\myNewFolder - the closer to the base C: drive the better.
Then run:
npm init --yes
Now run:
npm install underscore --save
and finally:
npm install mocha --save-dev
Does everything work as expected?
What I am trying to do is understand whether your problem is global, or something local to the previous folder and dependencies.
Regarding your question about the Permutation Cycle, read more here: https://www.codechef.com/problems/PCYCLE
You can try this code (enter the size and the digits number):
# include<cstdio>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
int num[1000];
int visited[1000]={0};
int vindex[2000];
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
int t_visited=0;
int cycles=0;
int start=0, index;
while(t_visited < n)
{
for(int i=1;i<=n;i++)
{
if(visited[i]==0)
{
vindex[start]=i;
visited[i]=1;
t_visited++;
index=start;
break;
}
}
while(true)
{
index++;
vindex[index]=num[vindex[index-1]];
if(vindex[index]==vindex[start])
break;
visited[vindex[index]]=1;
t_visited++;
}
vindex[++index]=0;
start=index+1;
cycles++;
}
printf("%d\n",cycles,vindex[0]);
for(int i=0;i<(n+2*cycles);i++)
{
if(vindex[i]==0)
printf("\n");
else
printf("%d ",vindex[i]);
}
}
Since I don't believe "Please use..." plus some random code that is unrelated to the question
is a good answer, but I do believe the spirit was correct, I decided to answer this correctly.
When you are using Sql Bulk Copy, it attempts to align your input data directly with the data on the server. So, it takes the Server Table and performs a SQL statement similar to this:
INSERT INTO [schema].[table] (col1, col2, col3) VALUES
Therefore, if you give it Columns 1, 3, and 2, EVEN THOUGH your names may match (e.g.: col1, col3, col2). It will insert like so:
INSERT INTO [schema].[table] (col1, col2, col3) VALUES
('col1', 'col3', 'col2')
It would be extra work and overhead for the Sql Bulk Insert to have to determine a Column Mapping. So it instead allows you to choose... Either ensure your Code and your SQL Table columns are in the same order, or explicitly state to align by Column Name.
Therefore, if your issue is mis-alignment of the columns, which is probably the majority of the cause of this error, this answer is for you.
using System.Data;
//...
myDataTable.Columns.Cast<DataColumn>().ToList().ForEach(x =>
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(x.ColumnName, x.ColumnName)));
This will take your existing DataTable, which you are attempt to insert into your created BulkCopy object, and it will just explicitly map name to name. Of course if, for some reason, you decided to name your DataTable Columns differently than your SQL Server Columns... that's on you.
<div class="nav-collapse">
<ul class="nav">
<li class="home"><a href="~/Home/Index">Home</a></li>
<li class="Project"><a href="#">Project</a></li>
<li class="Customer"><a href="#">Customer</a></li>
<li class="Staff"><a href="#">Staff</a></li>
<li class="Broker"><a href="~/Home/Broker">Broker</a></li>
<li class="Sale"><a href="#">Sale</a></li>
</ul>
</div>
then for each page you add this:
//home
$(document).ready(function () {
$('.home').addClass('active');
});
//Project page
$(document).ready(function () {
$('.Project').addClass('active');
});
//Customer page
$(document).ready(function () {
$('.Customer').addClass('active');
});
//staff page
$(document).ready(function () {
$('.Staff').addClass('active');
});
I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:
$("#addComment").click(function() {
if(typeof TinyMCE === "undefined") {
$.ajax({
url: "tinymce.js",
dataType: "script",
cache: true,
success: function() {
TinyMCE.init();
}
});
}
});
The getScript()
function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:
http://www.yoursite.com/js/tinymce.js?_=1399055841840
If a user clicks the #addComment
link multiple times, tinymce.js
will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.
===
Alternatively, in the getScript()
documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript()
function as follows:
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
===
Or, if you want to disable caching globally, you can do so using ajaxSetup()
as follows:
$.ajaxSetup({
cache: true
});
The problem is that your img
s will always bump down to the next line because of the containing div
.
In order to get around this, you need to place the img
s in their own div
with a width
wide enough to hold all of them. Then you can use your styles as is.
So, when I set the img
s to 120px
each and place them inside a
div#insideDiv{
width:800px;
}
it all works.
Adjust width as necessary.
The substitute of fcntl
on windows are win32api
calls. The usage is completely different. It is not some switch you can just flip.
In other words, porting a fcntl
-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl
call does and then find the equivalent win32api
code, if any.
There's also the possibility that some code using fcntl
has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.
If you provide more details about the fcntl
calls people can find windows equivalents.
one option is javascript parseFloat()
...
never do parse a "text chain" --> 12.3456
with point to a int... 123456
(int remove the point)
parse a text chain to a FLOAT...
to send this coords to a server do this sending a text chain. HTTP
only sends TEXT
in the client keep out of parsing the input coords with "int
", work with text strings
if you print the cords in the html with php or similar... float to text and print in html
It depends on your definition of what memory query you wish to get.
Usually, you'd like to know the status of the heap memory, since if it uses too much memory, you get OOM and crash the app.
For this, you can check the next values:
final Runtime runtime = Runtime.getRuntime();
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;
The more the "usedMemInMB" variable gets close to "maxHeapSizeInMB", the closer availHeapSizeInMB
gets to zero, the closer you get OOM. (Due to memory fragmentation, you may get OOM BEFORE this reaches zero.)
That's also what the DDMS tool of memory usage shows.
Alternatively, there is the real RAM usage, which is how much the entire system uses - see accepted answer to calculate that.
Update: since Android O makes your app also use the native RAM (at least for Bitmaps storage, which is usually the main reason for huge memory usage), and not just the heap, things have changed, and you get less OOM (because the heap doesn't contain bitmaps anymore,check here), but you should still keep an eye on memory use if you suspect you have memory leaks. On Android O, if you have memory leaks that should have caused OOM on older versions, it seems it will just crash without you being able to catch it. Here's how to check for memory usage:
val nativeHeapSize = Debug.getNativeHeapSize()
val nativeHeapFreeSize = Debug.getNativeHeapFreeSize()
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
But I believe it might be best to use the profiler of the IDE, which shows the data in real time, using a graph.
So the good news on Android O is that it's much harder to get crashes due to OOM of storing too many large bitmaps, but the bad news is that I don't think it's possible to catch such a case during runtime.
EDIT: seems Debug.getNativeHeapSize()
changes over time, as it shows you the total max memory for your app. So those functions are used only for the profiler, to show how much your app is using.
If you want to get the real total and available native RAM , use this:
val memoryInfo = ActivityManager.MemoryInfo()
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
val nativeHeapSize = memoryInfo.totalMem
val nativeHeapFreeSize = memoryInfo.availMem
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
Log.d("AppLog", "total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
"free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
"used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)")
Use checked="checked"
attribute if you want your checkbox to be checked.
Since you're using SQL 2008:
UPDATE
table_Name
SET
column_A
= CASE
WHEN @flag = '1' THEN @new_value
ELSE 0
END + column_A,
column_B
= CASE
WHEN @flag = '0' THEN @new_value
ELSE 0
END + column_B
WHERE
ID = @ID
If you were using SQL 2012:
UPDATE
table_Name
SET
column_A = column_A + IIF(@flag = '1', @new_value, 0),
column_B = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
ID = @ID
Import your csv or sql to sqlite with phpLiteAdmin, it is excellent.
Add 0.001
first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)
Code example:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(b);
}
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
You may like to first create a dialogue by right clicking the project in solution explorer and in the code file type
dialogue1.show()
that's all !!!
In our current project at work we had a invisible iFrame and I had to feed the url for the file to the iFrame to get a download dialog box. On the button click, the controller generates the dynamic url and triggers a $scope event where a custom directive
I wrote, is listing. The directive will append a iFrame to the body if it does not exist already and sets the url attribute on it.
EDIT: Adding a directive
appModule.directive('fileDownload', function ($compile) {
var fd = {
restrict: 'A',
link: function (scope, iElement, iAttrs) {
scope.$on("downloadFile", function (e, url) {
var iFrame = iElement.find("iframe");
if (!(iFrame && iFrame.length > 0)) {
iFrame = $("<iframe style='position:fixed;display:none;top:-1px;left:-1px;'/>");
iElement.append(iFrame);
}
iFrame.attr("src", url);
});
}
};
return fd;
});
This directive responds to a controller event called downloadFile
so in your controller you do
$scope.$broadcast("downloadFile", url);
Perl's behavior, with the code given in the OP can take none or several arguments, and if an argument is a single hyphen -
this is understood as stdin. Moreover, it's always possible to have the filename with $ARGV
.
None of the answers given so far really mimic Perl's behavior in these respects. Here's a pure Bash possibility. The trick is to use exec
appropriately.
#!/bin/bash
(($#)) || set -- -
while (($#)); do
{ [[ $1 = - ]] || exec < "$1"; } &&
while read -r; do
printf '%s\n' "$REPLY"
done
shift
done
Filename's available in $1
.
If no arguments are given, we artificially set -
as the first positional parameter. We then loop on the parameters. If a parameter is not -
, we redirect standard input from filename with exec
. If this redirection succeeds we loop with a while
loop. I'm using the standard REPLY
variable, and in this case you don't need to reset IFS
. If you want another name, you must reset IFS
like so (unless, of course, you don't want that and know what you're doing):
while IFS= read -r line; do
printf '%s\n' "$line"
done
I was having the same issue
Role.java
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
Set<BusinessUnitMaster> businessUnits =new HashSet<>();
BusinessUnitMaster.java
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
name = "BusinessUnitRoles",
joinColumns = {@JoinColumn(name = "unit_id", referencedColumnName = "record_id")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "record_id")}
)
private Set<Role> roles=new HashSet<>();
the problem is that when you create BusinessUnitMaster and Role you have to save the object for both sides for RoleService.java
roleRepository.save(role);
for BusinessUnitMasterService.java
businessUnitMasterRepository.save(businessUnitMaster);
First, you do not need android:process=":remote"
, so please remove it, since all it will do is take up extra RAM for no benefit.
Second, since the <service>
element contains an action string, use it:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=new Intent("com.sample.service.serviceClass");
this.startService(intent);
}
As others said, you simply put :not(.class). For CSS selectors, I recommend visiting this link, it's been very helpful throughout my journey: https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048
div:not(.success) {
color: red;
}
The negation pseudo class is particularly helpful. Let's say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.
Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:
*:not(p) {
color: green;
}
This function isn't just for headers. You can do a lot of interesting stuff with this. Example: You could split your page into sections and use it like this:
$someTemplate->selectSection('header');
echo 'This is the header.';
$someTemplate->selectSection('content');
echo 'This is some content.';
You can capture the output that is generated here and add it at two totally different places in your layout.
I'm afraid your map contains something other than String
objects. If you call toString()
on a String object, you obtain the string itself.
What you get [Ljava.lang.String
indicates you might have a String array.
The python documentation is actually very clear, and following the instructions did the job whereas other answers I found here were not fixing this issue.
first, install python 3.x.x from source using, for example with version 3.6.2 https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tar.xz
make sure you have openssl installed by running brew install openssl
unzip it and move to the python directory: tar xvzf Python-3.6.2.tar.xz && cd Python-3.6.2
then if the python version is < 3.7, run
CPPFLAGS="-I$(brew --prefix openssl)/include" \
LDFLAGS="-L$(brew --prefix openssl)/lib" \
./configure --with-pydebug
5. finallly, run make -s -j2
(-s
is the silent flag, -j2
tells your machine to use 2 jobs)
Sorry, but you're doing it wrong.
People should have the following security guideline tattooed on the inside of their eyelids:
Never keep plain text passwords in memory.
The reason the WPF/Silverlight PasswordBox
doesn't expose a DP for the Password
property is security related.
If WPF/Silverlight were to keep a DP for Password
it would require the framework to keep the password itself unencrypted in memory. Which is considered quite a troublesome security attack vector.
The PasswordBox
uses encrypted memory (of sorts) and the only way to access the password is through the CLR property.
I would suggest that when accessing the PasswordBox.Password
CLR property you'd refrain from placing it in any variable or as a value for any property.
Keeping your password in plain text on the client machine RAM is a security no-no.
So get rid of that public string Password { get; set; }
you've got up there.
When accessing PasswordBox.Password
, just get it out and ship it to the server ASAP.
Don't keep the value of the password around and don't treat it as you would any other client machine text. Don't keep clear text passwords in memory.
I know this breaks the MVVM pattern, but you shouldn't ever bind to PasswordBox.Password
Attached DP, store your password in the ViewModel or any other similar shenanigans.
If you're looking for an over-architected solution, here's one:
1. Create the IHavePassword
interface with one method that returns the password clear text.
2. Have your UserControl
implement a IHavePassword
interface.
3. Register the UserControl
instance with your IoC as implementing the IHavePassword
interface.
4. When a server request requiring your password is taking place, call your IoC for the IHavePassword
implementation and only than get the much coveted password.
Just my take on it.
-- Justin
According to Firebase docs you can also use string resources instead of google-services.json.
Because this provider is just reading resources with known names, another option is to add the string resources directly to your app instead of using the Google Services gradle plugin. You can do this by:
- Removing the
google-services
plugin from your root build.gradle- Deleting the
google-services.json
from your project- Adding the string resources directly
- Deleting apply plugin:
'com.google.gms.google-services'
from your app build.gradle
Example strings.xml
:
<string name="google_client_id">XXXXXXXXX.apps.googleusercontent.com</string>
<string name="default_web_client_id">XXXX-XXXXXX.apps.googleusercontent.com</string>
<string name="gcm_defaultSenderId">XXXXXX</string>
<string name="google_api_key">AIzaXXXXXX</string>
<string name="google_app_id">1:XXXXXX:android:XXXXX</string>
<string name="google_crash_reporting_api_key">AIzaXXXXXXX</string>
<string name="project_id">XXXXXXX</string>
Command to remove Cordova and ionic
For Window system
For Mac system
For install cordova and ionic
eg.
sudo npm install -g [email protected]
sudo npm install -g [email protected]
In swift :
#if (arch(i386) || arch(x86_64))
...
#endif
From Detect if app is being built for device or simulator in Swift
I've historically rolled my own access at a low level (XML generation and parsing) to deal with the occasional need to do SOAP style requests from Objective-C. That said, there's a library available called SOAPClient (soapclient) that is open source (BSD licensed) and available on Google Code (mac-soapclient) that might be of interest.
I won't attest to it's abilities or effectiveness, as I've never used it or had to work with it's API's, but it is available and might provide a quick solution for you depending on your needs.
Apple had, at one time, a very broken utility called WS-MakeStubs. I don't think it's available on the iPhone, but you might also be interested in an open-source library intended to replace that - code generate out Objective-C for interacting with a SOAP client. Again, I haven't used it - but I've marked it down in my notes: wsdl2objc
For future reference, I had the same problem
"warning: Skipping unreadable file"
under Linux. The reason was that I love using Tab-completing and in gnuplot this added a whitespace at the end that I did not really notice
gnuplot> plot "./datafile.txt "
I have read all the answers here and none of them was complete answer for my situation (which is exactly the same in this question) so here is how I gathered some parts of the suggested answers and come up with the exact solution:
echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won't work) The code below should be your first line!
<?php header('HTTP/1.0 403 Forbidden');
$contents = file_get_contents('/home/your_account/public_html/domain.com/403.html', TRUE);
exit($contents);
Now you have the exact solution. I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.
Try this
function test()
{
$("body").append("<input type='button' id='field' />");
}