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.
In my particular case, I fixed this error by looking in the Event Viewer to get a clue as to the source of the issue:
I then followed the steps outlined at Rebuilding Master Database in SQL Server.
Note: Take some good backups first. After erasing the master database, you will have to attach to all of your existing databases again by browsing to the
.mdf files
.
In my particular case, the command to rebuild the master database was:
C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\SQLServer2012>setup /ACTION=rebuilddatabase /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=mike /sapwd=[insert password]
Note that this will reset SQL server to its defaults, so you will have to hope that you can restore the master database from E:\backup\master.bak
. I couldn't find this file, so attached the existing databases (by browsing to the existing .mdf
files), and everything was back to normal.
After fixing everything, I created a maintenance plan to back up everything, including the master database, on a weekly basis.
In my particular case, this whole issue was caused by a Seagate hard drive getting bad sectors a couple of months after its 2-year warranty period expired. Most of the Seagate drives I have ever owned have ended up expiring either before or shortly after warranty - so I'm avoiding Seagate like the plague now!!
perhaps this comes too late, but still it could be nice to "document it" for others out there.
I received the same error after experimenting and testing with Remote Desktop Services on a MS Server 2012 with MS SQL Server 2012.
During the Remote Desktop Services install one is asked to create a (local) certificate, and so I did. After finishing the test/experiments I removed the Remote Desktop Services. That's when this error appeared (I cannot say whether the error occured during the test with RDS, I don't remember if I used/tried the SQL Connection during the RDS test).
I am not sure how to solve this since the default certificate does not work for me, but the "RDS" certificate does.
BTW, the certificates are found in App: "SQL Server Configuration Manager" -> "SQL Server Network Configuration" -> Right click: "Protocols for " -> Select "Properties" -> Tab "Certificate"
My default SQL Certificate is named: ConfigMgr SQL Server Identification Certificate, has expiration date: 2114-06-09.
Hope this can give a hint to others.
/Kim
Following Shane's answer above (which works great BTW)…
You might encounter a slew of yellow triangles in the reference list.
Most of these can be eliminated by a Build->Clean Solution
and Build->Rebuild Solution
.
I did happen to have some Google API references that were a little more stubborn...as well as NewtonSoft JSon.
Trying to reinstall the NuGet package of the same version didn't work.
Visual Studio thinks you already have it installed.
To get around this:
1: Write down the original version.
2: Install the next higher/lower version...then uninstall it.
3: Install the original version from step #1.
Using the ampersand (&) will run the command in a child process (child to the current bash session). However, when you exit the session, all child processes will be killed.
using nohup + ampersand (&) will do the same thing, except that when the session ends, the parent of the child process will be changed to "1" which is the "init" process, thus preserving the child from being killed.
here's a simple one
private boolean isFirst = true;
private void setAdapter() {
final ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Select your option");
spinnerArray.add("Option 1");
spinnerArray.add("Option 2");
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
TextView tv = (TextView)selectedItemView;
String res = tv.getText().toString().trim();
if (res.equals("Option 1")) {
//do Something
} else if (res.equals("Option 2")) {
//do Something else
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) { }
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_spinner_style,spinnerArray) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics());
((TextView) v).setTypeface(tf2);
((TextView) v).getLayoutParams().height = height;
((TextView) v).setGravity(Gravity.CENTER);
((TextView) v).setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
((TextView) v).setTextColor(Color.WHITE);
return v;
}
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
if (isFirst) {
isFirst = false;
spinnerArray.remove(0);
}
View v = super.getDropDownView(position, convertView, parent);
((TextView) v).setTextColor(Color.argb(255, 70, 70, 70));
((TextView) v).setTypeface(tf2);
((TextView) v).setGravity(Gravity.CENTER);
return v;
}
};
spin.setAdapter(adapter);
}
Check this: Why is the Android emulator so slow? How can we speed up the Android emulator?
Android Emulator is very slow on most computers, on that post you can read some suggestions to improve performance of emulator, or use android_x86 virtual machine
def sort_np_array(x, column=None, flip=False):
x = x[np.argsort(x[:, column])]
if flip:
x = np.flip(x, axis=0)
return x
Array in the original question:
a = np.array([[9, 2, 3],
[4, 5, 6],
[7, 0, 5]])
The result of the sort_np_array
function as expected by the author of the question:
sort_np_array(a, column=1, flip=False)
[2]: array([[7, 0, 5],
[9, 2, 3],
[4, 5, 6]])
I think awk
would be the best tool for this as it can both filter and perform the necessary string manipulation functions on filtered lines:
tail -f logfile | awk '/org.springframework/ {print substr($0, 6)}'
or
tail -f logfile | awk '/org.springframework/ && sub(/^.{5}/,"",$0)'
You can see Hive MetaStore tables,Partitions information in table of "PARTITIONS". You could use "TBLS" join "Partition" to query special table partitions.
date
as background dedicated processIn order to make this kind of translation a lot quicker...
In this post, you will find
bc
, rot13
, sed
...).fifo=$HOME/.fifoDate-$$
mkfifo $fifo
exec 5> >(exec stdbuf -o0 date -f - +%s >$fifo 2>&1)
echo now 1>&5
exec 6< $fifo
rm $fifo
read -t 1 -u 6 now
echo $now
This must output current UNIXTIME. From there, you could compare
time for i in {1..5000};do echo >&5 "now" ; read -t 1 -u6 ans;done
real 0m0.298s
user 0m0.132s
sys 0m0.096s
and:
time for i in {1..5000};do ans=$(date +%s -d "now");done
real 0m6.826s
user 0m0.256s
sys 0m1.364s
From more than 6 seconds to less than a half second!!(on my host).
You could check echo $ans
, replace "now"
by "2019-25-12 20:10:00"
and so on...
Optionaly, you could, once requirement of date subprocess ended:
exec 5>&- ; exec 6<&-
Instead of running 1 fork by date to convert, run date
just 1 time and do all convertion with same process (this could become a lot quicker)!:
date -f - +%s <<eof
Apr 17 2014
May 21 2012
Mar 8 00:07
Feb 11 00:09
eof
1397685600
1337551200
1520464020
1518304140
Sample:
start1=$(LANG=C ps ho lstart 1)
start2=$(LANG=C ps ho lstart $$)
dirchg=$(LANG=C date -r .)
read -p "A date: " userdate
{ read start1 ; read start2 ; read dirchg ; read userdate ;} < <(
date -f - +%s <<<"$start1"$'\n'"$start2"$'\n'"$dirchg"$'\n'"$userdate" )
Then now have a look:
declare -p start1 start2 dirchg userdate
(may answer something like:
declare -- start1="1518549549" declare -- start2="1520183716" declare -- dirchg="1520601919" declare -- userdate="1397685600"
This was done in one execution!
We just need one fifo:
mkfifo /tmp/myDateFifo
exec 7> >(exec stdbuf -o0 /bin/date -f - +%s >/tmp/myDateFifo)
exec 8</tmp/myDateFifo
rm /tmp/myDateFifo
(Note: As process is running and all descriptors are opened, we could safely remove fifo's filesystem entry.)
Then now:
LANG=C ps ho lstart 1 $$ >&7
read -u 8 start1
read -u 8 start2
LANG=C date -r . >&7
read -u 8 dirchg
read -p "Some date: " userdate
echo >&7 $userdate
read -u 8 userdate
We could buid a little function:
mydate() {
local var=$1;
shift;
echo >&7 $@
read -u 8 $var
}
mydate start1 $(LANG=C ps ho lstart 1)
echo $start1
newConnector
functionWith functions for connecting MySQL/MariaDB
, PostgreSQL
and SQLite
...
You may find them in different version on GitHub, or on my site: download or show.
wget https://raw.githubusercontent.com/F-Hauri/Connector-bash/master/shell_connector.bash
. shell_connector.bash
newConnector /bin/date '-f - +%s' @0 0
myDate "2018-1-1 12:00" test
echo $test
1514804400
Nota: On GitHub, functions and test are separated files. On my site test are run simply if this script is not sourced.
# Exit here if script is sourced
[ "$0" = "$BASH_SOURCE" ] || { true;return 0;}
When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:
return StatusCode(500, "My error");
Or
return StatusCode((int)HttpStatusCode.InternalServerError, "My error");
Or
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });
Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error:
in client side (ajax).
you can have ajax call like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
success: function (response) {
console.log("Custom message : " + response.responseText);
}, //Is Called when Status Code is 200[OK] or other Http success code
error: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
})
Additionally you can handle different HTTP errors from jQuery side like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
statusCode: {
500: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
501: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}
})
statusCode:
is useful when you want to call different functions for different status codes that you return from server.
You can see list of different Http Status codes here:Wikipedia
Additional resources:
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
Fixed! I basically just selected "Import" without even making a table myself. phpMyAdmin created the table for me, with all the right column names, from the original document.
In SQL Server , cast text as datetime
select cast('5/21/2013 9:45:48' as datetime)
Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
(which references 32-bit programs) for part of the name of the program, or
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
(if it actually was a 64-bit program).
If you find something that matches your program in one of those, the contents of UninstallString
in that key usually give you the exact command you are looking for (that you can run in a script).
If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.
Then in a .bat script you can do
if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)
You have two options:
Install cron as a windows service, using cygrunsrv:
cygrunsrv -I cron -p /usr/sbin/cron -a -n
net start cron
Note, in (very) old versions of cron you need to use -D instead of -n
The 'non .exe' files are probably bash scripts, so you can run them via the windows scheduler by invoking bash to run the script, e.g.:
C:\cygwin\bin\bash.exe -l -c "./full-path/to/script.sh"
On technologies with message loops (not sure if ASP is one of them), you can block the loop and process messages until the task is over, and use ContinueWith to unblock the code:
public void WaitForTask(Task task)
{
DispatcherFrame frame = new DispatcherFrame();
task.ContinueWith(t => frame.Continue = false));
Dispatcher.PushFrame(frame);
}
This approach is similar to blocking on ShowDialog and still keeping the UI responsive.
If using SQL Server 2012 or above;
SELECT DATEADD(MONTH, -1, DATEADD(DAY, 1, EOMONTH(GETDATE())))
Thanks for your great question, this has caught me out a few times. When using dataURI HTML source, I find that I have to define a complete HTML document.
See below a modified example.
var html = '<html><head></head><body>Foo</body></html>';
var iframe = document.createElement('iframe');
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
take note of the html content wrapped with <html>
tags and the iframe.src
string.
The iframe element needs to be added to the DOM tree to be parsed.
document.body.appendChild(iframe);
You will not be able to inspect the iframe.contentDocument
unless you disable-web-security
on your browser.
You'll get a message
DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://localhost:7357" from accessing a cross-origin frame.
Check also if the project has facet. The java version may be overriden there.
I don't believe it is. Firefox 2 trims long link titles anyway and they should really only be used to convey a small amount of help text. If you need more explanation text I would suggest that it belongs in a paragraph associated with the link. You could then add the tooltip javascript code to hide those paragraphs and show them as tooltips on hover. That's your best bet for getting it to work cross-browser IMO.
Option 1. To measure total time
:
curl -o /dev/null -s -w 'Total: %{time_total}s\n' https://www.google.com
Sample output:
Option 2. To get time to establish connection
, TTFB: time to first byte
and total time
:
curl -o /dev/null -s -w 'Establish Connection: %{time_connect}s\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n' https://www.google.com
Sample output:
I think this is the most reliable way to get the desktop path which isn't always the same as the username.
MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")
<div class="col-md-4 py-3 pic-card">
<div class="card ">
<div class="pic-overlay"></div>
<img class="img-fluid " src="images/Site Images/Health & Fitness-01.png" alt="">
<div class="centeredcard">
<h3>
<span class="card-headings">HEALTH & FITNESS</span>
</h3>
<div class="content-inner mt-5">
<p class="lead p-overlay">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae ipsam nemo quasi quo quae voluptate.</p>
</div>
</div>
</div>
</div>
.pic-card{
position: relative;
}
.pic-overlay{
top: 0;
left: 0;
right:0;
bottom:0;
width: 100%;
height: 100%;
position: absolute;
transition: background-color 0.5s ease;
}
.content-inner{
position: relative;
display: none;
}
.pic-card:hover{
.pic-overlay{
background-color: $dark-overlay;
}
.content-inner{
display: block;
cursor: pointer;
}
.card-headings{
font-size: 15px;
padding: 0;
}
.card-headings::after{
content: '';
width: 80%;
border-bottom: solid 2px rgb(52, 178, 179);
position: absolute;
left: 5%;
top: 25%;
z-index: 1;
}
.p-overlay{
font-size: 15px;
}
}
enter code here
Following is the function to resize bitmap by keeping the same Aspect Ratio. Here I have also written a detailed blog post on the topic to explain this method. Resize a Bitmap by Keeping the Same Aspect Ratio.
public static Bitmap resizeBitmap(Bitmap source, int maxLength) {
try {
if (source.getHeight() >= source.getWidth()) {
int targetHeight = maxLength;
if (source.getHeight() <= targetHeight) { // if image already smaller than the required height
return source;
}
double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
int targetWidth = (int) (targetHeight * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
}
return result;
} else {
int targetWidth = maxLength;
if (source.getWidth() <= targetWidth) { // if image already smaller than the required height
return source;
}
double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
int targetHeight = (int) (targetWidth * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
}
return result;
}
}
catch (Exception e)
{
return source;
}
}
My solution is a little verbose, but it handles variable positioning from the left edge for centered layouts.
// Ensurs that a element (usually a div) stays on the screen
// aElementToStick = The jQuery selector for the element to keep visible
global.makeSticky = function (aElementToStick) {
var $elementToStick = $(aElementToStick);
var top = $elementToStick.offset().top;
var origPosition = $elementToStick.css('position');
function positionFloater(a$Win) {
// Set the original position to allow the browser to adjust the horizontal position
$elementToStick.css('position', origPosition);
// Test how far down the page is scrolled
var scrollTop = a$Win.scrollTop();
// If the page is scrolled passed the top of the element make it stick to the top of the screen
if (top < scrollTop) {
// Get the horizontal position
var left = $elementToStick.offset().left;
// Set the positioning as fixed to hold it's position
$elementToStick.css('position', 'fixed');
// Reuse the horizontal positioning
$elementToStick.css('left', left);
// Hold the element at the top of the screen
$elementToStick.css('top', 0);
}
}
// Perform initial positioning
positionFloater($(window));
// Reposition when the window resizes
$(window).resize(function (e) {
positionFloater($(this));
});
// Reposition when the window scrolls
$(window).scroll(function (e) {
positionFloater($(this));
});
};
You need to pass the parameters, try this:
doskey np=notepad++.exe $*
Edit (responding to Romonov's comment) Q: Is there any way I can make the command prompt remember so I don't have to run this each time I open a new command prompt?
doskey
is a textual command that is interpreted by the command processor (e.g. cmd.exe), it can't know to modify state in some other process (especially one that hasn't started yet).
People that use doskey
to setup their initial command shell environments typically use the /K
option (often via a shortcut) to run a batch file which does all the common setup (like- set window's title, colors, etc).
cmd.exe /K env.cmd
env.cmd:
title "Foo Bar"
doskey np=notepad++.exe $*
...
Python 3.6 and newer have literal string interpolation using f-strings:
name='world'
print(f"Hello {name}!")
Your command is completely incorrect. The output format is not rawvideo
and you don't need the bitstream filter h264_mp4toannexb
which is used when you want to convert the h264
contained in an mp4
to the Annex B
format used by MPEG-TS
for example. What you want to use instead is the aac_adtstoasc
for the AAC
streams.
ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
Example for Windows (no extra dependencies and error handling)
const path = require('path');
const fs = require('fs');
let dir = "C:\\temp\\dir1\\dir2\\dir3";
function createDirRecursively(dir) {
if (!fs.existsSync(dir)) {
createDirRecursively(path.join(dir, ".."));
fs.mkdirSync(dir);
}
}
createDirRecursively(dir); //creates dir1\dir2\dir3 in C:\temp
I always liked this (you could modify as appropriate):
public static IEnumerable<TEnum> GetEnumValues()
{
Type enumType = typeof(TEnum);
if(!enumType.IsEnum)
throw new ArgumentException("Type argument must be Enum type");
Array enumValues = Enum.GetValues(enumType);
return enumValues.Cast<TEnum>();
}
You'd need to register DHTMLED.ocx
In case you use jQuery you need to wait for $(window).load
, because the embedded SVG document might not be yet loaded at $(document).ready
$(window).load(function () {
//alert("Document loaded, including graphics and embedded documents (like SVG)");
var a = document.getElementById("alphasvg");
//get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
//get the inner element by id
var delta = svgDoc.getElementById("delta");
delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});
Try this for a friendly representation of time differences (in milliseconds):
String friendlyTimeDiff(long timeDifferenceMilliseconds) {
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = timeDifferenceMilliseconds / ((long)60 * 60 * 1000 * 24 * 365);
if (diffSeconds < 1) {
return "less than a second";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds";
} else if (diffHours < 1) {
return diffMinutes + " minutes";
} else if (diffDays < 1) {
return diffHours + " hours";
} else if (diffWeeks < 1) {
return diffDays + " days";
} else if (diffMonths < 1) {
return diffWeeks + " weeks";
} else if (diffYears < 1) {
return diffMonths + " months";
} else {
return diffYears + " years";
}
}
It must be here, because accepted answer from 2012
In 2018 and modern browsers you can send a custom event from iframe to parent window.
iframe:
var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)
parent:
window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
console.log(e.detail) // outputs: {foo: 'bar'}
}
PS: Of course, you can send events in opposite direction same way.
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
I was appalled at the clumsiness of the CLASSPATH, JAVA_HOME, and PATH ideas, in Windows, to keep track of Java files. I got here, because of multiple JREs, and how to content with it. Without regurgitating information, from a guy much more clever than me, I would rather point to to his article on this issue, which for me, resolves it perfectly.
Article by: Ted Neward: Multiple Java Homes: Giving Java Apps Their Own JRE
With the exponential growth of Java as a server-side development language has come an equivablent exponential growth in Java development tools, environments, frameworks, and extensions. Unfortunately, not all of these tools play nicely together under the same Java VM installation. Some require a Servlet 2.1-compliant environment, some require 2.2. Some only run under JDK 1.2 or above, some under JDK 1.1 (and no higher). Some require the "com.sun.swing" packages from pre-Swing 1.0 days, others require the "javax.swing" package names.
Worse yet, this problem can be found even within the corporate enterprise, as systems developed using Java from just six months ago may suddenly "not work" due to the installation of some Java Extension required by a new (seemingly unrelated) application release. This can complicate deployment of Java applications across the corporation, and lead customers to wonder precisely why, five years after the start of the infamous "Installing-this-app-breaks-my-system" woes began with Microsoft's DLL schemes, we still haven't progressed much beyond that. (In fact, the new .NET initiative actually seeks to solve the infamous "DLL-Hell" problem just described.)
This paper describes how to configure a Java installation such that a given application receives its own, private, JRE, allowing multiple Java environments to coexist without driving customers (or system administrators) insane...
You can use now()
like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
Alternatively, you can use requests.Session
and observe cookies
before and after a request:
>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}
I find the Code Metrics and Dependency Structure Matrix add-ins for Reflector very useful.
>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()
where a is your x data b is your y data c is your y error if any
note that c is the error in each direction already
just as a .crt file is in .pem format, a .key file is also stored in .pem format. Assuming that the cert is the only thing in the .crt file (there may be root certs in there), you can just change the name to .pem. The same goes for a .key file. Which means of course that you can rename the .pem file to .key.
Which makes gtrig's answer the correct one. I just thought I'd explain why.
This will help you.
debugger;
var today = new Date();
document.getElementById('date').innerHTML = today
$('.list-toggle').click(function() {
var $listSort = $('.list-sort');
if ($listSort.attr('colspan')) {
$listSort.removeAttr('colspan');
} else {
$listSort.attr('colspan', 6);
}
});
Here's a working fiddle example.
See the answer by @RienNeVaPlus below for a more elegant solution.
When you use a TemplateField and bind literal text to it like you are doing, asp.net will actually insert a control FOR YOU! It gets put into a DataBoundLiteralControl. You can see this if you look in the debugger near your line of code that is getting the empty text.
So, to access the information without changing your template to use a control, you would cast like this:
string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;
That will get you your text!
i tried this clean easy method and seems to work in all browsers. Inside the svg file:
<svg>_x000D_
<a id="anchor" xlink:href="http://www.google.com" target="_top">_x000D_
_x000D_
<!--your graphic-->_x000D_
_x000D_
</a>_x000D_
</svg>_x000D_
_x000D_
For Apache HttpClient 4.5 or newer version:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://targethost/login");
String JSON_STRING="";
HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
Note:
1 in order to make the code compile, both httpclient
package and httpcore
package should be imported.
2 try-catch block has been ommitted.
Reference: appache official guide
the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules
In your pg_hba.conf file, I see some incorrect and confusing lines:
# fine, this allows all dbs, all users, to be trusted from 192.168.0.1/32
# not recommend because of the lax permissions
host all all 192.168.0.1/32 trust
# wrong, /128 is an invalid netmask for ipv4, this line should be removed
host all all 192.168.0.1/128 trust
# this conflicts with the first line
# it says that that the password should be md5 and not plaintext
# I think the first line should be removed
host all all 192.168.0.1/32 md5
# this is fine except is it unnecessary because of the previous line
# which allows any user and any database to connect with md5 password
host chaosLRdb postgres 192.168.0.1/32 md5
# wrong, on local lines, an IP cannot be specified
# remove the 4th column
local all all 192.168.0.1/32 trust
I suspect that if you md5'd the password, this might work if you trim the lines. To get the md5 you can use perl or the following shell script:
echo -n 'chaos123' | md5sum
> d6766c33ba6cf0bb249b37151b068f10 -
So then your connect line would like something like:
my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433",
"chaosuser", "d6766c33ba6cf0bb249b37151b068f10");
For more information, here's the documentation of postgres 8.X's pg_hba.conf file.
Both methods do the same functionally - they compare values.
As is written on MSDN:
String.Equals
method - Determines whether this instance and
another specified String object have the same value. (http://msdn.microsoft.com/en-us/library/858x0yyx.aspx)==
- Although string is a reference type, the equality operators (==
and
!=
) are defined to compare the values of string objects, not
references. This makes testing for string equality more intuitive. (http://msdn.microsoft.com/en-en/library/362314fe.aspx)But if one of your string instances is null, these methods are working differently:
string x = null;
string y = "qq";
if (x == y) // returns false
MessageBox.Show("true");
else
MessageBox.Show("false");
if (x.Equals(y)) // returns System.NullReferenceException: Object reference not set to an instance of an object. - because x is null !!!
MessageBox.Show("true");
else
MessageBox.Show("false");
/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$
1st Capturing Group (.+)
.+
matches any character (except for line terminators)
+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)2nd Capturing Group (\d{4}-\d{2}-\d{2})
\d{4}
matches a digit (equal to [0-9]
)
{4}
Quantifier — Matches exactly 4 times-
matches the character -
literally (case sensitive)
\d{2}
matches a digit (equal to [0-9]
)
{2}
Quantifier — Matches exactly 2 times-
matches the character -
literally (case sensitive)
\d{2}
matches a digit (equal to [0-9]
)
{2}
Quantifier — Matches exactly 2 times-
matches the character -
literally (case sensitive)
3rd Capturing Group (\d+)
\d+
matches a digit (equal to [0-9]
)
+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)4th Capturing Group (.*)?
?
Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
.*
matches any character (except for line terminators)
*
Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)$
asserts position at the end of the string
# Write a Python program that accepts a string and calculate the number of digits
# andletters.
stre =input("enter the string-->")
countl = 0
countn = 0
counto = 0
for i in stre:
if i.isalpha():
countl += 1
elif i.isdigit():
countn += 1
else:
counto += 1
print("The number of letters are --", countl)
print("The number of numbers are --", countn)
print("The number of characters are --", counto)
**#include<fstream> //to use file
#include<string> //to use getline
using namespace std;
int main(){
ifstream file;
string str;
file.open("path the file" , ios::binary | ios::in);
while(true){
getline(file , str);
if(file.fail())
break;
cout<<str;
}
}**
Since START is the only way to execute something in the background from a CMD script, I would recommend you keep using it. Instead of the /B modifier, try /MIN so the newly created window won't bother you. Also, you can set the priority to something lower with /LOW or /BELOWNORMAL, which should improve your system responsiveness.
Add the following to your ~/.gitconfig
file
[alias]
cat = "!git show \"$1:$2\" #"
And then try this
git cat BRANCHNAME FILEPATH
Personally I prefer separate parameters without a colon. Why? This choice mirrors the parameters of the checkout
command, which I tend to use rather frequently and I find it thus much easier to remember than the bizarro colon-separated parameter of the show
command.
Just to add some performance insights.
A few years ago I had a project, where we had issues trying to set a large HTML / Text to various HTML elements.
It appeared, that "recreating" the element and injecting it to the DOM was way faster than any of the suggested methods to update the DOM content.
So something like:
var text = "very big content";_x000D_
$("#regTitle").remove();_x000D_
$("<div id='regTitle'>" + text + "</div>").appendTo("body");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Should get you a better performance. I haven't recently tried to measure that (browsers should be clever these days), but if you're looking for performance it may help.
The downside is that you will have more work to keep the DOM and the references in your scripts pointing to the right object.
Here's an answer, based on (and I think an improvement on) Tester101's answer, expressed as a subroutine, with the CopyFile line once instead of three times, and prepared to handle changing the file name as the copy is made (no hard-coded destination directory). I also found I had to delete the target file before copying to get this to work, but that might be a Windows 7 thing. The WScript.Echo statements are because I didn't have a debugger and can of course be removed if desired.
Sub CopyFile(SourceFile, DestinationFile)
Set fso = CreateObject("Scripting.FileSystemObject")
'Check to see if the file already exists in the destination folder
Dim wasReadOnly
wasReadOnly = False
If fso.FileExists(DestinationFile) Then
'Check to see if the file is read-only
If fso.GetFile(DestinationFile).Attributes And 1 Then
'The file exists and is read-only.
WScript.Echo "Removing the read-only attribute"
'Remove the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
wasReadOnly = True
End If
WScript.Echo "Deleting the file"
fso.DeleteFile DestinationFile, True
End If
'Copy the file
WScript.Echo "Copying " & SourceFile & " to " & DestinationFile
fso.CopyFile SourceFile, DestinationFile, True
If wasReadOnly Then
'Reapply the read-only attribute
fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
End If
Set fso = Nothing
End Sub
To add an Activity
using Android Studio.
This step is same as adding Fragment, Service, Widget, and etc. Screenshot provided.
[UPDATE] Android Studio 3.5. Note that I have removed the steps for the older version. I assume almost all is using version 3.x.
To add a Service
, or a BroadcastReceiver
, just do the same step.
More simple: SELECT max(id) FROM client
As far as I can tell, this is a bug in setuptools where it isn't removing the setuptools specific options before calling up to the base class in the standard library: https://bitbucket.org/pypa/setuptools/issue/29/avoid-userwarnings-emitted-when-calling
If you have an unconditional import setuptools
in your setup.py
(as you should if using the setuptools specific options), then the fact the script isn't failing with ImportError
indicates that setuptools is properly installed.
You can silence the warning as follows:
python -W ignore::UserWarning:distutils.dist setup.py <any-other-args>
Only do this if you use the unconditional import that will fail completely if setuptools isn't installed :)
(I'm seeing this same behaviour in a checkout from the post-merger setuptools repo, which is why I'm confident it's a setuptools bug rather than a system config problem. I expect pre-merge distribute would have the same problem)
In my case, I have used 2 different context with Unitofwork and Ioc container so i see this problem insistanting while service layer try to make inject second repository to DI. The reason is that exist module has containing other module instance and container supposed to gettng a call from not constractured new repository.. i write here for whome in my shooes
That doesn't work because the second parameter should be a mapped entity and of course Integer is not a persistent class (since it doesn't have the @Entity annotation on it).
for you you should do the following:
Query q = em.createNativeQuery("select id from users where username = :username");
q.setParameter("username", "lt");
List<BigDecimal> values = q.getResultList();
or if you want to use HQL you can do something like this:
Query q = em.createQuery("select new Integer(id) from users where username = :username");
q.setParameter("username", "lt");
List<Integer> values = q.getResultList();
Regards.
They are equivalent. See this code:
mySlice1 := make([]int, 0)
mySlice2 := []int{}
fmt.Println("mySlice1", cap(mySlice1))
fmt.Println("mySlice2", cap(mySlice2))
Output:
mySlice1 0
mySlice2 0
Both slices have 0
capacity which implies both slices have 0
length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.
See similar questions:
What is the point of having nil slice and empty slice in golang?
I found this courtesy of ryanfait.com. It's actually remarkably simple.
In order to float a footer to the bottom of the page when content is shorter than window-height, or at the bottom of the content when it is longer than window-height, utilize the following code:
Basic HTML structure:
<div id="content">
Place your content here.
<div id="push"></div>
</div>
<div id="footer">
Place your footer information here.
</footer>
Note: Nothing should be placed outside the '#content' and '#footer' divs unless it is absolutely positioned.
Note: Nothing should be placed inside the '#push' div as it will be hidden.
And the CSS:
* {
margin: 0;
}
html, body {
height: 100%;
}
#content {
min-height: 100%;
height: auto !important; /*min-height hack*/
height: 100%; /*min-height hack*/
margin-bottom: -4em; /*Negates #push on longer pages*/
}
#footer, #push {
height: 4em;
}
To make headers or footers span the width of a page, you must absolutely position the header.
Note: If you add a page-width header, I found it necessary to add an extra wrapper div to #content. The outer div controls horizontal spacing while the inner div controls vertical spacing. I was required to do this because I found that 'min-height:' works only on the body of an element and adds padding to the height.
*Edit: missing semicolon
The proof answers are good, but I always have to do a few iterations by hand to really convince myself. So I drew out a small calling tree on my whiteboard, and started counting the nodes. I split my counts out into total nodes, leaf nodes, and interior nodes. Here's what I got:
IN | OUT | TOT | LEAF | INT
1 | 1 | 1 | 1 | 0
2 | 1 | 1 | 1 | 0
3 | 2 | 3 | 2 | 1
4 | 3 | 5 | 3 | 2
5 | 5 | 9 | 5 | 4
6 | 8 | 15 | 8 | 7
7 | 13 | 25 | 13 | 12
8 | 21 | 41 | 21 | 20
9 | 34 | 67 | 34 | 33
10 | 55 | 109 | 55 | 54
What immediately leaps out is that the number of leaf nodes is fib(n)
. What took a few more iterations to notice is that the number of interior nodes is fib(n) - 1
. Therefore the total number of nodes is 2 * fib(n) - 1
.
Since you drop the coefficients when classifying computational complexity, the final answer is ?(fib(n))
.
You can get html out of an iframe using this code iframe = document.getElementById('frame'); innerHtml = iframe.contentDocument.documentElement.innerHTML
This error can occur if you project is compiling with JDK 1.6 and you have dependencies compiled with Java 7.
Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
fn
literally refers to the jquery prototype
.
This line of code is in the source code:
jQuery.fn = jQuery.prototype = {
//list of functions available to the jQuery api
}
But the real tool behind fn
is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this
will refer to the jquery object.
$.fn.myExtension = function(){
var currentjQueryObject = this;
//work with currentObject
return this;//you can include this if you would like to support chaining
};
So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.
jsFiddle Demo
$.fn.blueBorder = function(){
this.each(function(){
$(this).css("border","solid blue 2px");
});
return this;
};
$.fn.blueText = function(){
this.each(function(){
$(this).css("color","blue");
});
return this;
};
Now you can use those against a class like this:
$('.blue').blueBorder().blueText();
(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)
This answer has a good example of a full fledged extension.
Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.
Install:
$ npm install cors
const cors = require('cors');
app.use(cors());
You have to put this code in your node server.
[Updated Dec 2020]: Tested and Included 5.0
version of Bootstrap.
I know this question is old. And the question did not mentioned which version of Bootstrap he was using. So i'll assume the answer to this question is resolved.
If any of you (like me) stumbled upon this question and looking for answer using current bootstrap 5.0 (2020) and 4.5 (2019) framework, then here's the solution.
Use d-flex justify-content-center
on your column div. This will center everything inside that column.
<div class="row">
<div class="col-4 d-flex justify-content-center">
// Image
</div>
</div>
If you want to align the text inside the col just use text-center
<div class="row">
<div class="col-4 text-center">
// text only
</div>
</div>
If you have text and image inside the column, you need to use d-flex
justify-content-center
and text-center
.
<div class="row">
<div class="col-4 d-flex justify-content-center text-center">
// for image and text
</div>
</div>
This is my solution for the problem. You can 'implement' multiple interfaces by overriding one Interface with another.
class MyInterface {
// Declare your JS doc in the Interface to make it acceable while writing the Class and for later inheritance
/**
* Gives the sum of the given Numbers
* @param {Number} a The first Number
* @param {Number} b The second Number
* @return {Number} The sum of the Numbers
*/
sum(a, b) { this._WARNING('sum(a, b)'); }
// delcare a warning generator to notice if a method of the interface is not overridden
// Needs the function name of the Interface method or any String that gives you a hint ;)
_WARNING(fName='unknown method') {
console.warn('WARNING! Function "'+fName+'" is not overridden in '+this.constructor.name);
}
}
class MultipleInterfaces extends MyInterface {
// this is used for "implement" multiple Interfaces at once
/**
* Gives the square of the given Number
* @param {Number} a The Number
* @return {Number} The square of the Numbers
*/
square(a) { this._WARNING('square(a)'); }
}
class MyCorrectUsedClass extends MyInterface {
// You can easy use the JS doc declared in the interface
/** @inheritdoc */
sum(a, b) {
return a+b;
}
}
class MyIncorrectUsedClass extends MyInterface {
// not overriding the method sum(a, b)
}
class MyMultipleInterfacesClass extends MultipleInterfaces {
// nothing overriden to show, that it still works
}
let working = new MyCorrectUsedClass();
let notWorking = new MyIncorrectUsedClass();
let multipleInterfacesInstance = new MyMultipleInterfacesClass();
// TEST IT
console.log('working.sum(1, 2) =', working.sum(1, 2));
// output: 'working.sum(1, 2) = 3'
console.log('notWorking.sum(1, 2) =', notWorking.sum(1, 2));
// output: 'notWorking.sum(1, 2) = undefined'
// but also sends a warn to the console with 'WARNING! Function "sum(a, b)" is not overridden in MyIncorrectUsedClass'
console.log('multipleInterfacesInstance.sum(1, 2) =', multipleInterfacesInstance.sum(1, 2));
// output: 'multipleInterfacesInstance.sum(1, 2) = undefined'
// console warn: 'WARNING! Function "sum(a, b)" is not overridden in MyMultipleInterfacesClass'
console.log('multipleInterfacesInstance.square(2) =', multipleInterfacesInstance.square(2));
// output: 'multipleInterfacesInstance.square(2) = undefined'
// console warn: 'WARNING! Function "square(a)" is not overridden in MyMultipleInterfacesClass'
EDIT:
I improved the code so you now can simply use implement(baseClass, interface1, interface2, ...) in the extend.
/**
* Implements any number of interfaces to a given class.
* @param cls The class you want to use
* @param interfaces Any amount of interfaces separated by comma
* @return The class cls exteded with all methods of all implemented interfaces
*/
function implement(cls, ...interfaces) {
let clsPrototype = Object.getPrototypeOf(cls).prototype;
for (let i = 0; i < interfaces.length; i++) {
let proto = interfaces[i].prototype;
for (let methodName of Object.getOwnPropertyNames(proto)) {
if (methodName!== 'constructor')
if (typeof proto[methodName] === 'function')
if (!clsPrototype[methodName]) {
console.warn('WARNING! "'+methodName+'" of Interface "'+interfaces[i].name+'" is not declared in class "'+cls.name+'"');
clsPrototype[methodName] = proto[methodName];
}
}
}
return cls;
}
// Basic Interface to warn, whenever an not overridden method is used
class MyBaseInterface {
// declare a warning generator to notice if a method of the interface is not overridden
// Needs the function name of the Interface method or any String that gives you a hint ;)
_WARNING(fName='unknown method') {
console.warn('WARNING! Function "'+fName+'" is not overridden in '+this.constructor.name);
}
}
// create a custom class
/* This is the simplest example but you could also use
*
* class MyCustomClass1 extends implement(MyBaseInterface) {
* foo() {return 66;}
* }
*
*/
class MyCustomClass1 extends MyBaseInterface {
foo() {return 66;}
}
// create a custom interface
class MyCustomInterface1 {
// Declare your JS doc in the Interface to make it acceable while writing the Class and for later inheritance
/**
* Gives the sum of the given Numbers
* @param {Number} a The first Number
* @param {Number} b The second Number
* @return {Number} The sum of the Numbers
*/
sum(a, b) { this._WARNING('sum(a, b)'); }
}
// and another custom interface
class MyCustomInterface2 {
/**
* Gives the square of the given Number
* @param {Number} a The Number
* @return {Number} The square of the Numbers
*/
square(a) { this._WARNING('square(a)'); }
}
// Extend your custom class even more and implement the custom interfaces
class AllInterfacesImplemented extends implement(MyCustomClass1, MyCustomInterface1, MyCustomInterface2) {
/**
* @inheritdoc
*/
sum(a, b) { return a+b; }
/**
* Multiplies two Numbers
* @param {Number} a The first Number
* @param {Number} b The second Number
* @return {Number}
*/
multiply(a, b) {return a*b;}
}
// TEST IT
let x = new AllInterfacesImplemented();
console.log("x.foo() =", x.foo());
//output: 'x.foo() = 66'
console.log("x.square(2) =", x.square(2));
// output: 'x.square(2) = undefined
// console warn: 'WARNING! Function "square(a)" is not overridden in AllInterfacesImplemented'
console.log("x.sum(1, 2) =", x.sum(1, 2));
// output: 'x.sum(1, 2) = 3'
console.log("x.multiply(4, 5) =", x.multiply(4, 5));
// output: 'x.multiply(4, 5) = 20'
That's really all you need!
Update: if you want to do this inside your app, you have several options:
Application.Idle
event and check to see whether you've reached the time in the day to call your method. This method is only called when your app isn't busy with other stuff. A quick check to see if your target time has been reached shouldn't put too much stress on your app, I think...Update #2: if you want to check every 60 minutes, you could create a timer that wakes up every 60 minutes and if the time is up, it calls the method.
Something like this:
using System.Timers;
const double interval60Minutes = 60 * 60 * 1000; // milliseconds to one hour
Timer checkForTime = new Timer(interval60Minutes);
checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
checkForTime.Enabled = true;
and then in your event handler:
void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
{
if (timeIsReady())
{
SendEmail();
}
}
I had to create a timer for teachers grading students' work. Here's one I used which is entirely based on elapsed time since the grading begun by storing the system time at the point that the page is loaded, and then comparing it every half second to the system time at that point:
var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page
function startTimeCounter() {
var now = Math.floor(Date.now() / 1000); // get the time now
var diff = now - startTime; // diff in seconds between now and start
var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
m = checkTime(m); // add a leading zero if it's single digit
s = checkTime(s); // add a leading zero if it's single digit
document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTimeCounter();
This way, it really doesn't matter if the 'setTimeout' is subject to execution delays, the elapsed time is always relative the system time when it first began, and the system time at the time of update.
foreach (DataRow row in myDataTable.Rows)
{
Console.WriteLine(row["ImagePath"]);
}
I am writing this from memory.
Hope this gives you enough hint to understand the object model.
DataTable
-> DataRowCollection
-> DataRow
(which one can use & look for column contents for that row, either using columnName or ordinal).
-> = contains.
ConfigurationManager.AppSettings
is actually a property, so you need to use square brackets.
Overall, here's what you need to do:
SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.
You can also get by phpPgAdmin if you are configured it in your system,
Step 1: Select your database
Step 2: Click on find button
Step 3: Change search option to functions then click on Find.
You will get the list of defined functions.You can search functions by name also, hope this answer will help others.
It has to do with the order in which bytes are stored in memory. The decimal number 5001
is 0x1389
in hexadecimal, so the bytes involved are 0x13
and 0x89
. Many devices store numbers in little-endian format, meaning that the least significant byte comes first. So in this particular example it means that in memory the number 5001
will be stored as
0x89 0x13
The htons()
function makes sure that numbers are stored in memory in network byte order, which is with the most significant byte first. It will therefore swap the bytes making up the number so that in memory the bytes will be stored in the order
0x13 0x89
On a little-endian machine, the number with the swapped bytes is 0x8913
in hexadecimal, which is 35091
in decimal notation. Note that if you were working on a big-endian machine, the htons()
function would not need to do any swapping since the number would already be stored in the right way in memory.
The underlying reason for all this swapping has to do with the network protocols in use, which require the transmitted packets to use network byte order.
I would like to mention the key before writing the code for your consideration.
//Key
temp= address of new node allocated by malloc function (member od alloc.h library in C )
prev= address of last node of existing link list.
next = contains address of next node
struct node {
int data;
struct node *next;
} *head;
void addnode_end(int a) {
struct node *temp, *prev;
temp = (struct node*) malloc(sizeof(node));
if (temp == NULL) {
cout << "Not enough memory";
} else {
node->data = a;
node->next = NULL;
prev = head;
while (prev->next != NULL) {
prev = prev->next;
}
prev->next = temp;
}
}
I don't think you have data for every single day for the past seven days. Days for which no data exist, will obviously not show up.
Try this and validate that you have data for EACH day for the past 7 days
SELECT DISTINCT CreatedDate
FROM News
WHERE CreatedDate >= DATEADD(day,-7, GETDATE())
ORDER BY CreatedDate
EDIT - Copied from your comment
i have dec 19th -1 row data,18th -2 rows,17th -3 rows,16th -3 rows,15th -3 rows,12th -2 rows, 11th -4 rows,9th -1 row,8th -1 row
You don't have data for all days. That is your problem and not the query. If you execute the query today - 22nd - you will only get data for 19th, 18th,17th,16th and 15th. You have no data for 20th, 21st and 22nd.
EDIT - To get data for the last 7 days, where data is available you can try
select id,
NewsHeadline as news_headline,
NewsText as news_text,
state,
CreatedDate as created_on
from News
WHERE CreatedDate IN (SELECT DISTINCT TOP 7 CreatedDate from News
order by createddate DESC)
You can get your package name like so:
$ /path/to/adb shell 'pm list packages -f myapp'
package:/data/app/mycompany.myapp-2.apk=mycompany.myapp
Here are the options:
$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android
-a - directs adb to listen on all interfaces for a connection
-d - directs command to the only connected USB device
returns an error if more than one USB device is present.
-e - directs command to the only running emulator.
returns an error if more than one emulator is running.
-s <specific device> - directs command to the device or emulator with the given
serial number or qualifier. Overrides ANDROID_SERIAL
environment variable.
-p <product name or path> - simple product name like 'sooner', or
a relative/absolute path to a product
out directory like 'out/target/product/sooner'.
If -p is not specified, the ANDROID_PRODUCT_OUT
environment variable is used, which must
be an absolute path.
-H - Name of adb server host (default: localhost)
-P - Port of adb server (default: 5037)
devices [-l] - list all connected devices
('-l' will also list device qualifiers)
connect <host>[:<port>] - connect to a device via TCP/IP
Port 5555 is used by default if no port number is specified.
disconnect [<host>[:<port>]] - disconnect from a TCP/IP device.
Port 5555 is used by default if no port number is specified.
Using this command with no additional arguments
will disconnect from all connected TCP/IP devices.
device commands:
adb push [-p] <local> <remote>
- copy file/dir to device
('-p' to display the transfer progress)
adb pull [-p] [-a] <remote> [<local>]
- copy file/dir from device
('-p' to display the transfer progress)
('-a' means copy timestamp and mode)
adb sync [ <directory> ] - copy host->device only if changed
(-l means list but don't copy)
adb shell - run remote shell interactively
adb shell <command> - run remote shell command
adb emu <command> - run emulator console command
adb logcat [ <filter-spec> ] - View device log
adb forward --list - list all forward socket connections.
the format is a list of lines with the following format:
<serial> " " <local> " " <remote> "\n"
adb forward <local> <remote> - forward socket connections
forward specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
dev:<character device name>
jdwp:<process pid> (remote only)
adb forward --no-rebind <local> <remote>
- same as 'adb forward <local> <remote>' but fails
if <local> is already forwarded
adb forward --remove <local> - remove a specific forward socket connection
adb forward --remove-all - remove all forward socket connections
adb reverse --list - list all reverse socket connections from device
adb reverse <remote> <local> - reverse socket connections
reverse specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
adb reverse --norebind <remote> <local>
- same as 'adb reverse <remote> <local>' but fails
if <remote> is already reversed.
adb reverse --remove <remote>
- remove a specific reversed socket connection
adb reverse --remove-all - remove all reversed socket connections from device
adb jdwp - list PIDs of processes hosting a JDWP transport
adb install [-lrtsdg] <file>
- push this package file to the device and install it
(-l: forward lock application)
(-r: replace existing application)
(-t: allow test packages)
(-s: install application on sdcard)
(-d: allow version code downgrade)
(-g: grant all runtime permissions)
adb install-multiple [-lrtsdpg] <file...>
- push this package file to the device and install it
(-l: forward lock application)
(-r: replace existing application)
(-t: allow test packages)
(-s: install application on sdcard)
(-d: allow version code downgrade)
(-p: partial application install)
(-g: grant all runtime permissions)
adb uninstall [-k] <package> - remove this app package from the device
('-k' means keep the data and cache directories)
adb bugreport - return all information from the device
that should be included in a bug report.
adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
- write an archive of the device's data to <file>.
If no -f option is supplied then the data is written
to "backup.ab" in the current directory.
(-apk|-noapk enable/disable backup of the .apks themselves
in the archive; the default is noapk.)
(-obb|-noobb enable/disable backup of any installed apk expansion
(aka .obb) files associated with each application; the default
is noobb.)
(-shared|-noshared enable/disable backup of the device's
shared storage / SD card contents; the default is noshared.)
(-all means to back up all installed applications)
(-system|-nosystem toggles whether -all automatically includes
system applications; the default is to include system apps)
(<packages...> is the list of applications to be backed up. If
the -all or -shared flags are passed, then the package
list is optional. Applications explicitly given on the
command line will be included even if -nosystem would
ordinarily cause them to be omitted.)
adb restore <file> - restore device contents from the <file> backup archive
adb disable-verity - disable dm-verity checking on USERDEBUG builds
adb enable-verity - re-enable dm-verity checking on USERDEBUG builds
adb keygen <file> - generate adb public/private key. The private key is stored in <file>,
and the public key is stored in <file>.pub. Any existing files
are overwritten.
adb help - show this help message
adb version - show version num
scripting:
adb wait-for-device - block until device is online
adb start-server - ensure that there is a server running
adb kill-server - kill the server if it is running
adb get-state - prints: offline | bootloader | device
adb get-serialno - prints: <serial-number>
adb get-devpath - prints: <device-path>
adb remount - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
adb reboot [bootloader|recovery]
- reboots the device, optionally into the bootloader or recovery program.
adb reboot sideload - reboots the device into the sideload mode in recovery program (adb root required).
adb reboot sideload-auto-reboot
- reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
adb sideload <file> - sideloads the given package
adb root - restarts the adbd daemon with root permissions
adb unroot - restarts the adbd daemon without root permissions
adb usb - restarts the adbd daemon listening on USB
adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port
networking:
adb ppp <tty> [parameters] - Run PPP over USB.
Note: you should not automatically start a PPP connection.
<tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
[parameters] - Eg. defaultroute debug dump local notty usepeerdns
adb sync notes: adb sync [ <directory> ]
<localdir> can be interpreted in several ways:
- If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.
- If it is "system", "vendor", "oem" or "data", only the corresponding partition
is updated.
environment variables:
ADB_TRACE - Print debug information. A comma separated list of the following values
1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
ANDROID_SERIAL - The serial number to connect to. -s takes priority over this if given.
ANDROID_LOG_TAGS - When used with the logcat option, only these debug tags are printed.
LinkedHashMap maintains the order of the keys.
java.util.LinkedHashMap appears to work just like a normal HashMap otherwise.
function Update(key, value)
{
for (var i = 0; i < array.length; i++) {
if (array[i].Key == key) {
array[i].Value = value;
break;
}
}
}
final public void Call(View view){
try {
EditText editt=(EditText)findViewById(R.id.ed1);
String str=editt.getText().toString();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+str));
startActivity(intent);
}
catch (android.content.ActivityNotFoundException e){
Toast.makeText(getApplicationContext(),"App failed",Toast.LENGTH_LONG).show();
}
Here is a full example, I hope it helps =).
<!DOCTYPE html>
<html>
<body>
<video id="myVideo" controls="controls">
<source src="your_video_file.mp4" type="video/mp4">
<source src="your_video_file.mp4" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<script type='text/javascript'>
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler(e) {
if(!e) { e = window.event; }
alert("Video Finished");
}
</script>
</body>
</html>
you can also mark the application as private if you don’t plan to put it in an actual repository.
{
"name": "my-application",
"version": "0.0.1",
"private": true
}
Following command work for me:
sudo npm i -g node-pre-gyp
Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:
SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);
In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).
In CPython 3.6+ (and all other Python implementations starting with Python 3.7+), dictionaries are ordered, so the way to remove duplicates from an iterable while keeping it in the original order is:
>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']
In Python 3.5 and below (including Python 2.7), use the OrderedDict
. My timings show that this is now both the fastest and shortest of the various approaches for Python 3.5.
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']
Given a data URL, you can create an image (either on the page or purely in JS) by setting the src
of the image to your data URL. For example:
var img = new Image;
img.src = strDataURI;
The drawImage()
method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.
You might use it like so:
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;
Edit: I previously suggested in this space that it might not be necessary to use the onload
handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload
to use the new image, and then set the src
—is necessary for some browsers to surely use the results.
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
My code work well just as the answer above. The reason is that the json from jackson is different with the json sent from controller.
String test1= mapper.writeValueAsString(result1);
And the json is like(which can be deserialized normally):
{"code":200,"message":"god","data":[{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"AAAA","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null},{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"BBBB","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null}]}
but the json send from the another service just like:
{"code":200,"message":"????????","data":[{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"csrgzbsjy","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"B-jiegou-all-15","desktop_id":"6360ee29-eb82-416b-aab8-18ded887e8ff","created":"2018-11-12T07:45:15.000Z","ip_address":"192.168.2.215","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""},{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"glory_2147","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"H-pkpm-all-357","desktop_id":"709164e4-d3e6-495d-9c1e-a7b82e30bc83","created":"2018-11-09T09:54:09.000Z","ip_address":"192.168.2.235","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""}]}
You can notice the difference when dealing with the param without initiation. Be careful
A quick tip that tripped me up: if you're invoking the linker as "gcc" or "g++", then using "--start-group" and "--end-group" won't pass those options through to the linker -- nor will it flag an error. It will just fail the link with undefined symbols if you had the library order wrong.
You need to write them as "-Wl,--start-group" etc. to tell GCC to pass the argument through to the linker.
The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
It's possible to some extent but won't be really accurate, the idea is load image with a known file size then in its onload
event measure how much time passed until that event was triggered, and divide this time in the image file size.
Example can be found here: Calculate speed using javascript
Test case applying the fix suggested there:
//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!_x000D_
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg"; _x000D_
var downloadSize = 4995374; //bytes_x000D_
_x000D_
function ShowProgressMessage(msg) {_x000D_
if (console) {_x000D_
if (typeof msg == "string") {_x000D_
console.log(msg);_x000D_
} else {_x000D_
for (var i = 0; i < msg.length; i++) {_x000D_
console.log(msg[i]);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var oProgress = document.getElementById("progress");_x000D_
if (oProgress) {_x000D_
var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");_x000D_
oProgress.innerHTML = actualHTML;_x000D_
}_x000D_
}_x000D_
_x000D_
function InitiateSpeedDetection() {_x000D_
ShowProgressMessage("Loading the image, please wait...");_x000D_
window.setTimeout(MeasureConnectionSpeed, 1);_x000D_
}; _x000D_
_x000D_
if (window.addEventListener) {_x000D_
window.addEventListener('load', InitiateSpeedDetection, false);_x000D_
} else if (window.attachEvent) {_x000D_
window.attachEvent('onload', InitiateSpeedDetection);_x000D_
}_x000D_
_x000D_
function MeasureConnectionSpeed() {_x000D_
var startTime, endTime;_x000D_
var download = new Image();_x000D_
download.onload = function () {_x000D_
endTime = (new Date()).getTime();_x000D_
showResults();_x000D_
}_x000D_
_x000D_
download.onerror = function (err, msg) {_x000D_
ShowProgressMessage("Invalid image, or error downloading");_x000D_
}_x000D_
_x000D_
startTime = (new Date()).getTime();_x000D_
var cacheBuster = "?nnn=" + startTime;_x000D_
download.src = imageAddr + cacheBuster;_x000D_
_x000D_
function showResults() {_x000D_
var duration = (endTime - startTime) / 1000;_x000D_
var bitsLoaded = downloadSize * 8;_x000D_
var speedBps = (bitsLoaded / duration).toFixed(2);_x000D_
var speedKbps = (speedBps / 1024).toFixed(2);_x000D_
var speedMbps = (speedKbps / 1024).toFixed(2);_x000D_
ShowProgressMessage([_x000D_
"Your connection speed is:", _x000D_
speedBps + " bps", _x000D_
speedKbps + " kbps", _x000D_
speedMbps + " Mbps"_x000D_
]);_x000D_
}_x000D_
}
_x000D_
<h1 id="progress">JavaScript is turned off, or your browser is realllllly slow</h1>
_x000D_
Quick comparison with "real" speed test service showed small difference of 0.12 Mbps when using big picture.
To ensure the integrity of the test, you can run the code with Chrome dev tool throttling enabled and then see if the result matches the limitation. (credit goes to user284130 :))
Important things to keep in mind:
The image being used should be properly optimized and compressed. If it isn't, then default compression on connections by the web server might show speed bigger than it actually is. Another option is using uncompressible file format, e.g. jpg. (thanks Rauli Rajande for pointing this out and Fluxine for reminding me)
The cache buster mechanism described above might not work with some CDN servers, which can be configured to ignore query string parameters, hence better setting cache control headers on the image itself. (thanks orcaman for pointing this out))
Answers by ‘smartnut007’, ‘Bill Karwin’, and ‘sqlvogel’ are excellent. Yet let me put an interesting perspective to it.
Well, we have prime and non-prime keys.
When we focus on how non-primes depend on primes, we see two cases:
Non-primes can be dependent or not.
When not dependent: there can be no-dependency or transitive dependency
What about dependencies among primes?
Now you see, we’re not addressing the dependency relationship among primes by either 2nd or 3rd NF. Further such dependency, if any, is not desirable and thus we’ve a single rule to address that. This is BCNF.
Referring to the example from Bill Karwin's post here, you’ll notice that both ‘Topping’, and ‘Topping Type’ are prime keys and have a dependency. Had they been non-primes with dependency, then 3NF would have kicked in.
Note:
The definition of BCNF is very generic and without differentiating attributes between prime and non-prime. Yet, the above way of thinking helps to understand how some anomaly is percolated even after 2nd and 3rd NF.
Advanced Topic: Mapping generic BCNF to 2NF & 3NF
Now that we know BCNF provides a generic definition without reference to any prime/non-prime attribues, let's see how BCNF and 2/3 NF's are related.
First, BCNF requires (other than the trivial case) that for each functional dependency
For case (1), 3NF takes care of.
For case (3), 2NF takes care of.
For case (2), we find the use of BCNFX -> Y
(FD), X should be super-key.
If you just consider any FD, then we've three cases - (1) Both X and Y non-prime, (2) Both prime and (3) X prime and Y non-prime, discarding the (nonsensical) case X non-prime and Y prime.
You can use read_csv
from pandas
to skip these lines.
import pandas as pd
data_df = pd.read_csv('data.csv', error_bad_lines=False)
Using Concat on the group by will work
SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30
To expand on Pavlo's answer https://stackoverflow.com/a/34063808/1069914, you can have multiple child items justify-content: flex-start
in their behavior but have the last item justify-content: flex-end
.container {
height: 100px;
border: solid 10px skyblue;
display: flex;
justify-content: flex-end;
}
.container > *:not(:last-child) {
margin-right: 0;
margin-left: 0;
}
/* set the second to last-child */
.container > :nth-last-child(2) {
margin-right: auto;
margin-left: 0;
}
.block {
width: 50px;
background: tomato;
border: 1px solid black;
}
_x000D_
<div class="container">
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block" style="width:150px">I should be at the end of the flex container (i.e. justify-content: flex-end)</div>
</div>
_x000D_
It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.
In 'Path Variables' create a variable for example ANALYTICS_VERSION
.
In a 'Run Configuration' under 'Environment Variables' add for example the following:
ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin
To answer the original question you would need to add an APP_HOME
environment variable to your run configuration which references the path variable:
APP_HOME=$APP_HOME$
Splat Method with Calculations
If you choose splat method, beware calculations that are made using other parameters. In practice, sometimes I have to set variables first then create the hash table. Also, the format doesn't require single quotes around the key value or the semi-colon (as mentioned above).
Example of a call to a function that creates an Excel spreadsheet
$title = "Cut-off File Processing on $start_date_long_str"
$title_row = 1
$header_row = 2
$data_row_start = 3
$data_row_end = $($data_row_start + $($file_info_array.Count) - 1)
# use parameter hash table to make code more readable
$params = @{
title = $title
title_row = $title_row
header_row = $header_row
data_row_start = $data_row_start
data_row_end = $data_row_end
}
$xl_wksht = Create-Excel-Spreadsheet @params
Note: The file array contains information that will affect how the spreadsheet is populated.
public abstract class RootFragment extends Fragment implements OnBackPressListener {
@Override
public boolean onBackPressed() {
return new BackPressImpl(this).onBackPressed();
}
public abstract void OnRefreshUI();
}
public class BackPressImpl implements OnBackPressListener {
private Fragment parentFragment;
public BackPressImpl(Fragment parentFragment) {
this.parentFragment = parentFragment;
}
@Override
public boolean onBackPressed() {
((RootFragment) parentFragment).OnRefreshUI();
}
}
and final extent your Frament from RootFragment to see effect
We can easily add animated gif image on imageview using Ion library.
Tutorial video :: https://www.youtube.com/watch?v=IqKtpdeIpjA
ImageView image = (ImageView)findViewById(R.id.image_gif);
Ion.with(image).load("http://mygifimage.gif");
As a python neophyte, I just wanted to mention that if the data did actually look like this:
data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
then sorted()
would automatically sort by the second element in the tuple, as the first elements are all identical.
I'm not quite sure what your problem is, but you need to specify the parameter name like so.
-(void) changeCellText:(NSIndexPath *) nowIndex{
UILabel *content = (UILabel *)[[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex] contentView] viewWithTag:contentTag];
content.text = [formatter stringFromDate:checkInDate.date];
}
here is something I found from here: github
made a little improvising. Very simple and clean. No external files or methods:
public class RoundedImageView extends ImageView {
private float mCornerRadius = 10.0f;
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attributes) {
super(context, attributes);
}
@Override
protected void onDraw(Canvas canvas) {
// Round some corners betch!
Drawable myDrawable = getDrawable();
if (myDrawable!=null && myDrawable instanceof BitmapDrawable && mCornerRadius > 0) {
Paint paint = ((BitmapDrawable) myDrawable).getPaint();
final int color = 0xff000000;
Rect bitmapBounds = myDrawable.getBounds();
final RectF rectF = new RectF(bitmapBounds);
// Create an off-screen bitmap to the PorterDuff alpha blending to work right
int saveCount = canvas.saveLayer(rectF, null,
Canvas.MATRIX_SAVE_FLAG |
Canvas.CLIP_SAVE_FLAG |
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
Canvas.FULL_COLOR_LAYER_SAVE_FLAG |
Canvas.CLIP_TO_LAYER_SAVE_FLAG);
// Resize the rounded rect we'll clip by this view's current bounds
// (super.onDraw() will do something similar with the drawable to draw)
getImageMatrix().mapRect(rectF);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, mCornerRadius, mCornerRadius, paint);
Xfermode oldMode = paint.getXfermode();
// This is the paint already associated with the BitmapDrawable that super draws
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
super.onDraw(canvas);
paint.setXfermode(oldMode);
canvas.restoreToCount(saveCount);
} else {
super.onDraw(canvas);
}
}
}
Note for Android 9 (Pie).
Additionally to useLibrary 'org.apache.http.legacy'
you have to add in AndroidManifest.xml:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
Source: https://developer.android.com/about/versions/pie/android-9.0-changes-28
On android (API 16 or greater) you can:
Html.escapeHtml(textToScape);
or for lower API:
TextUtils.htmlEncode(textToScape);
How about this:
$(document).ready(function() {
$('#subscribeForm').submit(function() {
var $fields = $(this).find('input[name="list"]:checked');
if (!$fields.length) {
alert('You must check at least one box!');
return false; // The form will *not* submit
}
});
});
It might be a bit messy, but sometimes you just don't need to access self
, but you would prefer to keep the method in the class and not make it static. Or you just want to avoid adding a bunch of unsightly decorators. Here are some potential workarounds for that situation.
If your method only has side effects and you don't care about what it returns:
def bar(self):
doing_something_without_self()
return self
If you do need the return value:
def bar(self):
result = doing_something_without_self()
if self:
return result
Now your method is using self
, and the warning goes away!
I'm currently achieving the task, by using the following
#!/usr/bin/python
import boto3
s3=boto3.client('s3')
list=s3.list_objects(Bucket='bucket')['Contents']
for s3_key in list:
s3_object = s3_key['Key']
if not s3_object.endswith("/"):
s3.download_file('bucket', s3_object, s3_object)
else:
import os
if not os.path.exists(s3_object):
os.makedirs(s3_object)
Although, it does the job, I'm not sure its good to do this way. I'm leaving it here to help other users and further answers, with better manner of achieving this
In the lates TS you can do like this:
const isMyInterface = (val: any): val is MyInterface => {
if (!val) { return false; }
if (!val.myProp) { return false; }
return true;
};
And than user like this:
if (isMyInterface(data)) {
// now data will be type of MyInterface
}
@Html.Partial("NameOfPartialView")
Required here
<div class="outer">Outer Text
<div class="inner"> Inner Text</div>
</div>
added by
$(document).ready(function(){
$('.inner').prepend('<div class="middle">New Text Middle</div>');
});
I often use trigger ('change') to make it work
$('#selectBox option:eq(position_index)').prop('selected', true).trigger('change');
Example with id select = selectA1 and position_index = 0 (frist option in select):
$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');
If you add all your events with this snippet of code:
//put this somewhere in your JavaScript:
HTMLElement.prototype.addEvent = function(event, callback){
if(!this.events)this.events = {};
if(!this.events[event]){
this.events[event] = [];
var element = this;
this['on'+event] = function(e){
var events = element.events[event];
for(var i=0;i<events.length;i++){
events[i](e||event);
}
}
}
this.events[event].push(callback);
}
//use like this:
element.addEvent('change', function(e){...});
then you can just use element.on<EVENTNAME>()
where <EVENTNAME>
is the name of your event, and that will call all events with <EVENTNAME>
Not necessary to give 160 . 141 will also work. For the value field provide value="" .
You can also use the java.util.Scanner class.
private static void readFileWithScanner() {
File file = new File("path/to/your/file/file.txt");
Scanner scan = null;
try {
scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] lineArray = line.split(",");
// do something with lineArray, such as instantiate an object
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scan.close();
}
}
<input type="radio" name="radio" value="upi">upi
<input type="radio" name="radio" value="bankAcc">Bank
<script type="text/javascript">
$(document).ready(function() {
$('input[type=radio][name=radio]').change(function() {
if (this.value == 'upi') {
//write your logic here
}
else if (this.value == 'bankAcc') {
//write your logic here
}
});
</script>
create div with id name
var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}
add text to div
var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}
test code
divCreator("div1");
textAdder("div1", "this is paragraph 1");
output
this is paragraph 1
Simply, your question sounded wrong because the JavaScript variables need to be echoed.
<?php_x000D_
$num = 1;_x000D_
echo $num;_x000D_
echo "<input type='button' value='Click' onclick='readmore()' />";_x000D_
echo "<script> function readmore() { document.write('";_x000D_
$num = 2;_x000D_
echo $num;_x000D_
echo "'); } </script>";_x000D_
?>
_x000D_
Add http:// in front of url
Incorrect
<a href="www.example.com">www.example.com</span></p>
Correct
<a href="http://www.example.com">www.example.com</span></p>
From what I see, people use package.json scripts when they would like to run script in simpler way. For example, to use nodemon
that installed in local node_modules, we can't call nodemon
directly from the cli, but we can call it by using ./node_modules/nodemon/nodemon.js
. So, to simplify this long typing, we can put this...
... scripts: { 'start': 'nodemon app.js' } ...
... then call npm start
to use 'nodemon' which has app.js as the first argument.
What I'm trying to say, if you just want to start your server with the node
command, I don't think you need to use scripts
. Typing npm start
or node app.js
has the same effort.
But if you do want to use nodemon
, and want to pass a dynamic argument, don't use script
either. Try to use symlink instead.
For example using migration with sequelize
. I create a symlink...
ln -s node_modules/sequelize/bin/sequelize sequelize
... And I can pass any arguement when I call it ...
./sequlize -h /* show help */
./sequelize -m /* upgrade migration */
./sequelize -m -u /* downgrade migration */
etc...
At this point, using symlink is the best way I could figure out, but I don't really think it's the best practice.
I also hope for your opinion to my answer.
Instead of a comment, I just want to answer post.
Interface java.sql.PreparedStatement
columnIndexes « You can use prepareStatement function that accepts columnIndexes and SQL statement. Where columnIndexes allowed constant flags are Statement.RETURN_GENERATED_KEYS1 or Statement.NO_GENERATED_KEYS[2], SQL statement that may contain one or more '?' IN parameter placeholders.
SYNTAX «
Connection.prepareStatement(String sql, int autoGeneratedKeys)
Connection.prepareStatement(String sql, int[] columnIndexes)
Example:
PreparedStatement pstmt =
conn.prepareStatement( insertSQL, Statement.RETURN_GENERATED_KEYS );
columnNames « List out the columnNames like 'id', 'uniqueID', ...
. in the target table that contain the auto-generated keys that should be returned. The driver will ignore them if the SQL statement is not an INSERT
statement.
SYNTAX «
Connection.prepareStatement(String sql, String[] columnNames)
Example:
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
Full Example:
public static void insertAutoIncrement_SQL(String UserName, String Language, String Message) {
String DB_URL = "jdbc:mysql://localhost:3306/test", DB_User = "root", DB_Password = "";
String insertSQL = "INSERT INTO `unicodeinfo`( `UserName`, `Language`, `Message`) VALUES (?,?,?)";
//"INSERT INTO `unicodeinfo`(`id`, `UserName`, `Language`, `Message`) VALUES (?,?,?,?)";
int primkey = 0 ;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(DB_URL, DB_User, DB_Password);
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
pstmt.setString(1, UserName );
pstmt.setString(2, Language );
pstmt.setString(3, Message );
if (pstmt.executeUpdate() > 0) {
// Retrieves any auto-generated keys created as a result of executing this Statement object
java.sql.ResultSet generatedKeys = pstmt.getGeneratedKeys();
if ( generatedKeys.next() ) {
primkey = generatedKeys.getInt(1);
}
}
System.out.println("Record updated with id = "+primkey);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
If you don't want to or simply can't use Linq you can also use the static Array.Exists(...);
function:
https://msdn.microsoft.com/en-us/library/yw84x8be%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
var arr = new string[]{"bird","foo","cat","dog"};
var catInside = Array.Exists(
arr, // your Array
(s)=>{ return s == "cat"; } // the Predicate
);
When the Predicate do return true once catInside will be true as well.
If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next.equals("Two")) {
//Replace element
iterator.set("New");
}
}
You can also use v-model for the rescue
<template>
<select name="LeaveType" v-model="leaveType" @change="onChange()" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
</template>
<script>
export default {
data() {
return {
leaveType: '',
}
},
methods: {
onChange() {
console.log('The new value is: ', this.leaveType)
}
}
}
</script>
If the image is in a container with a responsive width:
HTML
<div class="img-container">
<img src="" alt="">
</div>
CSS
.img-container {
position: relative;
&::after {
content: "";
display: block;
padding-bottom: 100%;
}
img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
}
}
I prepared my commit that I wanted to amend with an older one and was surprised to see that rebase -i complained that I have uncommitted changes. But I didn't want to make my changes again specifying edit option of the older commit. So the solution was pretty easy and straightforward:
git rebase -i <commit you want to amend>^
- notice the ^
so you see the said commit in the text editoryou will get sometihng like this:
pick 8c83e24 use substitution instead of separate subsystems file to avoid jgroups.xml and jgroups-e2.xml going out of sync
pick 799ce28 generate ec2 configuration out of subsystems-ha.xml and subsystems-full-ha.xml to avoid discrepancies
pick e23d23a fix indentation of jgroups.xml
now to combine e23d23a with 8c83e24 you can change line order and use squash like this:
pick 8c83e24 use substitution instead of separate subsystems file to avoid jgroups.xml and jgroups-e2.xml going out of sync
squash e23d23a fix indentation of jgroups.xml
pick 799ce28 generate ec2 configuration out of subsystems-ha.xml and subsystems-full-ha.xml to avoid discrepancies
write and exit the file, you will be present with an editor to merge the commit messages. Do so and save/exit the text document
credit goes to: http://git-scm.com/book/en/Git-Tools-Rewriting-History There's also other useful demonstrated git magic.
This is a better solution, using:
$("table tr:first-child").has('img')
Jest's setupFiles
is the proper way to handle this, and you need not install dotenv
, nor use an .env
file at all, to make it work.
jest.config.js
:
module.exports = {
setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};
.jest/setEnvVars.js
:
process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'
That's it.
It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.
Based on the page listed above, the default sizes look something like this:
IE7 IE8 FF2 FF3 Opera Safari 3.1
H1 24pt 2em 32px 32px 32px 32px
H2 18pt 1.5em 24px 24px 24px 24px
H3 13.55pt 1.17em 18.7333px 18.7167px 18px 19px
H4 n/a n/a n/a n/a n/a n/a
H5 10pt 0.83em 13.2667px 13.2833px 13px 13px
H6 7.55pt 0.67em 10.7333px 10.7167px 10px 11px
Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:
h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }
Hope this information is helpful.
(Background: I have some experience implementing C and C++ compilers.)
Variable-length arrays in C99 were basically a misstep. In order to support VLAs, C99 had to make the following concessions to common sense:
sizeof x
is no longer always a compile-time constant; the compiler must sometimes generate code to evaluate a sizeof
-expression at runtime.
Allowing two-dimensional VLAs (int A[x][y]
) required a new syntax for declaring functions that take 2D VLAs as parameters: void foo(int n, int A[][*])
.
Less importantly in the C++ world, but extremely important for C's target audience of embedded-systems programmers, declaring a VLA means chomping an arbitrarily large chunk of your stack. This is a guaranteed stack-overflow and crash. (Anytime you declare int A[n]
, you're implicitly asserting that you have 2GB of stack to spare. After all, if you know "n
is definitely less than 1000 here", then you would just declare int A[1000]
. Substituting the 32-bit integer n
for 1000
is an admission that you have no idea what the behavior of your program ought to be.)
Okay, so let's move to talking about C++ now. In C++, we have the same strong distinction between "type system" and "value system" that C89 does… but we've really started to rely on it in ways that C has not. For example:
template<typename T> struct S { ... };
int A[n];
S<decltype(A)> s; // equivalently, S<int[n]> s;
If n
weren't a compile-time constant (i.e., if A
were of variably modified type), then what on earth would be the type of S
? Would S
's type also be determined only at runtime?
What about this:
template<typename T> bool myfunc(T& t1, T& t2) { ... };
int A1[n1], A2[n2];
myfunc(A1, A2);
The compiler must generate code for some instantiation of myfunc
. What should that code look like? How can we statically generate that code, if we don't know the type of A1
at compile time?
Worse, what if it turns out at runtime that n1 != n2
, so that !std::is_same<decltype(A1), decltype(A2)>()
? In that case, the call to myfunc
shouldn't even compile, because template type deduction should fail! How could we possibly emulate that behavior at runtime?
Basically, C++ is moving in the direction of pushing more and more decisions into compile-time: template code generation, constexpr
function evaluation, and so on. Meanwhile, C99 was busy pushing traditionally compile-time decisions (e.g. sizeof
) into the runtime. With this in mind, does it really even make sense to expend any effort trying to integrate C99-style VLAs into C++?
As every other answerer has already pointed out, C++ provides lots of heap-allocation mechanisms (std::unique_ptr<int[]> A = new int[n];
or std::vector<int> A(n);
being the obvious ones) when you really want to convey the idea "I have no idea how much RAM I might need." And C++ provides a nifty exception-handling model for dealing with the inevitable situation that the amount of RAM you need is greater than the amount of RAM you have. But hopefully this answer gives you a good idea of why C99-style VLAs were not a good fit for C++ — and not really even a good fit for C99. ;)
For more on the topic, see N3810 "Alternatives for Array Extensions", Bjarne Stroustrup's October 2013 paper on VLAs. Bjarne's POV is very different from mine; N3810 focuses more on finding a good C++ish syntax for the things, and on discouraging the use of raw arrays in C++, whereas I focused more on the implications for metaprogramming and the typesystem. I don't know if he considers the metaprogramming/typesystem implications solved, solvable, or merely uninteresting.
A good blog post that hits many of these same points is "Legitimate Use of Variable Length Arrays" (Chris Wellons, 2019-10-27).
If you don't have a common way to atomically update or insert (e.g., via a transaction) then you can fallback to another locking scheme. A 0-byte file, system mutex, named pipe, etc...
You need to add a reference to System.Web.Extensions.dll
in project for System.Web.Script.Serialization error.
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
My variant, one word at a time on the entire file.
I read it into memory.
def replace_word(infile,old_word,new_word):
if not os.path.isfile(infile):
print ("Error on replace_word, not a regular file: "+infile)
sys.exit(1)
f1=open(infile,'r').read()
f2=open(infile,'w')
m=f1.replace(old_word,new_word)
f2.write(m)
The case (single page style) for browser history
HttpContext.Request.UrlReferrer
Today the command
heroku pg:reset --db SHARED_DATABASE_URL
not working for shared plans, I'm resolve using
heroku pg:reset SHARED_DATABASE
You may consider FluentFTP, previously known as System.Net.FtpClient.
It is released under The MIT License and available on NuGet (FluentFTP).
is this already solved?
i also had this problem. I solved it just by cleaning the project.
Project>Clean>Clean projects selected below>Check [your project's name]
Use this command, (go to java < jdk < bin path in cmd prompt)
$ jarsigner -verify -verbose -certs my_application.apk
If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK (means it is unsigned), otherwise you will find something for CN. For more details see: http://developer.android.com/guide/publishing/app-signing.html
mysqldump -h [host] -p -u [user] [database name] > filename.sql
Example in localhost
mysqldump -h localhost -p -u root cookbook > cookbook.sql
You can use a Contains
query for this:
var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));
Most people will tell you to check your proxy settings or delete and re-add artifacts, but I will stay away from that and give another suggestion in case that doesn't turn out to be your problem. It could be your mirror settings.
If you use maven at the office then there's a good chance maven is configured to look for your company's internal maven repository. If you're doing some work from home and you are not connected to the network this could be the problem. An obvious solution might be VPN to the office to get visibility to this repo. Another way around this is to add another mirror site to your /User/.m2/settings.xml file so if it fails to find it on your office network it will try public repo.
<mirror>
<id>Central</id>
<url>http://repo1.maven.org/maven2</url>
<mirrorOf>central</mirrorOf>
<!-- United States, St. Louis-->
</mirror>
For other maven repositories take a look here: http://docs.codehaus.org/display/MAVENUSER/Mirrors+Repositories
Here is one that hard fails after 4 attempts, and waits 2 seconds between attempts. Change as you wish to get what you want form this one:
from time import sleep
for x in range(0, 4): # try 4 times
try:
# msg.send()
# put your logic here
str_error = None
except Exception as str_error:
pass
if str_error:
sleep(2) # wait for 2 seconds before trying to fetch the data again
else:
break
Here is an example with backoff:
from time import sleep
sleep_time = 2
num_retries = 4
for x in range(0, num_retries):
try:
# put your logic here
str_error = None
except Exception as str_error:
pass
if str_error:
sleep(sleep_time) # wait before trying to fetch the data again
sleep_time *= 2 # Implement your backoff algorithm here i.e. exponential backoff
else:
break
Just make sure that the controller name is the same as yours DeliveryController if you renamed it (it will not change automatically!). if you rename the project name too you should delete the reference to this project from the Bin folder. Don't forget to specify the method get or post.
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
Some of the comments mention this as well, but asp net core does all this work for you.
If you have a query string that matches the name it will be available in the controller.
https://myapi/some-endpoint/123?someQueryString=YayThisWorks
[HttpPost]
[Route("some-endpoint/{someValue}")]
public IActionResult SomeEndpointMethod(int someValue, string someQueryString)
{
Debug.WriteLine(someValue);
Debug.WriteLine(someQueryString);
return Ok();
}
Ouputs:
123
YayThisWorks
It is faster to slice the string twice, like this:
function spliceSlice(str, index, count, add) {
// We cannot pass negative indexes directly to the 2nd slicing operation.
if (index < 0) {
index = str.length + index;
if (index < 0) {
index = 0;
}
}
return str.slice(0, index) + (add || "") + str.slice(index + count);
}
than using a split followed by a join (Kumar Harsh's method), like this:
function spliceSplit(str, index, count, add) {
var ar = str.split('');
ar.splice(index, count, add);
return ar.join('');
}
Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)
Although the code above implements functions that reproduce the general functionality of splice
, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.
you can reverse your array and push the data , at the end again reverse it:
var arr=[2,3,4,5,6];
var arr2=1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);
Just came across the same issue today...
In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:
list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)
Internal classes need to be tested and there is an assemby attribute:
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("MyTests")]
Add this to the project info file, e.g. Properties\AssemblyInfo.cs
.
var offset = new Date().getTimezoneOffset();
offset
will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.
utc_date.setMinutes(utc_date.getMinutes() - offset);
I tried all of the above. I kept getting the error about the UUID not being found.
I went to the project, opened project.pbxproj and found all instances of the UUID (2) and deleted the UUID (not the entire line).
Fixed the problem.
In Swift:
import AVFoundation
...
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
TRY THIS CODE
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("Please enter number only...");
e.Handled = true;
}
}
Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx
I guess it's meant that you enable gzip compression for your css and js files, because that will enable the client to receive both gzip-encoded content and a plain content.
This is how to do it in apache2:
<IfModule mod_deflate.c>
#The following line is enough for .js and .css
AddOutputFilter DEFLATE js css
#The following line also enables compression by file content type, for the following list of Content-Type:s
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml
#The following lines are to avoid bugs with some browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</IfModule>
And here's how to add the Vary Accept-Encoding
header: [src]
<IfModule mod_headers.c>
<FilesMatch "\.(js|css|xml|gz)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>
The Vary:
header tells the that the content served for this url will vary according to the value of a certain request header. Here it says that it will serve different content for clients who say they Accept-Encoding: gzip, deflate
(a request header), than the content served to clients that do not send this header. The main advantage of this, AFAIK, is to let intermediate caching proxies know they need to have two different versions of the same url because of such change.
Here is a Swift way to get screen status bar height:
var screenStatusBarHeight: CGFloat {
return UIApplication.sharedApplication().statusBarFrame.height
}
These are included as a standard function in a project of mine: https://github.com/goktugyil/EZSwiftExtensions
Add a datatable into session:
DataTable Tissues = new DataTable();
Tissues = dal.returnTissues("TestID", "TestValue");// returnTissues("","") sample function for adding values
Session.Add("Tissues", Tissues);
Retrive that datatable from session:
DataTable Tissues = Session["Tissues"] as DataTable
or
DataTable Tissues = (DataTable)Session["Tissues"];
Simple answer:A grammar is said to be an LL(1),if the associated LL(1) parsing table has atmost one production in each table entry.
Take the simple grammar A -->Aa|b.[A is non-terminal & a,b are terminals]
then find the First and follow sets A.
First{A}={b}.
Follow{A}={$,a}.
Parsing table for Our grammar.Terminals as columns and Nonterminal S as a row element.
a b $
--------------------------------------------
S | A-->a |
| A-->Aa. |
--------------------------------------------
As [S,b] contains two Productions there is a confusion as to which rule to choose.So it is not LL(1).
Some simple checks to see whether a grammar is LL(1) or not. Check 1: The Grammar should not be left Recursive. Example: E --> E+T. is not LL(1) because it is Left recursive. Check 2: The Grammar should be Left Factored.
Left factoring is required when two or more grammar rule choices share a common prefix string. Example: S-->A+int|A.
Check 3:The Grammar should not be ambiguous.
These are some simple checks.
I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)
This is for reading images from Azure Cognative Services's Vision API
const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';
// Request parameters.
const params = {
'visualFeatures': 'Categories,Description,Adult,Faces',
'maxCandidates': '2',
'details': 'Celebrities,Landmarks',
'language': 'en'
};
const options = {
uri: uriBase,
qs: params,
body: fs.readFileSync(./my_local_image_path.jpg),
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, ' ');
body = JSON.parse(body);
if (body.code) // err
{
console.log("AZURE: " + body.message)
}
console.log('Response\n' + jsonString);
C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> names = new Dictionary<string,int>();
for (int i = 0; i < 10; i++)
{
names.Add(String.Format("name{0}", i.ToString()), i);
}
var xx1 = names["name1"];
var xx2 = names["name2"];
var xx3 = names["name3"];
}
}
}
Any answer which suggests using grep to exclude the CREATE
lines or just grab the INSERT
lines from the sqlite3 $DB .dump
output will fail badly. The CREATE TABLE
commands list one column per line (so excluding CREATE
won't get all of it), and values on the INSERT
lines can have embedded newlines (so you can't grab just the INSERT
lines).
for t in $(sqlite3 $DB .tables); do
echo -e ".mode insert $t\nselect * from $t;"
done | sqlite3 $DB > backup.sql
Tested on sqlite3 version 3.6.20.
If you want to exclude certain tables you can filter them with $(sqlite $DB .tables | grep -v -e one -e two -e three)
, or if you want to get a specific subset replace that with one two three
.
you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.
declare a HashMap somewhere in your class:
private static HashMap<String, Integer> images = null;
//Then initialize it in your constructor:
public myClass() {
if (images == null) {
images = new HashMap<String, Integer>();
images.put("Human1Arm", R.drawable.human_one_arm);
// for all your images - don't worry, this is really fast and will only happen once
}
}
Now for access -
String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);
one of the approach if you want to get all user_id that satisfies all conditions is:
SELECT DISTINCT user_id FROM table WHERE ancestry IN ('England', '...', '...') GROUP BY user_id HAVING count(*) = <number of conditions that has to be satisfied>
etc. If you need to take all user_ids that satisfies at least one condition, then you can do
SELECT DISTINCT user_id from table where ancestry IN ('England', 'France', ... , '...')
I am not aware if there is something similar to IN but that joins conditions with AND instead of OR
There are some builtin modules that contain mostly bare functions (base64, math, os, shutil, sys, time, ...) and it is definitely a good practice to have these bare functions bound to some namespace and thus improve the readability of your code. Consider how more difficult is to understand the meaning of these functions without their namespace:
copysign(foo, bar)
monotonic()
copystat(foo, bar)
than when they are bound to some module:
math.copysign(foo, bar)
time.monotonic()
shutil.copystat(foo, bar)
Sometimes you even need the namespace to avoid conflicts between different modules (json.load vs. pickle.load)
configparser.RawConfigParser()
datetime.DateTime()
email.message.EmailMessage()
tempfile.NamedTemporaryFile()
zipfile.ZipFile()
so there can be a debate whether using these classes with the additional module namespace in your code adds some new information or just lengthens the code.
I was having this till today when I start grunt watch
. Finally solved by
watch: {
options: {
maxListeners: 99,
livereload: true
},
}
The annoying message is gone.
Check
config > config
codeigniter file structure
replace
$config['base_url'] = "your Website url";
with
$config['base_url'] = "http://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= preg_replace('@/+$@', '', dirname($_SERVER['SCRIPT_NAME'])).'/';
In Jan2018 the only solution worked for me:
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
How about this?
<div class="relative">
<div class="yellow-div"></div>
<div class="yellow-div"></div>
<div class="absolute"></div>
</div>
.relative{
position:relative;
}
.absolute {
position:absolute;
width: 40px;
height: 100px;
background: #000;
z-index: 1;
top:30px;
left:0px;
}
.yellow-div {
position:relative;
width: 200px;
height: 50px;
background: yellow;
margin-bottom:4px;
z-index:0;
}
use the relative div as wrapper and let the yellow div's have normal positioning.
Only the black block need to have an absolute position then.
From my point of view, disable images caching is a bad idea. At all.
The root problem here is - how to force browser to update image, when it has been updated on a server side.
Again, from my personal point of view, the best solution is to disable direct access to images. Instead access images via server-side filter/servlet/other similar tools/services.
In my case it's a rest service, that returns image and attaches ETag in response. The service keeps hash of all files, if file is changed, hash is updated. It works perfectly in all modern browsers. Yes, it takes time to implement it, but it is worth it.
The only exception - are favicons. For some reasons, it does not work. I could not force browser to update its cache from server side. ETags, Cache Control, Expires, Pragma headers, nothing helped.
In this case, adding some random/version parameter into url, it seems, is the only solution.
Use double braces {{
or }}
so your code becomes:
sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}",
prop.Type, prop.Name));
// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }
A very simple trick to do so, is to add a <span>
tag and add background color to that. It will look just the way you want it.
<h1>
<span>The Last Will and Testament of Eric Jones</span>
</h1>
And CSS
h1 { text-align: center; }
h1 span { background-color: green; }
<span>
tag in an inline element tag, so it will only span over the content faking the effect.
After few hours of searching, I just solved this issue with a few lines of code
Your model
[Required(ErrorMessage = "Enter the issued date.")]
[DataType(DataType.Date)]
public DateTime IssueDate { get; set; }
Razor Page
@Html.TextBoxFor(model => model.IssueDate)
@Html.ValidationMessageFor(model => model.IssueDate)
Jquery DatePicker
<script type="text/javascript">
$(document).ready(function () {
$('#IssueDate').datepicker({
dateFormat: "dd/mm/yy",
showStatus: true,
showWeeks: true,
currentText: 'Now',
autoSize: true,
gotoCurrent: true,
showAnim: 'blind',
highlightWeek: true
});
});
</script>
Webconfig File
<system.web>
<globalization uiCulture="en" culture="en-GB"/>
</system.web>
Now your text-box will accept "dd/MM/yyyy" format.
OP's problem was related with HTML coding. But if you are using plain text, please use "\n" and not "\r\n".
My personal use case: using mailx mailer, simply replacing "\r\n" into "\n" fixed my issue, related with wrong automatic Content-Type setting.
Wrong header:
User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Correct header:
User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
I'm not saying that "application/octet-stream" and "base64" are always wrong/unwanted, but they where in my case.
The easiest way is to use lubridate:
library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)
This function automatically returns objects of class POSIXct
and will work with either factors or characters.
I know this is late but on a linux/mac ,from the terminal you can use the following.
git status | sed -n 1p
Explanation:
git status -> gets the working tree status
sed -n 1p -> gets the first line from the status body
Response to the above command will look as follows:
"On branch your_branch_name"
SELECT SUBSTR(TRIM(rtp.role),1,12) AS ROLE
, SUBSTR(rp.grantee,1,16) AS GRANTEE
, SUBSTR(TRIM(rtp.privilege),1,12) AS PRIVILEGE
, SUBSTR(TRIM(rtp.owner),1,12) AS OWNER
, SUBSTR(TRIM(rtp.table_name),1,28) AS TABLE_NAME
, SUBSTR(TRIM(rtp.column_name),1,20) AS COLUMN_NAME
, SUBSTR(rtp.common,1,4) AS COMMON
, SUBSTR(rtp.grantable,1,4) AS GRANTABLE
, SUBSTR(rp.default_role,1,16) AS DEFAULT_ROLE
, SUBSTR(rp.admin_option,1,4) AS ADMIN_OPTION
FROM role_tab_privs rtp
LEFT JOIN dba_role_privs rp
ON (rtp.role = rp.granted_role)
WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
ORDER BY 1
, 2
, 3
, 4
;
SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.
If your CSS html
element has the following overflow
markup, scrollTop
will not function.
html {
overflow-x: hidden;
overflow-y: hidden;
}
To allow scrollTop
to scroll, modify your markup remove overflow
markup from the html
element and append to a body
element.
body {
overflow-x: hidden;
overflow-y: hidden;
}
I expand on the top of @gezdy's answer.
In every Activities, instead of having to "register" itself with Application
with manual coding, we can make use of the following API since level 14, to help us achieve similar purpose with less manual coding.
public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)
In Application.ActivityLifecycleCallbacks
, you can get which Activity
is "attached" to or "detached" to this Application
.
However, this technique is only available since API level 14.
If you want to stop process you can kill it manually from task manager onother side if you want to stop running query in DBMS you can stop as given here for ms sqlserver T-SQL STOP or ABORT command in SQL Server Hope it helps you
The extension method worked great for me with one exception that if the user logs out there old claim sets still existed so with a tiny modification as in passing usermanager through everything works great and you dont need to logout and login. I cant answer directly as my reputation has been dissed :(
public static class ClaimExtensions
{
public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value, ApplicationUserManager userManager)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return;
// check for existing claim and remove it
var existingClaim = identity.FindFirst(key);
if (existingClaim != null)
{
RemoveClaim(currentPrincipal, key, userManager);
}
// add new claim
var claim = new Claim(key, value);
identity.AddClaim(claim);
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
//Persist to store
userManager.AddClaim(identity.GetUserId(),claim);
}
public static void RemoveClaim(this IPrincipal currentPrincipal, string key, ApplicationUserManager userManager)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return ;
// check for existing claim and remove it
var existingClaims = identity.FindAll(key);
existingClaims.ForEach(c=> identity.RemoveClaim(c));
//remove old claims from store
var user = userManager.FindById(identity.GetUserId());
var claims = userManager.GetClaims(user.Id);
claims.Where(x => x.Type == key).ToList().ForEach(c => userManager.RemoveClaim(user.Id, c));
}
public static string GetClaimValue(this IPrincipal currentPrincipal, string key)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return null;
var claim = identity.Claims.First(c => c.Type == key);
return claim.Value;
}
public static string GetAllClaims(this IPrincipal currentPrincipal, ApplicationUserManager userManager)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return null;
var claims = userManager.GetClaims(identity.GetUserId());
var userClaims = new StringBuilder();
claims.ForEach(c => userClaims.AppendLine($"<li>{c.Type}, {c.Value}</li>"));
return userClaims.ToString();
}
}
You can use dir(your_object)
to get the attributes and getattr(your_object, your_object_attr)
to get the values
usage :
for att in dir(your_object):
print (att, getattr(your_object,att))
This is particularly useful if your object have no __dict__. If that is not the case you can try var(your_object) also
with hablar::convert
To easily convert multiple columns to different data types you can use hablar::convert
. Simple syntax: df %>% convert(num(a))
converts the column a from df to numeric.
Detailed example
Lets convert all columns of mtcars
to character.
df <- mtcars %>% mutate_all(as.character) %>% as_tibble()
> df
# A tibble: 32 x 11
mpg cyl disp hp drat wt qsec vs am gear carb
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 21 6 160 110 3.9 2.62 16.46 0 1 4 4
2 21 6 160 110 3.9 2.875 17.02 0 1 4 4
3 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
With hablar::convert
:
library(hablar)
# Convert columns to integer, numeric and factor
df %>%
convert(int(cyl, vs),
num(disp:wt),
fct(gear))
results in:
# A tibble: 32 x 11
mpg cyl disp hp drat wt qsec vs am gear carb
<chr> <int> <dbl> <dbl> <dbl> <dbl> <chr> <int> <chr> <fct> <chr>
1 21 6 160 110 3.9 2.62 16.46 0 1 4 4
2 21 6 160 110 3.9 2.88 17.02 0 1 4 4
3 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
4 21.4 6 258 110 3.08 3.22 19.44 1 0 3 1
We were getting an error related to this after a recent release of code to one of our development environments. We have an application that is a child of another application. This relationship has been working fine for YEARS until yesterday.
The problem:
We were getting a yellow stack trace error due to duplicate keys being entered. This is because both the web.config for the child and parent applications had this key. But this existed for many years like this without change. Why all of sudden its an issue now?
The solution:
The reason this was never a problem is because the keys AND values were always the same. Yesterday we updated our SQL connection strings to include the Application Name in the connection string. This made the string unique and all of sudden started to fail.
Without doing any research on the exact reason for this, I have to assume that when the child application inherits the parents web.config values, it ignores identical key/value pairs.
We were able to solve it by wrapping the connection string like this
<location path="." inheritInChildApplications="false">
<connectionStrings>
<!-- Updated connection strings go here -->
</connectionStrings>
</location>
Edit: I forgot to mention that I added this in the PARENTS web.config. I didn't have to modify the child's web.config.
Thanks for everyones help on this, saved our butts.
<div class="dropdown">
<button data-toggle="dropdown">
Sample Button
</button>
<ul class="dropdown-menu">
<li>A</li>
<li>B</li>
<li class="dropdown-divider"></li>
<li>C</li>
</ul>
</div>
This is the sample code for the horizontal divider in bootstrap 4. Output looks like this:
class="dropdown-divider" used in bootstrap 4, while class="divider" used in bootstrap 3 for horizontal divider
That's the easy answer:
$query="SELECT * FROM CountryInfo WHERE Name = '".$name."'";
and you define $name
whatever you want.
And another way, the complex way, is like that:
$query = " SELECT '" . $GLOBALS['Name'] . "' .* " .
" FROM CountryInfo " .
" INNER JOIN District " .
" ON District.CountryInfoId = CountryInfo.CountryInfoId " .
" INNER JOIN City " .
" ON City.DistrictId = District.DistrictId " .
" INNER JOIN '" . $GLOBALS['Name'] . "' " .
" ON '" . $GLOBALS['Name'] . "'.CityId = City.CityId " .
" WHERE CountryInfo.Name = '" . $GLOBALS['CountryName'] .
"'";
If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.
We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.
l = ["a", "b", "c", "d", "e"]
To create a dictionary we can use the built in dict
function for Mapping Types as per the manual the following methods are supported.
dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])
The last option suggests that we supply a list of lists with 2 values or (key, value)
tuples, so we want to turn our sequential list into:
l = [["a", "b"], ["c", "d"], ["e",]]
We are also introduced to the zip
function, one of the built-in functions which the manual explains:
returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments
In other words if we can turn our list into two lists a, c, e
and b, d
then zip
will do the rest.
Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:
>>> l[::2]
['a', 'c', 'e']
>>> l[1::2]
['b', 'd']
>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]
>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}
Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:
>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]
>>> b is a
True
>>> b = a[:]
>>> b
[1, 2, 3]
>>> b is a
False
Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.
Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.
Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.
*[iter(l)]*2
Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.
>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']
>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]
>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]
>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]
>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]
>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}
As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.
You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.
>>> it = iter(l)
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}
What about the empty key e
if you've noticed it has been missing from all the examples which is because zip
picks the shortest of the two arguments, so what are we to do.
Well one solution might be adding an empty value to odd length lists, you may choose to use append
and an if
statement which would do the trick, albeit slightly boring, right?
>>> if len(l) % 2:
... l.append("")
>>> l
['a', 'b', 'c', 'd', 'e', '']
>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}
Now before you shrug away to go type from itertools import izip_longest
you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.
I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None
empty value when required, automagically.
>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']
>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None}
Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.
$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real 0m3.755s
user 0m2.815s
sys 0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real 0m2.102s
user 0m1.451s
sys 0m0.539s
However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.
$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real 0m0.046s
user 0m0.029s
sys 0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real 0m0.067s
user 0m0.042s
sys 0m0.021s
$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real 0m0.074s
user 0m0.050s
sys 0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real 0m0.075s
user 0m0.047s
sys 0m0.024s
See nothing to it! =)
nJoy!
It's a bug in Managed ODP.net - 'Bug 21113901 : MANAGED ODP.NET RAISE ORA-1008 USING SINGLE QUOTED CONST + BIND VAR IN SELECT' fixed in patch 23530387 superseded by patch 24591642
I use something similar all the time, as well as the top-k list of most recently modified files. For large directory trees, it can be much faster to avoid sorting. In the case of just top-1 most recently modified file:
find . -type f -printf '%T@ %p\n' | perl -ne '@a=split(/\s+/, $_, 2); ($t,$f)=@a if $a[0]>$t; print $f if eof()'
On a directory containing 1.7 million files, I get the most recent one in 3.4s, a speed-up of 7.5x against the 25.5s solution using sort.
Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.
If you're on GNU Make, use the :=
assignment instead of =
. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.
FILES := $(shell ...) # expand now; FILES is now the result of $(shell ...)
FILES = $(shell ...) # expand later: FILES holds the syntax $(shell ...)
If you use the =
assignment, it means that every single occurrence of $(FILES)
will be expanding the $(shell ...)
syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.
To answer the initial question "how to properly pass routedata to error controller?":
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Then in your ErrorController class, implement a function like this:
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Error(Exception exception)
{
return View("Error", exception);
}
This pushes the exception into the View. The view page should be declared as follows:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<System.Exception>" %>
And the code to display the error:
<% if(Model != null) { %> <p><b>Detailed error:</b><br /> <span class="error"><%= Helpers.General.GetErrorMessage((Exception)Model, false) %></span></p> <% } %>
Here is the function that gathers the all exception messages from the exception tree:
public static string GetErrorMessage(Exception ex, bool includeStackTrace)
{
StringBuilder msg = new StringBuilder();
BuildErrorMessage(ex, ref msg);
if (includeStackTrace)
{
msg.Append("\n");
msg.Append(ex.StackTrace);
}
return msg.ToString();
}
private static void BuildErrorMessage(Exception ex, ref StringBuilder msg)
{
if (ex != null)
{
msg.Append(ex.Message);
msg.Append("\n");
if (ex.InnerException != null)
{
BuildErrorMessage(ex.InnerException, ref msg);
}
}
}
be careful using isinstance
isinstance(True, bool)
True
>>> isinstance(True, int)
True
but type
type(True) == bool
True
>>> type(True) == int
False
..extending Mikaels' answers
SELECT
CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
...
e0
fixes some ISNUMERIC issues (such as +
-
.
and empty string being accepted)Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.
*.example.com IN A 1.2.3.4
See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html
To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.Net">
<listeners>
<add name="MyTraceFile"/>
<add name="MyConsole"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add
name="MyTraceFile"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="System.Net.trace.log" />
<add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose" />
</switches>
</system.diagnostics>
if by .add
you mean .append
, then the result is the same if #myDiv
is empty.
is the performance the same? dont know.
.html(x)
ends up doing the same thing as .empty().append(x)
In my case I have IBOutlet UILabel *description in .h, it was with yellow /!\ - "will not synthesized", as I remember. Dunno what is it and why only this label.
But I got this crash and error like above. Deleted *description and recreate *description2. No crash in result.