For quick reference, all the following methods will add a new key 'a' if it does not exist already or it will update the existing key value pair with the new value offered:
data['a']=1
data.update({'a':1})
data.update(dict(a=1))
data.update(a=1)
You can also mixing them up, for example, if key 'c' is in data but 'd' is not, the following method will updates 'c' and adds 'd'
data.update({'c':3,'d':4})
In Excel 2016 at least, you can use INDIRECT with a full path reference; the entire reference (including sheet name) needs to be enclosed by '
characters.
So this should work for you:
= INDIRECT("'C:\data\[myExcelFile.xlsm]" & C13 & "'!$A$1")
Note the closing '
in the last string (ie '!$A$1
surrounded by ""
)
You can achieve this by controlling the formatting of the old/new/unchanged lines in GNU diff
output:
diff --new-line-format="" --unchanged-line-format="" file1 file2
The input files should be sorted for this to work. With bash
(and zsh
) you can sort in-place with process substitution <( )
:
diff --new-line-format="" --unchanged-line-format="" <(sort file1) <(sort file2)
In the above new and unchanged lines are suppressed, so only changed (i.e. removed lines in your case) are output. You may also use a few diff
options that other solutions don't offer, such as -i
to ignore case, or various whitespace options (-E
, -b
, -v
etc) for less strict matching.
Explanation
The options --new-line-format
, --old-line-format
and --unchanged-line-format
let you control the way diff
formats the differences, similar to printf
format specifiers. These options format new (added), old (removed) and unchanged lines respectively. Setting one to empty "" prevents output of that kind of line.
If you are familiar with unified diff format, you can partly recreate it with:
diff --old-line-format="-%L" --unchanged-line-format=" %L" \
--new-line-format="+%L" file1 file2
The %L
specifier is the line in question, and we prefix each with "+" "-" or " ", like diff -u
(note that it only outputs differences, it lacks the ---
+++
and @@
lines at the top of each grouped change).
You can also use this to do other useful things like number each line with %dn
.
The diff
method (along with other suggestions comm
and join
) only produce the expected output with sorted input, though you can use <(sort ...)
to sort in place. Here's a simple awk
(nawk) script (inspired by the scripts linked-to in Konsolebox's answer) which accepts arbitrarily ordered input files, and outputs the missing lines in the order they occur in file1.
# output lines in file1 that are not in file2
BEGIN { FS="" } # preserve whitespace
(NR==FNR) { ll1[FNR]=$0; nl1=FNR; } # file1, index by lineno
(NR!=FNR) { ss2[$0]++; } # file2, index by string
END {
for (ll=1; ll<=nl1; ll++) if (!(ll1[ll] in ss2)) print ll1[ll]
}
This stores the entire contents of file1 line by line in a line-number indexed array ll1[]
, and the entire contents of file2 line by line in a line-content indexed associative array ss2[]
. After both files are read, iterate over ll1
and use the in
operator to determine if the line in file1 is present in file2. (This will have have different output to the diff
method if there are duplicates.)
In the event that the files are sufficiently large that storing them both causes a memory problem, you can trade CPU for memory by storing only file1 and deleting matches along the way as file2 is read.
BEGIN { FS="" }
(NR==FNR) { # file1, index by lineno and string
ll1[FNR]=$0; ss1[$0]=FNR; nl1=FNR;
}
(NR!=FNR) { # file2
if ($0 in ss1) { delete ll1[ss1[$0]]; delete ss1[$0]; }
}
END {
for (ll=1; ll<=nl1; ll++) if (ll in ll1) print ll1[ll]
}
The above stores the entire contents of file1 in two arrays, one indexed by line number ll1[]
, one indexed by line content ss1[]
. Then as file2 is read, each matching line is deleted from ll1[]
and ss1[]
. At the end the remaining lines from file1 are output, preserving the original order.
In this case, with the problem as stated, you can also divide and conquer using GNU split
(filtering is a GNU extension), repeated runs with chunks of file1 and reading file2 completely each time:
split -l 20000 --filter='gawk -f linesnotin.awk - file2' < file1
Note the use and placement of -
meaning stdin
on the gawk
command line. This is provided by split
from file1 in chunks of 20000 line per-invocation.
For users on non-GNU systems, there is almost certainly a GNU coreutils package you can obtain, including on OSX as part of the Apple Xcode tools which provides GNU diff
, awk
, though only a POSIX/BSD split
rather than a GNU version.
find
commandfind / -iname "*vimrc*" -type f 2>/dev/null
There are many answers already, but it can sometimes be useful to simply run a "find" for anything containing the name "vimrc".
The reason is that this will show you what files you actualy have available on the system currently, rather than what you might put on your system. (The information for which you would obtain from :version
as explained in other answers.)
On my system this produces
/usr/share/vim/vim82/vimrc_example.vim
/usr/share/vim/vim82/gvimrc_example.vim
/etc/vim/gvimrc
/etc/vim/vimrc
/etc/vim/vimrc.tiny
Which is quite useful because it tells us that there are 2 example files installed in the share directorys for both gvim and vim, and that there are also some system-wide config files below /etc/
.
On my system, I also have a file at ~/.vimrc
but this does not appear in this list because it is a link to another file, stored under ~/Linux-Config
. But you won't have this directory, it's specific to machines I use on my own network.
find
syntax usedExplanation:
/
(find works recursively)*vimrc*
which means any name with vimrc
(case insensitive) in it somewhere, can be preceeded or followed by anything or nothing (*
)/dev/null
otherwise the output is spammed with unreadable errors from /proc
Let's take an example. If your table has columns as follows:
<!-- ID Column -->
<ng-container matColumnDef="id" >
<th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
<td mat-cell *matCellDef="let row"> {{row.sid}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td mat-cell *matCellDef="let row"> {{row.name}} </td>
</ng-container>
As this contain two columns. then we can set the width of columns using
.mat-column-<matColumnDef-value>{
width: <witdh-size>% !important;
}
for this example, we take
.mat-column-id{
width: 20% !important;
}
.mat-column-name{
width: 80% !important;
}
The smallest change to fix this would be to change
onClick="document.getElementById("datepicker").click()">
to
onClick="$('#datepicker').click()">
click()
is a jQuery method. Also, you had a collision between the double-quotes used for the HTML element attribute and those use for the JavaScript function argument.
I've been looking through stack overflow to find a good answer and when i couldn't find one i went looking through the docs.
no one seems to have stumbled on this simple answer yet:
ViewCompat.setTranslationZ(view, translationZ);
default translation z is 0.0
A working code:
private void changeScreenOrientation() {
int orientation = yourActivityName.this.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
showMediaDescription();
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
hideMediaDescription();
}
if (Settings.System.getInt(getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 0) == 1) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}, 4000);
}
}
call this method in your button click
In Oracle you can do this:
SELECT * FROM table1 WHERE (col_a,col_b) IN (SELECT col_x,col_y FROM table2)
No, there's not really any way to control this as a web developer.
Small exceptions are that you can do some fake forcing of anti-aliasing by using Flash through sIFR, and some browsers won't anti-alias bitmap/pixel fonts (as they shouldn't, more info: Anti-Aliasing / Anti-Anti-Aliasing).
Also, as Daniel mentioned, it's ideal to be using em
units for all fonts, see The Incredible Em & Elastic Layouts with CSS for more information about this.
Check my code, I hope this helped you :)
public async Task GIF_Animation_Pro(string FileName,int speed,bool _Repeat)
{
int ab=0;
var gif = GifBitmapDecoder.Create(new Uri(FileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
var getFrames = gif.Frames;
BitmapFrame[] frames = getFrames.ToArray();
await Task.Run(() =>
{
while (ab < getFrames.Count())
{
Thread.Sleep(speed);
try
{
Dispatcher.Invoke(() =>
{
gifImage.Source = frames[ab];
});
if (ab == getFrames.Count - 1&&_Repeat)
{
ab = 0;
}
ab++;
}
catch
{
}
}
});
}
or
public async Task GIF_Animation_Pro(Stream stream, int speed,bool _Repeat)
{
int ab = 0;
var gif = GifBitmapDecoder.Create(stream , BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
var getFrames = gif.Frames;
BitmapFrame[] frames = getFrames.ToArray();
await Task.Run(() =>
{
while (ab < getFrames.Count())
{
Thread.Sleep(speed);
try
{
Dispatcher.Invoke(() =>
{
gifImage.Source = frames[ab];
});
if (ab == getFrames.Count - 1&&_Repeat)
{
ab = 0;
}
ab++;
}
catch{}
}
});
}
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
Perhaps this is a bit off-topic, seeing as the question has already been answered, but I have experienced a similar problem. In my case only some of the unit test resources were copied to the output folder upon compilation. My persistence.xml in the META-INF folder got copied but nothing else.
In the end I "solved" the problem by renaming the problematic files, rebuiling the project and then changing the file names back to the original ones. Do not ask me why this worked but it did. My best guess is that, somehow, my IntelliJ project had gotten a bit out of sync with the file system and the renaming operation triggered some kind of internal "resource rescan".
HTML and CSS only.
#leftsideMenu ul li {_x000D_
border-bottom: 1px dashed lightgray;_x000D_
background-color: cadetblue;_x000D_
}_x000D_
_x000D_
#leftsideMenu ul li a {_x000D_
padding: 8px 20px 8px 20px;_x000D_
color: white;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#leftsideMenu ul li a:hover {_x000D_
background-color: lightgreen;_x000D_
transition: 0.5s;_x000D_
padding-left: 30px;_x000D_
padding-right: 10px;_x000D_
}
_x000D_
<div id="leftsideMenu">_x000D_
<ul style="list-style-type:none">_x000D_
<li><a href="#">India</a></li>_x000D_
<li><a href="#">USA</a></li>_x000D_
<li><a href="#">Russia</a></li>_x000D_
<li><a href="#">China</a></li>_x000D_
<li><a href="#">Afganistan</a></li>_x000D_
<li><a href="#">Landon</a></li>_x000D_
<li><a href="#">Scotland</a></li>_x000D_
<li><a href="#">Ireland</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
If You test app like me on localhost or You will have some problems with blank white page i use this:
ng build --prod --build-optimizer --base-href="http://127.0.0.1/my-app/"
Explanation:
ng build
Build app but in code there is many spaces, tabs and other stuff what makes code able be read by human. For server it isnt important how code looks. This is why i use:
ng build --prod --build-optimizer
This make code out for production and reduce size [--build-optimizer
] allow to reduce more code].
So at end i add --base-href="http://127.0.0.1/my-app/"
to show application where is 'main frame' [in simple words]. With it You can have even multiple angular apps in any folder.
To set a class completely, instead of adding one or removing one, use this:
$(this).attr("class","newclass");
Advantage of this is that you'll remove any class that might be set in there and reset it to how you like. At least this worked for me in one situation.
If you hafe upload your file in media than:
media
example-input-file.txt
views.py
def download_csv(request):
file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
urls.py
path('download_csv/', views.download_csv, name='download_csv'),
download.html
a href="{% url 'download_csv' %}" download=""
See response on this thread that has worked for me:
https://stackoverflow.com/a/62275293/11141700
NOTE - Additional STEP 3 that has made the difference for me compared to similar approaches suggested here
In short:
Step 1 - Generate config for Jupyter Notebook:
jupyter notebook --generate-config
Step 2 - Edit the config file using "nano" or other editor
The config fileshould be under your home directory under ".jupyter" folder:
~/.jupyter/jupyter_notebook_config.py
Step 3 - Disable launching browser by redirecting file
First comment out the line, then change True to False:
c.NotebookApp.use_redirect_file = False
Step 4 - add a line to your .bashrc file to set the BROWSER path
export BROWSER='/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'
For me it was Chrome under my Windows Program File. Otherwise any linux installation under WSL doesn't have a native browser to launch, so need to set it to the Windows executable.
Step 5 - restart .bashrc
source .bashrc
You can use the built-in forEach
function for arrays.
Like this:
//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
element.product_desc = element.product_desc.substring(0,10);
});
Your version wasn't wrong though. It should look more like this:
for(let i=0; i<data.products.length; i++){
console.log(data.products[i].product_desc); //use i instead of 0
}
For CentOS 7:
sudo yum install python36u-devel
I followed the instructions here for installing python3.6 on several VMs: https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-local-programming-environment-on-centos-7 and was then able to build mod_wsgi and get it working with a python3.6 virtualenv
window.location.href
returns the location of the current page.
top.location.href
(which is an alias of window.top.location.href
) returns the location of the topmost window in the window hierarchy. If a window has no parent, top
is a reference to itself (in other words, window
=== window.top
).
top
is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html
with the following script:
var newWin=window.open('about:blank','test','width=100,height=100');
newWin.document.write('<script>alert(top.location.href);</script>');
The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href
would return.
To answer your question about redirecting, go with window.location.assign(url);
You can get the current username on Windows by going through the Windows API, although it's a bit cumbersome to invoke via the ctypes FFI (GetCurrentProcess ? OpenProcessToken ? GetTokenInformation ? LookupAccountSid).
I wrote a small module that can do this straight from Python, getuser.py. Usage:
import getuser
print(getuser.lookup_username())
It works on both Windows and *nix (the latter uses the pwd
module as described in the other answers).
And just to give you yet another option, you can use NOT ISNULL(archived)
as your WHERE filter.
Pass the decode pattern to ParseExact
Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)
ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string
Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:
>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
That is of course a pain to write, so you can let broadcasting help you:
>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
This is much simpler to do if you index with arrays, not lists:
>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0, 2],
[ 4, 6],
[12, 14]])
Put this in the <head>
section:
<link rel="icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />
Keep the picture file named "favicon.ico". You'll have to look online to get a .ico file generator.
In the numpy README.txt file, it says
After installation, tests can be run with:
python -c 'import numpy; numpy.test()'
This should be a sufficient test for proper installation.
I've only ever seen CopyFile
fail with a "permission denied" error in one of these 3 scenarios:
Assuming input of
{Anything}id={ID}{space}{Anything}
{Anything}id={ID}{space}{Anything}
--
#! /bin/sh
while read s; do
rhs=${s##*id=}
id=${rhs%% *}
echo $id # Do what you will with $id here
done <so.txt
Or if it's always the 7th field
#! /bin/sh
while read f1 f2 f3 f4 f5 f6 f7 rest
do
echo ${f7##id=}
done <so.txt
See Also
In Visual Studio Code open 'user settings': ctrl + p
and type >sett
press enter
This will open default settings on left side and User settings on right side.
Just add path to git.exe in user settings
"git.path": "C:\\Users\\[WINDOWS_USER]\\AppData\\Local\\Programs\\Git\\bin\\git.exe"
Replace [WINDOWS_USER] with your user name.
Restart Visual Studio Code
Update
Original
var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");
string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding
request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;
var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();
You should look at Computed Properties
In your code sample, perimeter
is a property not backed up by a class variable, instead its value is computed using the get
method and stored via the set
method - usually referred to as getter and setter.
When you use that property like this:
var cp = myClass.perimeter
you are invoking the code contained in the get
code block, and when you use it like this:
myClass.perimeter = 5.0
you are invoking the code contained in the set
code block, where newValue
is automatically filled with the value provided at the right of the assignment operator.
Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.
Here is a solution to make an accessible audio player with valid xHTML and non-intrusive javascript thanks to W3C Web Audio API :
What to do :
First of all, we check if the browser implements Web Audio API:
if (typeof Audio === 'undefined') {
// abort
}
Then we instanciate an Audio
object:
var player = new Audio('mysong.ogg');
Then we can check if the browser is able to decode this type of file :
if(!player.canPlayType('audio/ogg')) {
// abort
}
Or even if it can play the codec :
if(!player.canPlayType('audio/ogg; codecs="vorbis"')) {
// abort
}
Then we can use player.play()
, player.pause()
;
I have done a tiny JQuery plugin that I called nanodio to test this.
You can check how it works on my demo page (sorry, but text is in french :p )
Just click on a link to play, and click again to pause. If the browser can read it natively, it will. If it can't, it should download the file.
This is just a little example, but you can improve it to use any element of your page as a control button or generate ones on the fly with javascript... Whatever you want.
The difference is that Java binaries compiled as x86 (32-bit) or x64 (64-bit) applications respectively.
On a 64-bit Windows you can use either version, since x86 will run in WOW64 mode. On a 32-bit Windows you should use only x86 obviously.
For a Linux you should select appropriate type x86 for 32-bit OS, and x64 for 64-bit OS.
I have resolved this issue in react by using it like this.
window.$('#modal-id').modal();
If I understand you correctly, You have two folders, one houses your php script that you want to include
into a file that is in another folder?
If this is the case, you just have to follow the trail the right way. Let's assume your folders are set up like this:
root
includes
php_scripts
script.php
blog
content
index.php
If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:
include("../../../includes/php_scripts/script.php");
The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.
Alternatively you can check connection status by logging into Mongo Atlas and then navigating to your cluster.
By POST file uploads are done (commonly, there are also other methods). Look into the method attribute of the form which contains the file-upload field ;)
The lowest limit of any related setting supersedes a higher setting:
See Handling file uploads: Common Pitfals which explains this in detail and how to calculate the values.
You are looking for:
db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();
A = zeros(20, 10, 3); %# Creates a 20x10x3 matrix
B = zeros(4,4);
C = zeros(size(B,1), size(B,2), 4); %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B; %# Copy the content of B into C's first set of values
zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0
for a 3D matrix. To confirm the size of your matrices you can run: size(A)
which gives 20 10 3
.
There is no explicit bound on the number of dimensions a matrix may have.
I had the same problem on Windows. I used to read the file in scala line by line with
Source.fromFile(path).getLines()
Now I read it as a whole with
import org.apache.commons.io.FileUtils._
// encoding is null for platform default
val content=readFileToString(new File(path),null.asInstanceOf[String])
which closes the file properly after reading and now
new File(path).delete
works.
declare this
var intro;
outside of $(document).ready()
because, $(document).ready()
will hide your variable from global scope.
Code
var intro;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
Another way:
window.intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
window.intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
window.intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
window.intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
console.log(intro);
outside of DOM ready function (currently you've) will log undefined
, but within DOM ready it will give you true/ false.
console.log
execute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.I need to use it outside of DOM ready function
You can use following approach:
var intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
introCheck();
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function() {
if (this.checked) {
intro = true;
} else {
intro = false;
}
introCheck();
});
});
function introCheck() {
console.log(intro);
}
After change the value of intro
I called a function that will fire with new value of intro
.
For me, these steps fixed the issue:
1- Running this cmd as admin:
npm install --global --production windows-build-tools
2- Then running npm rebuild
after the 1st step is completed (especially completing the python 2.7 installation, which was the main cause of the issue)
@vignesh the single quotes are only needed if you are using js variables
<iframe src = "https://maps.google.com/maps?q=10.305385,77.923029&hl=es;z=14&output=embed"></iframe>
You typically restore purchases with this code:
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
It will reinvoke -paymentQueue:updatedTransactions
on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.
Not all types of In-App purchases can be restored.
Now in the latest TortoiseGit on Windows you can do it very easily.
Open the rebase dialog, configure it, and do the following steps.
Edit
" (among pick, squash, delete...). Start
" to start rebasing. Edit/Split
" button and
click on "Amend
" directly. The commit dialog opens.commit
". Very helpful, thanks TortoiseGit !
simplest way to send parameters with the post request:
String postURL = "http://www.example.com/page.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(ent);
HttpClient client = new DefaultHttpClient();
HttpResponse responsePOST = client.execute(post);
You have done. now you can use responsePOST
.
Get response content as string:
BufferedReader reader = new BufferedReader(new InputStreamReader(responsePOST.getEntity().getContent()), 2048);
if (responsePOST != null) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(" line : " + line);
sb.append(line);
}
String getResponseString = "";
getResponseString = sb.toString();
//use server output getResponseString as string value.
}
I almost never create a table without a numeric primary key. If there is also a natural key that should be unique, I also put a unique index on it. Joins are faster on integers than multicolumn natural keys, data only needs to change in one place (natural keys tend to need to be updated which is a bad thing when it is in primary key - foreign key relationships). If you are going to need replication use a GUID instead of an integer, but for the most part I prefer a key that is user readable especially if they need to see it to distinguish between John Smith and John Smith.
The few times I don't create a surrogate key are when I have a joining table that is involved in a many-to-many relationship. In this case I declare both fields as the primary key.
After running into the same issue - here're some of my thoughts:
As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:
for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:
if (window.chrome)
$("[type=video\\\/mp4]").each(function()
{
$(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
});
Unfortunately it's a bad Chrome hack, but hey, at least it works.
Source: user: eithedog
This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec
Also check your version of crome here: html5test
SOLUTION:
Here is the solution. Executing a function after the user has stopped typing for a specified amount of time:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Usage
$('input').keyup(function() {
delay(function(){
alert('Hi, func called');
}, 1000 );
});
There is a way that's pretty memory inefficient.
single file:
import hashlib
def file_as_bytes(file):
with file:
return file.read()
print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()
list of files:
[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:
[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
If you only want 128 bits worth of digest you can do .digest()[:16]
.
This will give you a list of tuples, each tuple containing the name of its file and its hash.
Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.
Here is a way that is more complex, but memory efficient:
import hashlib
def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
for block in bytesiter:
hasher.update(block)
return hasher.hexdigest() if ashexstr else hasher.digest()
def file_as_blockiter(afile, blocksize=65536):
with afile:
block = afile.read(blocksize)
while len(block) > 0:
yield block
block = afile.read(blocksize)
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
for fname in fnamelst]
And, again, since MD5 is broken and should not really ever be used anymore:
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
for fname in fnamelst]
Again, you can put [:16]
after the call to hash_bytestr_iter(...)
if you only want 128 bits worth of digest.
The for loop is definitely more pythonic, as it uses Python's higher level built in functionality to convey what you're doing both more clearly and concisely. The overhead of range vs xrange, and assigning an unused i
variable, stem from the absence of a statement like Verilog's repeat
statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:
from itertools import repeat
for unused in repeat(None, 10):
del unused # redundant and inefficient, the name is clear enough
print "This is run 10 times"
Using repeat instead of range here is less clear because it's not as well known a function, and more complex because you need to import it. The main style guides if you need a reference are PEP 20 - The Zen of Python and PEP 8 - Style Guide for Python Code.
We also note that the for range version is an explicit example used in both the language reference and tutorial, although in that case the value is used. It does mean the form is bound to be more familiar than the while expansion of a C-style for loop.
Put simply, an lvalue is something that can appear on the left-hand side of an assignment, typically a variable or array element.
So if you define int *p
, then p
is an lvalue. p+1
, which is a valid expression, is not an lvalue.
If you're trying to add 1 to p
, the correct syntax is:
p = p + 1;
After trying so hard with bind, unbind, on, off, click, attr, removeAttr, prop I made it work. So, I have the following scenario: In my html i have NOT attached any inline onclick handlers.
Then in my Javascript i used the following to add an inline onclick handler:
$(element).attr('onclick','myFunction()');
To remove this at a later point from Javascript I used the following:
$(element).prop('onclick',null);
This is the way it worked for me to bind and unbind click events dinamically in Javascript. Remember NOT to insert any inline onclick handler in your elements.
this works very well (find tomcat processes and kill them forcibly)
ps -ef | grep tomcat | awk '{print $2}' | xargs kill -9
On what basis should the merging take place? Your question is rather vague. Also, I assume a, b, ..., f are supposed to be strings, that is, 'a', 'b', ..., 'f'.
>>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> x[3:6] = [''.join(x[3:6])]
>>> x
['a', 'b', 'c', 'def', 'g']
Check out the documentation on sequence types, specifically on mutable sequence types. And perhaps also on string methods.
Here is a similiar thing that I would like to share,
while you're working on Visual Studio you could get an error like:
'scanf': function or variable may be unsafe. Consider using
scanf_s
instead. To disable deprecation, use_CRT_SECURE_NO_WARNINGS
To prevent this, you should write it in the following format
A single character may be read as follows:
char c;
scanf_s("%c", &c, 1);
When multiple characters for non-null terminated strings are read, integers are used as the width specification and the buffer size.
char c[4];
scanf_s("%4c", &c, _countof(c));
If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s:
String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
Changed to:
SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......
Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.
If you go to TextFX
menu and go to TextFX Edit
, you will see a menu item Reindent C++ Code
.
That will also format C# code.
import UIKit
import SafariServices
let url = URL(string: "https://sprotechs.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
Lets put this baby to bed; tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:
Bottom line performance wise, use:
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
or
function isEmpty(obj) {
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }
return true;
}
Results under Node:
return (Object.keys(obj).length === 0)
for (var x in obj) { return false; }...
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }...
return ('{}' === JSON.stringify(obj))
Testing for Object with 0 keys 0.00018 0.000015 0.000015 0.000324
Testing for Object with 1 keys 0.000346 0.000458 0.000577 0.000657
Testing for Object with 2 keys 0.000375 0.00046 0.000565 0.000773
Testing for Object with 3 keys 0.000406 0.000476 0.000577 0.000904
Testing for Object with 4 keys 0.000435 0.000487 0.000589 0.001031
Testing for Object with 5 keys 0.000465 0.000501 0.000604 0.001148
Testing for Object with 6 keys 0.000492 0.000511 0.000618 0.001269
Testing for Object with 7 keys 0.000528 0.000527 0.000637 0.00138
Testing for Object with 8 keys 0.000565 0.000538 0.000647 0.00159
Testing for Object with 100 keys 0.003718 0.00243 0.002535 0.01381
Testing for Object with 1000 keys 0.0337 0.0193 0.0194 0.1337
Note that if your typical use case tests a non empty object with few keys, and rarely do you get to test empty objects or objects with 10 or more keys, consider the Object.keys(obj).length option. - otherwise go with the more generic (for... in...) implementation.
Note that Firefox seem to have a faster support for Object.keys(obj).length and Object.getOwnPropertyNames(obj).length, making it a better choice for any non empty Object, but still when it comes to empty objects, the (for...in...) is simply 10 times faster.
My 2 cents is that Object.keys(obj).length is a poor idea since it creates an object of keys just to count how many keys are inside, than destroys it! In order to create that object he needs to loop overt the keys... so why use it and not the (for... in...) option :)
var a = {};_x000D_
_x000D_
function timeit(func,count) {_x000D_
if (!count) count = 100000;_x000D_
var start = Date.now();_x000D_
for (i=0;i<count;i++) func();_x000D_
var end = Date.now();_x000D_
var duration = end - start;_x000D_
console.log(duration/count)_x000D_
}_x000D_
_x000D_
function isEmpty1() {_x000D_
return (Object.keys(a).length === 0)_x000D_
}_x000D_
function isEmpty2() {_x000D_
for (x in a) { return false; }_x000D_
return true;_x000D_
}_x000D_
function isEmpty3() {_x000D_
for (x in a) { if (a.hasOwnProperty(x)) return false; }_x000D_
return true;_x000D_
}_x000D_
function isEmpty4() {_x000D_
return ('{}' === JSON.stringify(a))_x000D_
}_x000D_
_x000D_
_x000D_
for (var j=0;j<10;j++) {_x000D_
a = {}_x000D_
for (var i=0;i<j;i++) a[i] = i;_x000D_
console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
timeit(isEmpty1);_x000D_
timeit(isEmpty2);_x000D_
timeit(isEmpty3);_x000D_
timeit(isEmpty4);_x000D_
}_x000D_
_x000D_
a = {}_x000D_
for (var i=0;i<100;i++) a[i] = i;_x000D_
console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
timeit(isEmpty1);_x000D_
timeit(isEmpty2);_x000D_
timeit(isEmpty3);_x000D_
timeit(isEmpty4, 10000);_x000D_
_x000D_
a = {}_x000D_
for (var i=0;i<1000;i++) a[i] = i;_x000D_
console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
timeit(isEmpty1,10000);_x000D_
timeit(isEmpty2,10000);_x000D_
timeit(isEmpty3,10000);_x000D_
timeit(isEmpty4,10000);
_x000D_
Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
You may need to set up a root account for your MySQL database:
In the terminal type:
mysqladmin -u root password 'root password goes here'
And then to invoke the MySQL client:
mysql -h localhost -u root -p
MySQL doesn't reduce the size of ibdata1. Ever. Even if you use optimize table
to free the space used from deleted records, it will reuse it later.
An alternative is to configure the server to use innodb_file_per_table
, but this will require a backup, drop database and restore. The positive side is that the .ibd file for the table is reduced after an optimize table
.
In .NET a POCO is a 'Plain old CLR Object'. It is not a 'Plain old C# object'...
You can also try http://image.online-convert.com/convert-to-svg
I always use it for my needs.
This eclipse plugin allows for inline source viewing and even stepping inside the Android source code:
http://code.google.com/p/adt-addons/
(edit: specifically the "Android Sources" plugin: http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/)
I had the same problem and here was my way to solve it:
First, You must know your IP address. On my Windows PC, in the cmd windows i run ipconfig and select my IP V4 address. In my case 192.168.0.13
Second as mention above: runserver 192.168.0.13:8000
It worked for me. The error i did to get the message was the use of the gateway address not my PC address.
The proper test is:
if (capital != null && capital.length < 1) {
This ensures that capital
is always non null, when you perform the length check.
Also, as the comments suggest, capital
is null
because you never initialize it.
You can use the collections.Counter. Note, this will work for both numeric and non-numeric values.
>>> x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
>>> from collections import Counter
>>> #To sort in reverse order
>>> Counter(x).most_common()
[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
>>> #To sort in ascending order
>>> Counter(x).most_common()[::-1]
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
>>> #To get a dictionary sorted by values
>>> from collections import OrderedDict
>>> OrderedDict(Counter(x).most_common()[::-1])
OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])
string replace() function perfectly solves this problem:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
Actually there is a simpler way to do this, just:
if ($("#input").is(':empty')) {
console.log('empty');
} else {
console.log('not empty');
}
src: https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/
I have a similar thing going. I have a lot of cases where I do:
thedict = {}
for item in ('foo', 'bar', 'baz'):
mydict = thedict.get(item, {})
mydict = get_value_for(item)
thedict[item] = mydict
But going many levels deep. It's the ".get(item, {})" that's the key as it'll make another dictionary if there isn't one already. Meanwhile, I've been thinking of ways to deal with this better. Right now, there's a lot of
value = mydict.get('foo', {}).get('bar', {}).get('baz', 0)
So instead, I made:
def dictgetter(thedict, default, *args):
totalargs = len(args)
for i,arg in enumerate(args):
if i+1 == totalargs:
thedict = thedict.get(arg, default)
else:
thedict = thedict.get(arg, {})
return thedict
Which has the same effect if you do:
value = dictgetter(mydict, 0, 'foo', 'bar', 'baz')
Better? I think so.
HashSet implementations are, of course, much much faster -- less overhead because there's no ordering. A good analysis of the various Set implementations in Java is provided at http://java.sun.com/docs/books/tutorial/collections/implementations/set.html.
The discussion there also points out an interesting 'middle ground' approach to the Tree vs Hash question. Java provides a LinkedHashSet, which is a HashSet with an "insertion-oriented" linked list running through it, that is, the last element in the linked list is also the most recently inserted into the Hash. This allows you to avoid the unruliness of an unordered hash without incurring the increased cost of a TreeSet.
I also had this problem, however, right-clicking on the model.tt file and running "Custom tool" didn't make any difference for me somehow, but a comment on the page Ghlouw linked to mentioned to use the menu item "BUILD > Transform All T4 Templates." which did it for me
Basic method for beginners like me.
public void loadDataToJtable(ArrayList<String> liste){
rows = table.getRowCount();
cols = table.getColumnCount();
for (int i = 0; i < rows ; i++) {
for ( int k = 0; k < cols ; k++) {
for (int h = 0; h < list1.size(); h++) {
String b = list1.get(h);
b = table.getValueAt(i, k).toString();
}
}
}
}
If I may I could give you some new code for the same task, in my code you can create a so called 'document'(not really)and it is saved, and can be opened up again. It is also stored as a string file though(not a document). Here is the code:
#include "iostream"
#include "windows.h"
#include "string"
#include "fstream"
using namespace std;
int main() {
string saveload;
cout << "---------------------------" << endl;
cout << "|enter 'text' to write your document |" << endl;
cout << "|enter 'open file' to open the document |" << endl;
cout << "----------------------------------------" << endl;
while (true){
getline(cin, saveload);
if (saveload == "open file"){
string filenamet;
cout << "file name? " << endl;
getline(cin, filenamet, '*');
ifstream loadFile;
loadFile.open(filenamet, ifstream::in);
cout << "the text you entered was: ";
while (loadFile.good()){
cout << (char)loadFile.get();
Sleep(100);
}
cout << "" << endl;
loadFile.close();
}
if (saveload == "text") {
string filename;
cout << "file name: " << endl;
getline(cin, filename,'*');
string textToSave;
cout << "Enter your text: " << endl;
getline(cin, textToSave,'*');
ofstream saveFile(filename);
saveFile << textToSave;
saveFile.close();
}
}
return 0;
}
Just take this code and change it to serve your purpose. DREAM BIG,THINK BIG, DO BIG
Initializing a simple array :
<?php $array1=array(10,20,30,40,50); ?>
Initializing array within array :
<?php $array2=array(6,"santosh","rahul",array("x","y","z")); ?>
Source : Sorce for the code
Try this method for uploading Image file from camera
package com.example.imageupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName,
final InputStream fin, String type) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
public boolean isChunked() {
return false;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
public Header getContentEncoding() {
return null;
}
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
Use of class for uploading
private void doFileUpload(File file_path) {
Log.d("Uri", "Do file path" + file_path);
try {
HttpClient client = new DefaultHttpClient();
//use your server path of php file
HttpPost post = new HttpPost(ServerUploadPath);
Log.d("ServerPath", "Path" + ServerUploadPath);
FileBody bin1 = new FileBody(file_path);
Log.d("Enter", "Filebody complete " + bin1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploaded_file", bin1);
reqEntity.addPart("email", new StringBody(useremail));
post.setEntity(reqEntity);
Log.d("Enter", "Image send complete");
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
Log.d("Enter", "Get Response");
try {
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
JSONObject jobj = new JSONObject(response_str);
result = jobj.getString("ResponseCode");
Log.e("Result", "...." + result);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
} catch (Exception e) {
Log.e("Upload Exception", "");
e.printStackTrace();
}
}
Service for uploading
<?php
$image_name = $_FILES["uploaded_file"]["name"];
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;
$flag=0;
if (file_exists("Images/".$new_image_name))
{
$msg=$new_image_name . " already exists."
header('Content-type: application/json');
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));
}else{
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
$flag = 1;
}
if($flag == 1){
require 'db.php';
$static_url =$new_image_name;
$conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
$db=mysql_select_db($db_database,$conn) or die("unable to select message_app");
$email = "";
if((isset($_REQUEST['email'])))
{
$email = $_REQUEST['email'];
}
$sql ="insert into alert(images) values('$static_url')";
$result=mysql_query($sql);
if($result){
echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
} else
{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
}
}
else{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
}
?>
in MySQL are
".myd" a database self and
".tmd" a temporal file.
But sometimes I see also ".sql".
It depends on your settings and/or export method.
If you want to echo it out for later execution it's ok
If you want to execute the JS and use the results in PHP use V8JS
V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
You can refer here for further reference: What are Extensions in php v8js?
If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution
As an alternative to Balu Mohan's answer, it is possible to enforce the order of the patterns using only grep
, head
and tail
:
for f in FILEGLOB; do tail $f -n +$(grep -n "pattern1" $f | head -n1 | cut -d : -f 1) 2>/dev/null | grep "pattern2" &>/dev/null && echo $f; done
This one isn't very pretty, though. Formatted more readably:
for f in FILEGLOB; do
tail $f -n +$(grep -n "pattern1" $f | head -n1 | cut -d : -f 1) 2>/dev/null \
| grep -q "pattern2" \
&& echo $f
done
This will print the names of all files where "pattern2"
appears after "pattern1"
, or where both appear on the same line:
$ echo "abc
def" > a.txt
$ echo "def
abc" > b.txt
$ echo "abcdef" > c.txt; echo "defabc" > d.txt
$ for f in *.txt; do tail $f -n +$(grep -n "abc" $f | head -n1 | cut -d : -f 1) 2>/dev/null | grep -q "def" && echo $f; done
a.txt
c.txt
d.txt
tail -n +i
- print all lines after the i
th, inclusivegrep -n
- prepend matching lines with their line numbershead -n1
- print only the first rowcut -d : -f 1
- print the first cut column using :
as the delimiter2>/dev/null
- silence tail
error output that occurs if the $()
expression returns emptygrep -q
- silence grep
and return immediately if a match is found, since we are only interested in the exit codeI just encountered this issue. My resolution was to update the system time by manually syncing to the time servers. To do this you can:
Adjust Date/Time
Internet Time
tabChange Settings
Update Now
In my case this was syncing incorrectly so I had to click it several times before it updated correctly. If it continues to update incorrectly you can even try using a different time server from the server drop-down.
When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe
I had to choose the following options to get the management Tools:
When I was done I had an option "SQL Server Management Studio" within my Start Menu.
Searching for "Management" pulled it up faster within the Start Menu.
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
Accoriding to EF6 (4,5 also) documentation: https://msdn.microsoft.com/en-us/data/hh949853#9
9.3 Context per request
Entity Framework’s contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience. Contexts are expected to be short lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible. In web scenarios it’s important to keep this in mind and not have a context for more than the duration of a single request. Similarly, in non-web scenarios, context should be discarded based on your understanding of the different levels of caching in the Entity Framework. Generally speaking, one should avoid having a context instance throughout the life of the application, as well as contexts per thread and static contexts.
I had to post as none of the above answers worked completely for me.
I am using Android Studio
classpath 'com.android.tools.build:gradle:1.5.0'
compileSdkVersion 23
buildToolsVersion "23.0.3"
Step 1: Download lastest jar file (http://www-eu.apache.org/dist//httpcomponents/httpclient/binary/httpcomponents-client-4.5.2-bin.zip)
Step 2: Copy paste the .jar file to the libs folder (create if does not exist already) in your module (can be app or library)
Step 3: Right click on the jar and "Add as Library". It will automatically add the jar file as a dependency in your module's gradle file
Step 4: Now automatically your problem will get resolved but in case you are using proguard in your app, it will give you warning about duplicate class files and won't let you build. It is a known bug and you need to add following to your proguard-rules
-dontwarn org.apache.commons.**
-keep class org.apache.http.** { *; }
-dontwarn org.apache.http.**
Good Luck!
The key checks for FAST REFRESH includes the following:
1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.
No 3 is easy to miss and worth highlighting here
one of the ways I used it :
protected List<Field> getFieldsWithJsonView(Class sourceClass, Class jsonViewName){
List<Field> fields = new ArrayList<>();
for (Field field : sourceClass.getDeclaredFields()) {
JsonView jsonViewAnnotation = field.getDeclaredAnnotation(JsonView.class);
if(jsonViewAnnotation!=null){
boolean jsonViewPresent = false;
Class[] viewNames = jsonViewAnnotation.value();
if(jsonViewName!=null && Arrays.asList(viewNames).contains(jsonViewName) ){
fields.add(field);
}
}
}
return fields;
}
There are very good examples here to start trying with, but all of them are based on adding some extra or external element like a "div" as a reference element to drag it, and calculate the new dimensions or position of the original element.
Here's an example that doesn't use any extra elements. We could add borders, padding or margin without affecting its operation. In this example we have not added color, nor any visual reference to the borders nor to the lower right corner as a clue where you can enlarge or reduce dimensions, but using the cursor around the resizable elements the clues appears!
let resizerForCenter = new Resizer('center')
resizerForCenter.initResizer()
See it in action with CodeSandbox:
In this example we use ES6, and a module that exports a class called Resizer. An example is worth a thousand words:
Or with the code snippet:
const html = document.querySelector('html')_x000D_
_x000D_
class Resizer {_x000D_
constructor(elemId) {_x000D_
this._elem = document.getElementById(elemId)_x000D_
/**_x000D_
* Stored binded context handlers for method passed to eventListeners!_x000D_
* _x000D_
* See: https://stackoverflow.com/questions/9720927/removing-event-listeners-as-class-prototype-functions_x000D_
*/_x000D_
this._checkBorderHandler = this._checkBorder.bind(this)_x000D_
this._doResizeHandler = this._doResize.bind(this)_x000D_
this._initResizerHandler = this.initResizer.bind(this)_x000D_
this._onResizeHandler = this._onResize.bind(this)_x000D_
}_x000D_
_x000D_
initResizer() {_x000D_
this.stopResizer()_x000D_
this._beginResizer()_x000D_
}_x000D_
_x000D_
_beginResizer() {_x000D_
this._elem.addEventListener('mousemove', this._checkBorderHandler, false)_x000D_
}_x000D_
_x000D_
stopResizer() {_x000D_
html.style.cursor = 'default'_x000D_
this._elem.style.cursor = 'default'_x000D_
_x000D_
window.removeEventListener('mousemove', this._doResizeHandler, false)_x000D_
window.removeEventListener('mouseup', this._initResizerHandler, false)_x000D_
_x000D_
this._elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
this._elem.removeEventListener('mousemove', this._checkBorderHandler, false)_x000D_
}_x000D_
_x000D_
_doResize(e) {_x000D_
let elem = this._elem_x000D_
_x000D_
let boxSizing = getComputedStyle(elem).boxSizing_x000D_
let borderRight = 0_x000D_
let borderLeft = 0_x000D_
let borderTop = 0_x000D_
let borderBottom = 0_x000D_
_x000D_
let paddingRight = 0_x000D_
let paddingLeft = 0_x000D_
let paddingTop = 0_x000D_
let paddingBottom = 0_x000D_
_x000D_
switch (boxSizing) {_x000D_
case 'content-box':_x000D_
paddingRight = parseInt(getComputedStyle(elem).paddingRight)_x000D_
paddingLeft = parseInt(getComputedStyle(elem).paddingLeft)_x000D_
paddingTop = parseInt(getComputedStyle(elem).paddingTop)_x000D_
paddingBottom = parseInt(getComputedStyle(elem).paddingBottom)_x000D_
break_x000D_
case 'border-box':_x000D_
borderRight = parseInt(getComputedStyle(elem).borderRight)_x000D_
borderLeft = parseInt(getComputedStyle(elem).borderLeft)_x000D_
borderTop = parseInt(getComputedStyle(elem).borderTop)_x000D_
borderBottom = parseInt(getComputedStyle(elem).borderBottom)_x000D_
break_x000D_
default: break_x000D_
}_x000D_
_x000D_
let horizontalAdjustment = (paddingRight + paddingLeft) - (borderRight + borderLeft)_x000D_
let verticalAdjustment = (paddingTop + paddingBottom) - (borderTop + borderBottom)_x000D_
_x000D_
let newWidth = elem.clientWidth + e.movementX - horizontalAdjustment + 'px'_x000D_
let newHeight = elem.clientHeight + e.movementY - verticalAdjustment + 'px'_x000D_
_x000D_
let cursorType = getComputedStyle(elem).cursor_x000D_
switch (cursorType) {_x000D_
case 'all-scroll':_x000D_
elem.style.width = newWidth_x000D_
elem.style.height = newHeight_x000D_
break_x000D_
case 'col-resize':_x000D_
elem.style.width = newWidth_x000D_
break_x000D_
case 'row-resize':_x000D_
elem.style.height = newHeight_x000D_
break_x000D_
default: break_x000D_
}_x000D_
}_x000D_
_x000D_
_onResize(e) {_x000D_
// On resizing state!_x000D_
let elem = e.target_x000D_
let newCursorType = undefined_x000D_
let cursorType = getComputedStyle(elem).cursor_x000D_
switch (cursorType) {_x000D_
case 'nwse-resize':_x000D_
newCursorType = 'all-scroll'_x000D_
break_x000D_
case 'ew-resize':_x000D_
newCursorType = 'col-resize'_x000D_
break_x000D_
case 'ns-resize':_x000D_
newCursorType = 'row-resize'_x000D_
break_x000D_
default: break_x000D_
}_x000D_
_x000D_
html.style.cursor = newCursorType // Avoid cursor's flickering _x000D_
elem.style.cursor = newCursorType_x000D_
_x000D_
// Remove what is not necessary, and could have side effects!_x000D_
elem.removeEventListener('mousemove', this._checkBorderHandler, false);_x000D_
_x000D_
// Events on resizing state_x000D_
/**_x000D_
* We do not apply the mousemove event on the elem to resize it, but to the window to prevent the mousemove from slippe out of the elem to resize. This work bc we calculate things based on the mouse position_x000D_
*/_x000D_
window.addEventListener('mousemove', this._doResizeHandler, false);_x000D_
window.addEventListener('mouseup', this._initResizerHandler, false);_x000D_
}_x000D_
_x000D_
_checkBorder(e) {_x000D_
const elem = e.target_x000D_
const borderSensitivity = 5_x000D_
const coor = getCoordenatesCursor(e)_x000D_
const onRightBorder = ((coor.x + borderSensitivity) > elem.scrollWidth)_x000D_
const onBottomBorder = ((coor.y + borderSensitivity) > elem.scrollHeight)_x000D_
const onBottomRightCorner = (onRightBorder && onBottomBorder)_x000D_
_x000D_
if (onBottomRightCorner) {_x000D_
elem.style.cursor = 'nwse-resize'_x000D_
} else if (onRightBorder) {_x000D_
elem.style.cursor = 'ew-resize'_x000D_
} else if (onBottomBorder) {_x000D_
elem.style.cursor = 'ns-resize'_x000D_
} else {_x000D_
elem.style.cursor = 'auto'_x000D_
}_x000D_
_x000D_
if (onRightBorder || onBottomBorder) {_x000D_
elem.addEventListener('mousedown', this._onResizeHandler, false)_x000D_
} else {_x000D_
elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
function getCoordenatesCursor(e) {_x000D_
let elem = e.target;_x000D_
_x000D_
// Get the Viewport-relative coordinates of cursor._x000D_
let viewportX = e.clientX_x000D_
let viewportY = e.clientY_x000D_
_x000D_
// Viewport-relative position of the target element._x000D_
let elemRectangle = elem.getBoundingClientRect()_x000D_
_x000D_
// The function returns the largest integer less than or equal to a given number._x000D_
let x = Math.floor(viewportX - elemRectangle.left) // - elem.scrollWidth_x000D_
let y = Math.floor(viewportY - elemRectangle.top) // - elem.scrollHeight_x000D_
_x000D_
return {x, y}_x000D_
}_x000D_
_x000D_
let resizerForCenter = new Resizer('center')_x000D_
resizerForCenter.initResizer()_x000D_
_x000D_
let resizerForLeft = new Resizer('left')_x000D_
resizerForLeft.initResizer()_x000D_
_x000D_
setTimeout(handler, 10000, true); // 10s_x000D_
_x000D_
function handler() {_x000D_
resizerForCenter.stopResizer()_x000D_
}
_x000D_
body {_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
/* box-sizing: border-box; */_x000D_
position: relative;_x000D_
float:left;_x000D_
overflow: hidden;_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
background-color: blueviolet;_x000D_
}_x000D_
#center {_x000D_
background-color:lawngreen ;_x000D_
}_x000D_
#right {_x000D_
background: blueviolet;_x000D_
}_x000D_
#wrapper {_x000D_
border: 5px solid hotpink;_x000D_
display: inline-block;_x000D_
_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
<title>Resizer v0.0.1</title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="wrapper">_x000D_
<div id="left">Left</div>_x000D_
<div id="center">Center</div>_x000D_
<div id="right">Right</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
I got stuck exactly with the same error with psycopg2
. It looks like I skipped a few steps while installing Python and related packages.
sudo apt-get install python-dev libpq-dev
pip install psycopg2
(In your case you need to replace psycopg2
with the package you have an issue with.)
It worked seamlessly.
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
In my case just run the command and worked like charm.
php artisan route:clear
Instead of isset()
you can use something shorter getting errors muted, it is @$_POST['field']
. Then, if the field is not set, you'll get no error printed on a page.
after writing the jquery code perform this validation in your route or in controller.
$.ajax({
url: "/id/edit",
data:
name:name,
method:'get',
success:function(data){
console.log(data);}
});
Route::get('/', function(){
if(Request::ajax()){
return 'it's ajax request';}
});
There are a couple of mysql functions you need to look into.
mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false
value. Like the below:
while ($row = mysql_fetch_array($query)){
print_r $row;
}
Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..)
to get the row in an associative array.
Links:
In your case,
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
die("BAD!");
}
if (mysql_num_rows($result)==1){
$row = mysql_fetch_array($result);
echo "user Id: " . $row['userid'];
}
else{
echo "not found!";
}
this syntax :
SELECT *
FROM tbl_directorylisting listing
WHERE (civilite_etudiant IS NULL)
worked for me in Microsoft SQL Server 2008 (SP3)
I had the same problem as the title of this question, so incase anyone else googles upon this question and wants to start MySql in 'skip-grant-tables' mode on Windows, here is what I did.
Stop the MySQL service through Administrator tools, Services.
Modify the my.ini configuration file (assuming default paths)
C:\Program Files\MySQL\MySQL Server 5.5\my.ini
or for MySQL version >= 5.6
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini
In the SERVER SECTION, under [mysqld], add the following line:
skip-grant-tables
so that you have
# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.
#
[mysqld]
skip-grant-tables
Start the service again and you should be able to log into your database without a password.
If you're downloading text then I'd recommend using the WebClient and get a streamreader to the text:
WebClient web = new WebClient();
System.IO.Stream stream = web.OpenRead("http://www.yoursite.com/resource.txt");
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
String text = reader.ReadToEnd();
}
If this is taking a long time then it is probably a network issue or a problem on the web server. Try opening the resource in a browser and see how long that takes. If the webpage is very large, you may want to look at streaming it in chunks rather than reading all the way to the end as in that example. Look at http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx to see how to read from a stream.
Someone pointed me to args4j lately which is annotation based. I really like it!
Just took a look over the mustache docs and they support "inverted sections" in which they state
they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list
http://mustache.github.io/mustache.5.html#Inverted-Sections
{{#value}}
value is true
{{/value}}
{{^value}}
value is false
{{/value}}
Your $(magicSelector)
could be $('td', this)
. This will grab all td
that are children of this
, which in your case is each tr
. This is the same as doing $(this).find('td')
.
$('td', this).each(function() {
// Logic
});
Another way to navigate to the location of a function definition would be to break in debugger somewhere you can access the function and enter the functions fully qualified name in the console. This will print the function definition in the console and give a link which on click opens the script location where the function is defined.
This error appeared for me after I ran pod install
command for the new dependencies. Along with those, React had also been installed. Therefore probably Xcode was confused for path. I removed these lines from PodFile and error was gone. Please note that those removed from here were already linked in Xcode.
target 'app' do
pod 'GoogleMaps'
pod 'Firebase/Auth', '~> 6.3.0'
pod 'Firebase/Database', '~> 6.3.0'
# Removed four pods below and it worked.
pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'
pod 'ReactNativePermissions', :path => '../node_modules/react-native-permissions'
pod 'react-native-image-resizer', :path => '../node_modules/react-native-image-resizer'
pod 'RNFS', :path => '../node_modules/react-native-fs'
end
import UserNotifications
Next, go to the project editor for your target, and in the General tab, look for the Linked Frameworks and Libraries section.
Click + and select UserNotifications.framework:
// iOS 12 support
if #available(iOS 12, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound, .provisional, .providesAppNotificationSettings, .criticalAlert]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 10 support
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
Use Notification delegate methods
// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("APNs device token: \(deviceTokenString)")
}
// Called when APNs failed to register the device for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Print the error to console (you should alert the user that registration failed)
print("APNs registration failed: \(error)")
}
For receiving push notification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(UIBackgroundFetchResult.noData)
}
Setting up push notifications is enabling the feature within Xcode 8 for your app. Simply go to the project editor for your target and then click on the Capabilities tab. Look for Push Notifications and toggle its value to ON.
Check below link for more Notification delegate methods
Handling Local and Remote Notifications UIApplicationDelegate - Handling Local and Remote Notifications
https://developer.apple.com/reference/uikit/uiapplicationdelegate
This works in latest Chrome, FireFox and Edge, but not IE11:
document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';
And if you want to ignore spaces around the title:
document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'
The important thing of table-layout: fixed is that the column widths are determined by the first row of the table.
So
if your table structure is as follow (standard table structure)
<table>
<thead>
<tr>
<th> First column </th>
<th> Second column </th>
<th> Third column </th>
</tr>
</thead>
<tbody>
<tr>
<td> First column </td>
<td> Second column </td>
<td> Third column </td>
</tr>
</tbody>
if you would like to give a width to second column then
<style>
table{
table-layout:fixed;
width: 100%;
}
table tr th:nth-child(2){
width: 60%;
}
</style>
Please look that we style the th not the td.
If a class does not explicitly define a private static final long serialVersionUID
in the code it will be autogenerated, and there is no guarantee that different machines will generate the same id; it looks like that is exactly what happened.
Also if the classes are different in any way (using different versions of the class) the autogenerated serialVersionUID
s will also be different.
From the Serializable
interface's docs:
If a serializable class does not explicitly declare a
serialVersionUID
, then the serialization runtime will calculate a defaultserialVersionUID
value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declareserialVersionUID
values, since the defaultserialVersionUID
computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpectedInvalidClassExceptions
during deserialization. Therefore, to guarantee a consistentserialVersionUID
value across different java compiler implementations, a serializable class must declare an explicitserialVersionUID
value. It is also strongly advised that explicitserialVersionUID
declarations use theprivate
modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID
fields are not useful as inherited members. Array classes cannot declare an explicitserialVersionUID
, so they always have the default computed value, but the requirement for matchingserialVersionUID
values is waived for array classes.
You should define a serialVersionUID
in the class definition, e.g.:
class MyClass implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
...
Your JAVA_HOME variable must be set to /usr/lib/jvm/java-6-openjdk and it must be available for the user that starts Jenkins.
From Kyle Strand comment:
As of April 2015 (I think), Jenkins requires Java7. Also note that the java binary path (JAVA) must be set to the correct version if the system default is still Java 6. Finally, for anyone wondering where these variables are set, it's in a config file listed with the installation instructions on the Jenkins webpage (e.g. for Debian it's /etc/default/jenkins).
After I have placed my dock to the right (see older answers), I still found the panels split vertically.
To split the panels horizontally - and even got more from your screen width - go to Settings (bottom right corner), and remove the check on 'Split panels vertically when docked to right'.
Now, you have all panels from left to right :p
Well, in general, recursion can be mimicked as iteration by simply using a storage variable. Note that recursion and iteration are generally equivalent; one can almost always be converted to the other. A tail-recursive function is very easily converted to an iterative one. Just make the accumulator variable a local one, and iterate instead of recurse. Here's an example in C++ (C were it not for the use of a default argument):
// tail-recursive
int factorial (int n, int acc = 1)
{
if (n == 1)
return acc;
else
return factorial(n - 1, acc * n);
}
// iterative
int factorial (int n)
{
int acc = 1;
for (; n > 1; --n)
acc *= n;
return acc;
}
Knowing me, I probably made a mistake in the code, but the idea is there.
I found myself requiring this functionality often enough that I packaged it into a library called std-pour. It should let you execute a command and view the output in real time. To install simply:
npm install std-pour
Then it's simple enough to execute a command and see the output in realtime:
const { pour } = require('std-pour');
pour('ping', ['8.8.8.8', '-c', '4']).then(code => console.log(`Error Code: ${code}`));
It's promised based so you can chain multiple commands. It's even function signature-compatible with child_process.spawn
so it should be a drop in replacement anywhere you're using it.
i had also encountered this issue. . This Solution worked for me....
windows->navigation->maximize active View or Editor(ctrl + M) . in the screen you can see on left side navigation menus ... now click on those buttons one by one ....you will get your solution...
Rather than the select itself, you could disable all of the options except for the currently selected option. This gives the appearance of a working drop-down, but only the option you want passed in is a valid selection.
JMX now uses port 7199 instead of port 8080 (as of Cassandra 0.8.xx).
This is configurable in your cassandra-env.sh file, but the default is 7199.
It looks like Microsoft has published some their drivers to maven central:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
string dateInString = "01.10.2009";
DateTime startDate = DateTime.Parse(dateInString);
DateTime expiryDate = startDate.AddDays(30);
if (DateTime.Now > expiryDate) {
//... trial expired
}
Have a look on code below. Tested and found working on Mobile and Tablet devices.
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
You should build your own Authorize-filter attribute.
Here's mine to study ;)
Public Class RequiresRoleAttribute : Inherits ActionFilterAttribute
Private _role As String
Public Property Role() As String
Get
Return Me._role
End Get
Set(ByVal value As String)
Me._role = value
End Set
End Property
Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
If Not String.IsNullOrEmpty(Me.Role) Then
If Not filterContext.HttpContext.User.Identity.IsAuthenticated Then
Dim redirectOnSuccess As String = filterContext.HttpContext.Request.Url.AbsolutePath
Dim redirectUrl As String = String.Format("?ReturnUrl={0}", redirectOnSuccess)
Dim loginUrl As String = FormsAuthentication.LoginUrl + redirectUrl
filterContext.HttpContext.Response.Redirect(loginUrl, True)
Else
Dim hasAccess As Boolean = filterContext.HttpContext.User.IsInRole(Me.Role)
If Not hasAccess Then
Throw New UnauthorizedAccessException("You don't have access to this page. Only " & Me.Role & " can view this page.")
End If
End If
Else
Throw New InvalidOperationException("No Role Specified")
End If
End Sub
End Class
I do not think that there is need to hack around the value and label properties, use hidden input fields or to suppress events. You may add your own custom property to each Autocomplete object and then read that property value later.
Here is an example.
$(#yourInputTextBox).autocomplete({
source: function(request, response) {
// Do something with request.term (what was keyed in by the user).
// It could be an AJAX call or some search from local data.
// To keep this part short, I will do some search from local data.
// Let's assume we get some results immediately, where
// results is an array containing objects with some id and name.
var results = yourSearchClass.search(request.term);
// Populate the array that will be passed to the response callback.
var autocompleteObjects = [];
for (var i = 0; i < results.length; i++) {
var object = {
// Used by jQuery Autocomplete to show
// autocomplete suggestions as well as
// the text in yourInputTextBox upon selection.
// Assign them to a value that you want the user to see.
value: results[i].name;
label: results[i].name;
// Put our own custom id here.
// If you want to, you can even put the result object.
id: results[i].id;
};
autocompleteObjects.push(object);
}
// Invoke the response callback.
response(autocompleteObjects);
},
select: function(event, ui) {
// Retrieve your id here and do something with it.
console.log(ui.item.id);
}
});
The documentation mentions you have to pass in an array of objects with label and value properties. However, you may certainly pass in objects with more than these two properties and read them later.
Here is the relevant part I am referring to.
Array: An array can be used for local data. There are two supported formats: An array of strings: [ "Choice1", "Choice2" ] An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ] The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.
Try to use toISOString(). It returns string in ISO8601 format.
GET method
javascript
$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
console.log(result);
});
c#
[HttpGet]
public JsonResult DoGet(DateTime date)
{
return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}
POST method
javascript
$.post('/example/do', { date: date.toISOString() }, function (result) {
console.log(result);
});
c#
[HttpPost]
public JsonResult Do(DateTime date)
{
return Json(date.ToString());
}
In android google maps application there is a very easy way to find distance between 2 locations, to do so follow the following easy steps:
when you first open the app go to " your timeline " from the drop menue on the top left.
once the new windwo opens, chose from the settings on your top right menue and choose "add place".
Good luck
You can find elements by available methods and check response array length if the length of an array equal the 0 element not exist.
element_exist = False if len(driver.find_elements_by_css_selector('div.eiCW-')) > 0 else True
I had a similar problem, and after spending so much time and lots of searching about this issue the only trick worked for me:
Android SDK Tool
(update it to latest version)Android SDK Platform-tools
(update it to latest version)Android SDK Build-tools
(update it to latest version)Android Support Repository
under Extra
folder (update it to latest version)Android API
as the installed Android SDK Build-tools
& Android SDK Platform-tools
version as shown in the Configure Required SDKs
figure above.Note: Local Maven repository for Support Libraries which is listed as the SDK requirement in the official docs of React-native is now named as Android Support Repository in the SDK Manager .
Edit
gulp-util
is deprecated and should be avoid, so it's recommended to use minimist instead, which gulp-util
already used.
So I've changed some lines in my gulpfile to remove gulp-util
:
var argv = require('minimist')(process.argv.slice(2));
gulp.task('styles', function() {
return gulp.src(['src/styles/' + (argv.theme || 'main') + '.scss'])
…
});
Original
In my project I use the following flag:
gulp styles --theme literature
Gulp offers an object gulp.env
for that. It's deprecated in newer versions, so you must use gulp-util for that. The tasks looks like this:
var util = require('gulp-util');
gulp.task('styles', function() {
return gulp.src(['src/styles/' + (util.env.theme ? util.env.theme : 'main') + '.scss'])
.pipe(compass({
config_file: './config.rb',
sass : 'src/styles',
css : 'dist/styles',
style : 'expanded'
}))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'ff 17', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(livereload(server))
.pipe(gulp.dest('dist/styles'))
.pipe(notify({ message: 'Styles task complete' }));
});
The environment setting is available during all subtasks. So I can use this flag on the watch task too:
gulp watch --theme literature
And my styles task also works.
Ciao Ralf
What about @Primary
?
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the
<bean>
element'sprimary
attribute in Spring XML.
@Primary
public class HibernateDeviceDao implements DeviceDao
Or if you want your Jdbc version to be used by default:
<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">
@Primary
is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.
The image you're using is Alpine based, so you can't use apt-get
because it's Ubuntu's package manager.
To fix this just use:
apk update
and apk add
If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.
Your query execution will return list of Object[]
.
List result_source = LoadSource.list();
for(Object[] objA : result_source) {
// read it all
}
Binary tree: Tree where each node has up to two leaves
1
/ \
2 3
Binary search tree: Used for searching. A binary tree where the left child contains only nodes with values less than the parent node, and where the right child only contains nodes with values greater than or equal to the parent.
2
/ \
1 3
In case of this similar error Warning: Error in $: object of type 'closure' is not subsettable [No stack trace available]
Just add corresponding package name using :: e.g.
instead of tags(....)
write shiny::tags(....)
You can put this configuration in your settings.xml file:
<repository>
<id>mvnrepository</id>
<url>http://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
There is one way to do this, as long as you have regular time intervals between all your date-time values - make the x-axis consider the values as text.
in Excel 2007, click on the chart - Go to the layout menu (contextual menu on clicking on the chart) , choose the option Axes->Primary Horizontal Axes-> More Horizontal Axes Options
Under Axis Type, choose "Text Axis"
If we have a code:
<div id="myDiv" class="myClass myClass2"></div>
to take class name by using jQuery we could define and use a simple plugin method:
$.fn.class = function(){
return Array.prototype.slice.call( $(this)[0].classList );
}
or
$.fn.class = function(){
return $(this).prop('class');
}
The use of the method will be:
$('#myDiv').class();
We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.
The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:
// [myClass, myClass2]
// "myClass myClass2"
Another important notice is that both methods as well as jQuery method
$('div').prop('class');
return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.
$('div:eq(2)').prop('class');
It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":
if($('#myDiv').hasClass('myClass')){
// do something
}
as mentioned in the comments above. But if you could need to take all classes as a selector, then use this code:
$.fn.classes = function(){
var o = $(this);
return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
}
var mySelector = $('#myDiv').classes();
The result will be:
// .myClass.myClass2
and you could get it to create dynamically a specific rewriting css rule for example.
Regards
You could try that XCode plugin https://github.com/benoitsan/BBUncrustifyPlugin-Xcode
Just clone github repository, open plugin project in XCode and run it. It will be installed automatically. Restart Xode before using formatter plugin.
Don't forget to install uncrustify util before. Homebrew, for exmaple
brew install uncrustify
P.S. You can turn on "after save formatting" feature at Edit > Format Code > BBUncrustifyPlugin Preferences > Format On Save
Hope this will be useful for u ;-)
Solution in Android Java:
Start your EditText, the ID is come to your xml id.
EditText myText = (EditText)findViewById(R.id.my_text_id);
in your OnCreate Method, just set the text by the name defined.
String text = "here put the text that you want"
use setText method from your editText.
myText.setText(text); //variable from point 2
I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads()
function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...
I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [
or curly {
bracket. No images formats I know of start with those characters.
Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.
Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
A good question. Should tell you it took some time to crack this one. Here is my result.
DECLARE @TABLE TABLE
(
ID INT,
USERS VARCHAR(10),
ACTIVITY VARCHAR(10),
PAGEURL VARCHAR(10)
)
INSERT INTO @TABLE
VALUES (1, 'Me', 'act1', 'ab'),
(2, 'Me', 'act1', 'cd'),
(3, 'You', 'act2', 'xy'),
(4, 'You', 'act2', 'st')
SELECT T1.USERS, T1.ACTIVITY,
STUFF(
(
SELECT ',' + T2.PAGEURL
FROM @TABLE T2
WHERE T1.USERS = T2.USERS
FOR XML PATH ('')
),1,1,'')
FROM @TABLE T1
GROUP BY T1.USERS, T1.ACTIVITY
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');_x000D_
_x000D_
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {_x000D_
if (err) throw new Error(err);_x000D_
console.log(res);_x000D_
});
_x000D_
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
I'm a bit confused about Javascript undefined & null.
null
generally behaves similarly to other scripting languages' concepts of the out-of-band ‘null’, ‘nil’ or ‘None’ objects.
undefined
, on the other hand, is a weird JavaScript quirk. It's a singleton object that represents out-of-band values, essentially a second similar-but-different null
. It comes up:
When you call a function with fewer arguments than the arguments list in the function
statement lists, the unpassed arguments are set to undefined
. You can test for that with eg.:
function dosomething(arg1, arg2) {
if (arg2===undefined)
arg2= DEFAULT_VALUE_FOR_ARG2;
...
}
With this method you can't tell the difference between dosomething(1)
and dosomething(1, undefined)
; arg2
will be the same value in both. If you need to tell the difference you can look at arguments.length
, but doing optional arguments like that isn't generally very readable.
When a function has no return value;
, it returns undefined
. There's generally no need to use such a return result.
When you declare a variable by having a var a
statement in a block, but haven't yet assigned a value to it, it is undefined
. Again, you shouldn't really ever need to rely on that.
The spooky typeof
operator returns 'undefined'
when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but not a full expression involving a non-existant variable.) Not much use for that, either.
This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an undefined
object. (And then when you try to use that undefined
object later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.)
This is often used to check for the existence of properties:
if (o.prop!==undefined) // or often as truthiness test, if (o.prop)
...do something...
However, because you can assign undefined
like any other value:
o.prop= undefined;
that doesn't actually detect whether the property is there reliably. Better to use the in
operator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now:
if ('prop' in o)
...
In summary, undefined
is a JavaScript-specific mess, which confuses everyone. Apart from optional function arguments, where JS has no other more elegant mechanism, undefined
should be avoided. It should never have been part of the language; null
would have worked just fine for (2) and (3), and (4) is a misfeature that only exists because in the beginning JavaScript had no exceptions.
what does
if (!testvar)
actually do? Does it test for undefined and null or just undefined?
Such a ‘truthiness’ test checks against false
, undefined
, null
, 0
, NaN
and empty strings. But in this case, yes, it is really undefined
it is concerned with. IMO, it should be more explicit about that and say if (testvar!==undefined)
.
once a variable is defined can I clear it back to undefined (therefore deleting the variable).
You can certainly assign undefined
to it, but that won't delete the variable. Only the delete object.property
operator really removes things.
delete
is really meant for properties rather than variables as such. Browsers will let you get away with straight delete variable
, but it's not a good idea and won't work in ECMAScript Fifth Edition's strict mode. If you want to free up a reference to something so it can be garbage-collected, it would be more usual to say variable= null
.
can I pass undefined as a parameter?
Yes.
NSNotificationCenter add observer syntax in Swift 4.0 for iOS 11
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
This is for keyboardWillShow notification name type. Other type can be selected from the available option
the Selector is of type @objc func which handle how the keyboard will show ( this is your user function )
You’ll want to do:
UIImage(data: data)
In Swift, they’ve replaced most Objective C factory methods with regular constructors.
See:
You can embed websites into another website using the <embed>
tag, like so:
<embed src="http://www.example.com" style="width:500px; height: 300px;">
You can change the height, width, and URL to suit your needs.
The <embed>
tag is the most up-to-date way to embed websites, as it was introduced with HTML5.
Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.
I didn't find anyone who is using string.Join to join strings using a separator. Everyone keeps writing the same ugly for-loop
var sb = new StringBuilder();
var count = list.Count();
for(int i = 0; i < count; i++)
{
if (sb.Length > 0) sb.Append(seperator);
sb.Append(list[i]);
}
return sb.ToString();
instead of
return string.Join(separator, list.ToArray());
You can peek into the information_schema
schema. It has a list of all tables and all fields that are in a table. You can then run queries using the information that you have gotten from this table.
The tables involved are SCHEMATA, TABLES and COLUMNS. There are foreign keys such that you can build up exactly how the tables are created in a schema.
I was having an issue more complex because I have more than one file with same name, one is in the main Spring Boot jar and others are in jars inside main fat jar. My solution was getting all the resources with same name and after that get the one I needed filtering by package name. To get all the files:
ResourceLoader resourceLoader = new FileSystemResourceLoader();
final Enumeration<URL> systemResources = resourceLoader.getClassLoader().getResources(fileNameWithoutExt + FILE_EXT);
When MS-DOS and Windows 3.1 operated in 16-bit mode, an Intel 8086 word was 16 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 16 bits.
When Windows NT operated in 32-bit mode, an Intel 80386 word was 32 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 32 bits. The names WORD and DWORD were no longer self-descriptive but they preserved the functionality of Microsoft programs.
When Windows operates in 64-bit mode, an Intel word is 64 bits, a Microsoft WORD is 16 bits, a Microsoft DWORD is 32 bits, and a typical compiler's unsigned int is 32 bits. The names WORD and DWORD are no longer self-descriptive, AND an unsigned int no longer conforms to the principle of least surprises, but they preserve the functionality of lots of programs.
I don't think WORD or DWORD will ever change.
I've encountered this problem with a input[type="datetime-local"]
, which is similar to this problem.
And I've found a way to overcome this kind of problems.
First, you must turn on chrome's shadow-root feature by "DevTools -> Settings -> General -> Elements -> Show user agent shadow DOM"
Then you can see all shadowed DOM elements, for example, for <input type="number">
, the full element with shadowed DOM is:
<input type="number">_x000D_
<div id="text-field-container" pseudo="-webkit-textfield-decoration-container">_x000D_
<div id="editing-view-port">_x000D_
<div id="inner-editor"></div>_x000D_
</div>_x000D_
<div pseudo="-webkit-inner-spin-button" id="spin"></div>_x000D_
</div>_x000D_
</input>
_x000D_
And according to these info, you can draft some CSS to hide unwanted elements, just as @Josh said.
The default dbpath for mongodb is /data/db
.
There is no default config file, so you will either need to specify this when starting mongod
with:
mongod --config /etc/mongodb.conf
.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.
Note: to check the dbpath and command-line options for a running mongod
, connect via the mongo
shell and run:
db.serverCmdLineOpts()
In particular, if a custom dbpath
is set it will be the value of:
db.serverCmdLineOpts().parsed.dbpath // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath // MongoDB 2.6+
In rpy2, the way to get the very same operator as "[" with R is to use ".rx". See the documentation about extracting with rpy2
For creating vectors, if you know your way around with Python there should not be any issue. See the documentation about creating vectors
I tried all the suggestions above, but my actual issue was that my application was looking for the /font folder and its contents (.woff etc) in app/fonts, but my /fonts folder was on the same level as /app. I moved /fonts under /app, and it works fine now. I hope this helps someone else roaming the web for an answer.
You see the behavior when your target element contains child elements:
Each time your mouse enters or leaves a child element, mouseover
is triggered, but not mouseenter
.
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
var el = $("#" + e.type);_x000D_
var n = +el.text();_x000D_
el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
padding: 0 20px 20px 0;_x000D_
background-color: #eee;_x000D_
margin-bottom: 10px;_x000D_
width: 90px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
float: left;_x000D_
margin: 20px 0 0 20px;_x000D_
height: 25px;_x000D_
width: 25px;_x000D_
background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
I have the exact same problem, and here is the solution I make use of now: (Note, this seems ideal to me because it keeps the files closely tied to the SinglePageApplication React app, that loads from Amazon S3. So, it's like storing on S3, and in an application, that knows where it is in S3, relatively speaking.
3 steps:
npm install file-saver
or something)public
folder, under a resource
or an asset
name. Webpack doesn't touch the public
folder and index.html
and your resources get copied over in production build as is, where you may refer them as shown in next step.import FileSaver from 'file-saver';
FileSaver.saveAs(
process.env.PUBLIC_URL + "/resource/file.anyType",
"fileNameYouWishCustomerToDownLoadAs.anyType");
Link
component of react-router
react-router-docs/Link. The zip file would download, and somehow would unzip properly. Generally, links have blue color, to inherit parent color scheme, simply add a prop like: style={color: inherit}
or simply assign a class of your CSS library like button button-primary
or something if you're Bootstrappin'There are two ways to do this.
1. providing the SHA of the commit you want to see to git log
git log -p a2c25061
Where -p
is short for patch
2. use git show
git show a2c25061
The output for both commands will be:
The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field will scroll appropriately. The default is unlimited.
<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />
However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.
header( 'Location: http://www.yoursite.com/new_page.html' );
in your process.php file
Install a trap handler to catch SIGINT, which kills off your child process if it's still alive, though other posters are correct that it won't catch SIGKILL.
Open a .lockfile with exclusive access and have the child poll on it trying to open it - if the open succeeds, the child process should exit
I resolved this issue by creating a file called .user.ini
in the directory where the PHP file scripts reside (this means any PHP script in this directory gets the new file size limit)
The contents of .user.ini
were:
upload_max_filesize = 40M
post_max_size = 40M
If you're using IIS Express, select Show All Application
from IIS Express in the task bar notification area, then select Stop All
.
Now re-run your application.
Well, in java, you can also create a parameterized enum. Say you want to create a className enum, in which you need to store classCode as well as className, you can do that like this:
public enum ClassEnum {
ONE(1, "One"),
TWO(2, "Two"),
THREE(3, "Three"),
FOUR(4, "Four"),
FIVE(5, "Five")
;
private int code;
private String name;
private ClassEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
}
This is what I came up with while working on a class that needed to write a dictionary in a .txt file:
@staticmethod
def _pretty_write_dict(dictionary):
def _nested(obj, level=1):
indentation_values = "\t" * level
indentation_braces = "\t" * (level - 1)
if isinstance(obj, dict):
return "{\n%(body)s%(indent_braces)s}" % {
"body": "".join("%(indent_values)s\'%(key)s\': %(value)s,\n" % {
"key": str(key),
"value": _nested(value, level + 1),
"indent_values": indentation_values
} for key, value in obj.items()),
"indent_braces": indentation_braces
}
if isinstance(obj, list):
return "[\n%(body)s\n%(indent_braces)s]" % {
"body": "".join("%(indent_values)s%(value)s,\n" % {
"value": _nested(value, level + 1),
"indent_values": indentation_values
} for value in obj),
"indent_braces": indentation_braces
}
else:
return "\'%(value)s\'" % {"value": str(obj)}
dict_text = _nested(dictionary)
return dict_text
Now, if we have a dictionary like this:
some_dict = {'default': {'ENGINE': [1, 2, 3, {'some_key': {'some_other_key': 'some_value'}}], 'NAME': 'some_db_name', 'PORT': '', 'HOST': 'localhost', 'USER': 'some_user_name', 'PASSWORD': 'some_password', 'OPTIONS': {'init_command': 'SET foreign_key_checks = 0;'}}}
And we do:
print(_pretty_write_dict(some_dict))
We get:
{
'default': {
'ENGINE': [
'1',
'2',
'3',
{
'some_key': {
'some_other_key': 'some_value',
},
},
],
'NAME': 'some_db_name',
'OPTIONS': {
'init_command': 'SET foreign_key_checks = 0;',
},
'HOST': 'localhost',
'USER': 'some_user_name',
'PASSWORD': 'some_password',
'PORT': '',
},
}
Perhaps this is obvious, but FWIW this will only work if the web server is serving requests for that website on the alternate port. It's not at all uncommon for a webserver to only serve a site on port 80.
If you are writing code for Node, using Node modules as described by Ivan is without a doubt the way to go.
However, if you need to load JavaScript that has already been written and isn't aware of node, the vm
module is the way to go (and definitely preferable to eval
).
For example, here is my execfile
module, which evaluates the script at path
in either context
or the global context:
var vm = require("vm");
var fs = require("fs");
module.exports = function(path, context) {
var data = fs.readFileSync(path);
vm.runInNewContext(data, context, path);
}
Also note: modules loaded with require(…)
don't have access to the global context.
fill_parent
will make the width or height of the element to be as
large as the parent element, in other words, the container.
wrap_content
will make the width or height be as large as needed to
contain the elements within it.
Raw Javascript can accomplish the same thing pretty quickly also:
document.getElementById("myElement").onclick = function() { return false; }
I had a similar problem setting up eclipse in the office. I had set up the for HTTP, HTTPS and SOCKS in:
Window>pref>general>network connections
Clearing the proxy settings for SOCKS fixed the problem for me.
You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for.
You can use a sub-query which contains an aggregate in the WHERE clause.
Taken from the ReactKonvaCore.d.ts file:
onClick?(evt: Konva.KonvaEventObject<MouseEvent>): void;
So, I'd say your event type is Konva.KonvaEventObject<MouseEvent>
Title, Short Description and Developer Name
Full Description and What’s New:
Also you can refer this..
Change your meta tag to the one below and use placeholder attribute inside your HTML input tag.
<meta http-equiv="X-UA-Compatible" content="IE=edge" />_x000D_
<input type="text" placeholder="Placeholder text" />?
_x000D_
You are mixing pointers and arrays. If what you want is an array, then use an array:
struct test {
static int data[10]; // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:
struct test {
static int *data;
};
// cpp
static int* generate_data() { // static here is "internal linkage"
int * p = new int[10];
for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
return p;
}
int *test::data = generate_data();
Just a note that the constant
keyword use for safe-area margins has been updated to env
for 11.2 beta+
https://webkit.org/blog/7929/designing-websites-for-iphone-x/
If you don't want to use a separate JS library to create a custom control for that, you could use two confirm
dialogs to do the checks:
if (confirm("Are you sure you want to quit?") ) {
if (confirm("Save your work before leaving?") ) {
// code here for save then leave (Yes)
} else {
//code here for no save but leave (No)
}
} else {
//code here for don't leave (Cancel)
}
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
Using the .not()
method with selecting an entire element is also an option.
This way could be usefull if you want to do another action with that element directly.
$(".thisClass").not($("#thisId")[0].doAnotherAction()).doAction();
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
XML file saved at res/values/colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="opaque_red">#f00</color>
<color name="translucent_red">#80ff0000</color>
</resources>
This application code retrieves the color resource:
Resources res = getResources();
int color = res.getColor(R.color.opaque_red);
This layout XML applies the color to an attribute:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/translucent_red"
android:text="Hello"/>
You can iterate over keys by calling map.keySet()
, or iterate over the entries by calling map.entrySet()
. Iterating over entries will probably be faster.
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
// Do things with the list
}
If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap
.
By the way, I'd recommend changing the declared type of the map to <String, List<String>>
. Always best to declare types in terms of the interface rather than the implementation.
If you have anaconda, you can just install desired version and conda will automatically downgrade the current package for you.
For example:
conda install tensorflow=1.1
We can solve this by using String Buffer String s;
static String timeConversion(String s) {
StringBuffer st=new StringBuffer(s);
for(int i=0;i<=st.length();i++){
if(st.charAt(0)=='0' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='0' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '4');
}else if(st.charAt(0)=='0' && st.charAt(1)=='3' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '5');
}else if(st.charAt(0)=='0' && st.charAt(1)=='4' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '6');
}else if(st.charAt(0)=='0' && st.charAt(1)=='5' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '7');
}else if(st.charAt(0)=='0' && st.charAt(1)=='6' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '8');
}else if(st.charAt(0)=='0' && st.charAt(1)=='7' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '9');
}else if(st.charAt(0)=='0' && st.charAt(1)=='8' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='0' && st.charAt(1)=='9' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '1');
}else if(st.charAt(0)=='1' && st.charAt(1)=='0' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '2');
}else if(st.charAt(0)=='1' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='A' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '0');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
st.setCharAt(0, '1');
st.setCharAt(1, '2');
}
if(st.charAt(8)=='P'){
st.setCharAt(8,' ');
}else if(st.charAt(8)== 'A'){
st.setCharAt(8,' ');
}
if(st.charAt(9)=='M'){
st.setCharAt(9,' ');
}
}
String result=st.toString();
return result;
}
There's no built-in command for it, so I usually just do something like this:
#!/bin/bash
# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {
# first revision as full text
echo
read r
svn log -r$r $url@HEAD
svn cat -r$r $url@HEAD
echo
# remaining revisions as differences to previous revision
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
Then, you can call it with:
history_of_file $1
The second loop involves a lot less cache activity, so it's easier for the processor to keep up with the memory demands.
It can also be used as below:
from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
HTML
<img id="close" className="fa fa-close" src="" alt="" title="Close Me" />
CSS
#close[title]:hover:after {
color: red;
content: attr(title);
position: absolute;
left: 50px;
}
Adding this to my redirect page fixed the problem for me ...
if (window.location.href.indexOf('#_=_') > 0) {
window.location = window.location.href.replace(/#.*/, '');
}
UPDATE 2020. React Native 0.63.3 no longer support this command react-native eject
. Also react-native upgrade
responsible for - Upgrade your app's template files to the specified or latest npm version using rn-diff-purge
project.
Available options can be found thought this command
react-native --help
docker run --rm -v /c/Users/Christian/manager/bin:/app --workdir=/app php:7.2-cli php app.php
Git bash
cd /c/Users/Christian/manager
docker run --rm -v ${PWD}:/app --workdir=/app php:7.2-cli php bin/app.php
echo ${PWD}
result:
/c/Users/Christian/manager
cmd or PowerShell
cd C:\Users\Christian\manager
echo ${PWD}
result:
Path ---- C:\Users\Christian\manager
as we see in cmd or PowerShell $ {PWD} will not work
ActiveModel::Dirty
didn't work for me because the @model.update_attributes()
hid the changes. So this is how I detected changes it in an update
method in a controller:
def update
@model = Model.find(params[:id])
detect_changes
if @model.update_attributes(params[:model])
do_stuff if attr_changed?
end
end
private
def detect_changes
@changed = []
@changed << :attr if @model.attr != params[:model][:attr]
end
def attr_changed?
@changed.include :attr
end
If you're trying to detect a lot of attribute changes it could get messy though. Probably shouldn't do this in a controller, but meh.
For multiple elements, you should give it a class rather than id eg:
<input type="text" class="task" name="task[]" />
Now you can get those using jquery something like this:
$('.task').each(function(){
alert($(this).val());
});
function cleanup_func {
sleep 0.5
echo cleanup
}
trap "exit \$exit_code" INT TERM
trap "exit_code=\$?; cleanup_func; kill 0" EXIT
# exit 1
# exit 0
Like https://stackoverflow.com/a/22644006/10082476, but with added exit-code
I got Darin's solution working eventually but made a few mistakes first which resulted in a problem similar to David (in the comments below Darin's solution) where the result was posting to a new page.
Because I had to do something with the form after the method returned, I stored it for later use:
var form = $(this);
However, this variable did not have the "action" or "method" properties which are used in the ajax call.
$(document).on("submit", "form", function (event) {
var form = $(this);
if (form.valid()) {
$.ajax({
url: form.action, // Not available to 'form' variable
type: form.method, // Not available to 'form' variable
data: form.serialize(),
success: function (html) {
// Do something with the returned html.
}
});
}
event.preventDefault();
});
Instead you need to use the "this" variable:
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (html) {
// Do something with the returned html.
}
});
To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).
Then I register a pre- or post-build event in Visual Studio...
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"
For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).
None of the solutions work if you are using Jenkins build!! When pom is run inside Jenkins build server.. these solutions will fail, as Jenkins run pom will try to download these files from enterprise repository.
Copy jars under src/main/resources/lib (create lib folder). These will be part of your project and go all the way to deployment server. In deployment server, make sure your startup scripts contain src/main/resources/lib/* in classpath. Viola.
Javac Reporter.java
java Reporter
Similarily, you can set it in windows environment variables. for example, in Win7
Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila
I use this query:
var collection = "countries"; var field = "country";
db[collection].distinct(field).forEach(function(value){print(field + ", " + value + ": " + db.hosts.count({[field]: value}))})
Output:
countries, England: 3536
countries, France: 238
countries, Australia: 1044
countries, Spain: 16
This query first distinct all the values, and then count for each one of them the number of occurrences.