dir /b/s *.txt
searches for all txt file in the directory tree. Before using it just change the directory to root using
cd/
you can also export the list to a text file using
dir /b/s *.exe >> filelist.txt
and search within using
type filelist.txt | find /n "filename"
EDIT 1: Although this dir command works since the old dos days but Win7 added something new called Where
where /r c:\Windows *.exe *.dll
will search for exe & dll in the drive c:\Windows as suggested by @SPottuit you can also copy the output to the clipboard with
where /r c:\Windows *.exe |clip
just wait for the prompt to return and don't copy anything until then.
EDIT 2:
If you are searching recursively and the output is big you can always use more
to enable paging, it will show -- More --
at the bottom and will scroll to the next page once you press SPACE
or moves line by line on pressing ENTER
where /r c:\Windows *.exe |more
For more help try
where/?
@Chris Haas has explained very well how to use itextSharp
to convert HTML
to PDF
, very helpful
my add is:
By using HtmlTextWriter
I put html tags inside HTML
table + inline CSS i got my PDF as I wanted without using XMLWorker
.
Edit: adding sample code:
ASPX page:
<asp:Panel runat="server" ID="PendingOrdersPanel">
<!-- to be shown on PDF-->
<table style="border-spacing: 0;border-collapse: collapse;width:100%;display:none;" >
<tr><td><img src="abc.com/webimages/logo1.png" style="display: none;" width="230" /></td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla.</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:9px;color:#10466E;padding:0px;text-align:right;">blablabla</td></tr>
<tr style="line-height:10px;height:10px;"><td style="display:none;font-size:11px;color:#10466E;padding:0px;text-align:center;"><i>blablabla</i> Pending orders report<br /></td></tr>
</table>
<asp:GridView runat="server" ID="PendingOrdersGV" RowStyle-Wrap="false" AllowPaging="true" PageSize="10" Width="100%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="false"
PagerStyle-CssClass="pgr" HeaderStyle-ForeColor="White" PagerStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" RowStyle-HorizontalAlign="Center" DataKeyNames="Document#"
OnPageIndexChanging="PendingOrdersGV_PageIndexChanging" OnRowDataBound="PendingOrdersGV_RowDataBound" OnRowCommand="PendingOrdersGV_RowCommand">
<EmptyDataTemplate><div style="text-align:center;">no records found</div></EmptyDataTemplate>
<Columns>
<asp:ButtonField CommandName="PendingOrders_Details" DataTextField="Document#" HeaderText="Document #" SortExpression="Document#" ItemStyle-ForeColor="Black" ItemStyle-Font-Underline="true"/>
<asp:BoundField DataField="Order#" HeaderText="order #" SortExpression="Order#"/>
<asp:BoundField DataField="Order Date" HeaderText="Order Date" SortExpression="Order Date" DataFormatString="{0:d}"></asp:BoundField>
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status"></asp:BoundField>
<asp:BoundField DataField="Amount" HeaderText="Amount" SortExpression="Amount" DataFormatString="{0:C2}"></asp:BoundField>
</Columns>
</asp:GridView>
</asp:Panel>
C# code:
protected void PendingOrdersPDF_Click(object sender, EventArgs e)
{
if (PendingOrdersGV.Rows.Count > 0)
{
//to allow paging=false & change style.
PendingOrdersGV.HeaderStyle.ForeColor = System.Drawing.Color.Black;
PendingOrdersGV.BorderColor = Color.Gray;
PendingOrdersGV.Font.Name = "Tahoma";
PendingOrdersGV.DataSource = clsBP.get_PendingOrders(lbl_BP_Id.Text);
PendingOrdersGV.AllowPaging = false;
PendingOrdersGV.Columns[0].Visible = false; //export won't work if there's a link in the gridview
PendingOrdersGV.DataBind();
//to PDF code --Sam
string attachment = "attachment; filename=report.pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
htextw.AddStyleAttribute("font-size", "8pt");
htextw.AddStyleAttribute("color", "Grey");
PendingOrdersPanel.RenderControl(htextw); //Name of the Panel
Document document = new Document();
document = new Document(PageSize.A4, 5, 5, 15, 5);
FontFactory.GetFont("Tahoma", 50, iTextSharp.text.BaseColor.BLUE);
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
StringReader str = new StringReader(stw.ToString());
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.Parse(str);
document.Close();
Response.Write(document);
}
}
of course include iTextSharp Refrences to cs file
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using iTextSharp.tool.xml;
Hope this helps!
Thank you
It is because of virtual enviornment configuration. You need to work on your virtual enviornmnet of Python. You should try on your command promt with,
workon virtual_enviornment_name
You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN)
before you start your cleanup code.
> vec <- c(letters[1:3]) # vec <- c("a","b","c") ; or just empty vector: vec <- c()
> values<- c(1,2,3)
> for (i in 1:length(values)){
print(paste("length of vec", length(vec)));
vec[length(vec)+1] <- values[i] #Appends value at the end of vector
}
[1] "length of vec 3"
[1] "length of vec 4"
[1] "length of vec 5"
> vec
[1] "a" "b" "c" "1" "2" "3"
This single step worked for me... No 2-step verification. As I had created a dummy account for my local development, so I was OK with this setting. Make sure you only do this if your account contains NO personal or any critical data. This is just another way of tackling this error and NOT secure.
I turned ON the setting to alow less secured apps to be allowed access. Form here : https://myaccount.google.com/lesssecureapps
You should use this GBDeviceInfo framework or ...
Apple defines this:
public enum UIUserInterfaceIdiom : Int {
case unspecified
case phone // iPhone and iPod touch style UI
case pad // iPad style UI
@available(iOS 9.0, *)
case tv // Apple TV style UI
@available(iOS 9.0, *)
case carPlay // CarPlay style UI
}
so for the strict definition of the device can be used this code
struct ScreenSize
{
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceType
{
static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
static let IS_IPHONE_6_7 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
static let IS_IPHONE_6P_7P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
static let IS_IPAD_PRO = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0
}
how to use
if DeviceType.IS_IPHONE_6P_7P {
print("IS_IPHONE_6P_7P")
}
to detect iOS version
struct Version{
static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
static let iOS7 = (Version.SYS_VERSION_FLOAT < 8.0 && Version.SYS_VERSION_FLOAT >= 7.0)
static let iOS8 = (Version.SYS_VERSION_FLOAT >= 8.0 && Version.SYS_VERSION_FLOAT < 9.0)
static let iOS9 = (Version.SYS_VERSION_FLOAT >= 9.0 && Version.SYS_VERSION_FLOAT < 10.0)
}
how to use
if Version.iOS8 {
print("iOS8")
}
https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.
'1.0.0.0/8'
to '191.0.0.0/8'
are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:
import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
'0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8',
'169.254.0.0/16', '172.16.0.0/12', '192.0.0.0/24', '192.0.2.0/24',
'192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
'203.0.113.0/24', '224.0.0.0/4', '240.0.0.0/4', '255.255.255.255/32'
)
Generates a JSON dump of IP Addresses and associated Geo information.
Note that the valid public IP Address range is
from '1.0.0.0/8'
to '191.0.0.0/8'
excluding the reserved
Private IP Address ranges shown lower down in this readme.
docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0' geo-ip ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0' geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip
A little faster option for scanning all valid public addresses:
for i in $(seq 1 191); do \
docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
sleep 1; \
done
This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:
{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
"continent": "North America", "continent_code": "NA",
"state": "California", "country": "United States", "latitude": 37.418,
"iso_code": "US", "state_code": "CA", "aso": "PubNub",
"asn": "11404", "zip_code": "94107"}
The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses
The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home
Remove both http and https setting by using commands.
git config --global --unset http.proxy
git config --global --unset https.proxy
I am brand new to WindowBuilder, and, in fact, just getting back into Java after a few years, but I implemented "something", then thought I'd look it up and came across this thread.
I'm in the middle of testing this, so, based on being new to all this, I'm sure I must be missing something.
Here's what I did, where "runTxt" is a textbox and "runName" is a data member of the class:
public void focusGained(FocusEvent e) {
if (e.getSource() == runTxt) {
System.out.println("runTxt got focus");
runTxt.selectAll();
}
}
public void focusLost(FocusEvent e) {
if (e.getSource() == runTxt) {
System.out.println("runTxt lost focus");
if(!runTxt.getText().equals(runName))runName= runTxt.getText();
System.out.println("runText.getText()= " + runTxt.getText() + "; runName= " + runName);
}
}
Seems a lot simpler than what's here so far, and seems to be working, but, since I'm in the middle of writing this, I'd appreciate hearing of any overlooked gotchas. Is it an issue that the user could enter & leave the textbox w/o making a change? I think all you've done is an unnecessary assignment.
Seems I don't have enough rep to post a comment, so another answer will have to do.
When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.
Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()
function purge(d) {
var a = d.attributes, i, l, n;
if (a) {
for (i = a.length - 1; i >= 0; i -= 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}
And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.
And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.
During initial testing for Membership.ValidateUser with a SqlMembershipProvider, I use a hash (SHA1) algorithm combined with a salt, and, if I changed the salt length to a length not divisible by four, I received this error.
I have not tried any of the fixes above, but if the salt is being altered, this may help someone pinpoint that as the source of this particular error.
This works well for me:
from matplotlib import pyplot as plt
F = plt.gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True) # Set forward to True to resize window along with plot in figure.
plt.show() # or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array
This might also help: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html
You have added the add marker method call outside the function and that causes it to execute before the initialize method which will be called when google maps script loads and thus the marker is not added because map is not initialized Do as below.... Create separate method TestMarker and call it from initialize.
<script type="text/javascript">
// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
TestMarker();
}
// Function for adding a marker to the page.
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Testing the addMarker function
function TestMarker() {
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
addMarker(CentralPark);
}
</script>
There is a way to increase character using ascii_letters
from string
package which ascii_letters
is a string that contains all English alphabet, uppercase and lowercase:
>>> from string import ascii_letters
>>> ascii_letters[ascii_letters.index('a') + 1]
'b'
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Also it can be done manually;
>>> letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> letters[letters.index('c') + 1]
'd'
Almost same problem get resolved by creating a geoexplorer.xml file in /opt/apache-tomcat-8.5.37/conf/Catalina/localhost content of geoexplorer.xml file is
<Context displayName="geoexplorer" docBase="/usr/share/opengeo/geoexplorer" path="/geoexplorer"/>
A Monitor is an object designed to be accessed from multiple threads. The member functions or methods of a monitor object will enforce mutual exclusion, so only one thread may be performing any action on the object at a given time. If one thread is currently executing a member function of the object then any other thread that tries to call a member function of that object will have to wait until the first has finished.
A Semaphore is a lower-level object. You might well use a semaphore to implement a monitor. A semaphore essentially is just a counter. When the counter is positive, if a thread tries to acquire the semaphore then it is allowed, and the counter is decremented. When a thread is done then it releases the semaphore, and increments the counter.
If the counter is already zero when a thread tries to acquire the semaphore then it has to wait until another thread releases the semaphore. If multiple threads are waiting when a thread releases a semaphore then one of them gets it. The thread that releases a semaphore need not be the same thread that acquired it.
A monitor is like a public toilet. Only one person can enter at a time. They lock the door to prevent anyone else coming in, do their stuff, and then unlock it when they leave.
A semaphore is like a bike hire place. They have a certain number of bikes. If you try and hire a bike and they have one free then you can take it, otherwise you must wait. When someone returns their bike then someone else can take it. If you have a bike then you can give it to someone else to return --- the bike hire place doesn't care who returns it, as long as they get their bike back.
Math.NET is an opensource library that offers a method for calculating the Median. The nuget package is called MathNet.Numerics.
The usage is pretty simple:
using MathNet.Numerics.Statistics;
IEnumerable<double> data;
double median = data.Median();
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
You can use the base64
module to encode strings to stop shoulder surfing, but it's not going to stop someone finding your code if they have access to your files.
You can then use the compile()
function and the eval()
function to execute your code once you've decoded it.
>>> import base64
>>> mycode = "print 'Hello World!'"
>>> secret = base64.b64encode(mycode)
>>> secret
'cHJpbnQgJ2hlbGxvIFdvcmxkICEn'
>>> mydecode = base64.b64decode(secret)
>>> eval(compile(mydecode,'<string>','exec'))
Hello World!
So if you have 30 lines of code you'll probably want to encrypt it doing something like this:
>>> f = open('myscript.py')
>>> encoded = base64.b64encode(f.read())
You'd then need to write a second script that does the compile()
and eval()
which would probably include the encoded script as a string literal encased in triple quotes. So it would look something like this:
import base64
myscript = """IyBUaGlzIGlzIGEgc2FtcGxlIFB5d
GhvbiBzY3JpcHQKcHJpbnQgIkhlbG
xvIiwKcHJpbnQgIldvcmxkISIK"""
eval(compile(base64.b64decode(myscript),'<string>','exec'))
char buffer [50];
unsigned long a = 5;
int n=sprintf (buffer, "%lu", a);
I have to display files of computer code. If special characters are inside the file like less than or greater than, a simple "include" will not display them. Try:
$file = 'code.ino';
$orig = file_get_contents($file);
$a = htmlentities($orig);
echo '<code>';
echo '<pre>';
echo $a;
echo '</pre>';
echo '</code>';
You can do one of the following:
<?php
$data = 'My data';
function menugen() {
global $data;
echo "[" . $data . "]";
}
menugen();
Or
<?php
$data = 'My data';
function menugen() {
echo "[" . $GLOBALS['data'] . "]";
}
menugen();
That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example, instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called dependency injection. It makes your life a lot easier when you implement automated testing (which you should).
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}
Then, on the server side (i.e. myscript.php):
$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg
in /uploads/
on your server, and respond with a JSON variable (to a continueSubmission()
function) containing the fileName on the server.
Check out fwrite()
and jQuery.post()
.
On the above page it details how to use readAsBinaryString()
, readAsDataUrl()
, and readAsArrayBuffer()
for your other needs (e.g. images, videos, etc).
extension String{
func widthWithConstrainedHeight(_ height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.width)
}
func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat? {
let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.height)
}
}
Another approach is to use Collectors.groupingBy
of indices and then map the grouped indices to the actual elements:
final List<Integer> numbers = range(1, 12)
.boxed()
.collect(toList());
System.out.println(numbers);
final List<List<Integer>> groups = range(0, numbers.size())
.boxed()
.collect(groupingBy(index -> index / 4))
.values()
.stream()
.map(indices -> indices
.stream()
.map(numbers::get)
.collect(toList()))
.collect(toList());
System.out.println(groups);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]
Yes you can insert but not as similar to SQL.
In SQL we can insert the row level data, but here you can insert by fields (columns).
During this you have to make sure target table and the query should have same datatype and same number of columns.
eg:
CREATE TABLE test(stu_name STRING,stu_id INT,stu_marks INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE;
INSERT OVERWRITE TABLE test SELECT lang_name, lang_id, lang_legacy_id FROM export_table;
The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:
var len = menuitems.length;
for (var i = 0; i < len; i++){
(function(i) {
$('<li/>',{
'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
'click':function(){
menuitems[i].action();
},
'class':o.itemClass
}).appendTo('.'+o.listClass);
})(i);
}
In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token.
[Edit: In response to the incorrect "Just for the record" comment below that unfortunately received several upvotes, I will reiterate the statement above and observe that the program fragment
#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")
produces this error message from the preprocessing phase of gcc: error: pasting ""s"" and ""1"" does not give a valid preprocessing token
]
However, for general token pasting, try this:
/*
* Concatenate preprocessor tokens A and B without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define PPCAT_NX(A, B) A ## B
/*
* Concatenate preprocessor tokens A and B after macro-expanding them.
*/
#define PPCAT(A, B) PPCAT_NX(A, B)
Then, e.g., both PPCAT_NX(s, 1)
and PPCAT(s, 1)
produce the identifier s1
, unless s
is defined as a macro, in which case PPCAT(s, 1)
produces <macro value of s>1
.
Continuing on the theme are these macros:
/*
* Turn A into a string literal without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define STRINGIZE_NX(A) #A
/*
* Turn A into a string literal after macro-expanding it.
*/
#define STRINGIZE(A) STRINGIZE_NX(A)
Then,
#define T1 s
#define T2 1
STRINGIZE(PPCAT(T1, T2)) // produces "s1"
By contrast,
STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"
STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"
#define T1T2 visit the zoo
STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"
STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"
I made on this way, and work properly to me:
if (listview1.Items.Count > 0)
{
for (int a = listview1.Items.Count -1; a > 0 ; a--)
{
listview1.Items.RemoveAt(a);
}
listview1.Refresh();
}
Explaining: using "Clear()" erases only the items, do not removes then from object, using RemoveAt() to removing an item of beginning position just realocate the others [if u remove item[0], item[1] turns into [0] triggering a new internal event], so removing from the ending no affect de others position, its a Stack behavior, this way we can Stack over all items, reseting the object.
You have to use git clean -f -d
to get rid of untracked files and directories in your working copy.
You can add -x
to also remove ignored files, more info on that in this excellent SO answer.
If you need to reset an entire repository with submodules to the state on master, run this script:
git fetch origin master
git checkout --force -B master origin/master
git reset --hard
git clean -fdx
git submodule update --init --recursive --force
git submodule foreach git fetch
git submodule foreach git checkout --force -B master origin/master
git submodule foreach git reset --hard
git submodule foreach git clean -fdx
The best that I've been able to do is
$(this).closest('.modal').modal('toggle');
This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.
You can however do this:
$(".modal:visible").modal('toggle');
This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"
Reinstall java and choose a destination folder without a space
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
The accepted answer didn't quite work for me as I got a 502 Bad Gateway result from the ajax call even though everything seemed to be returning fine from the controller.
Perhaps I was hitting a limit with TempData - not sure, but I found that if I used IMemoryCache instead of TempData, it worked fine, so here is my adapted version of the code in the accepted answer:
public ActionResult PostReportPartial(ReportVM model){
// Validate the Model is correct and contains valid data
// Generate your report output based on the model parameters
// This can be an Excel, PDF, Word file - whatever you need.
// As an example lets assume we've generated an EPPlus ExcelPackage
ExcelPackage workbook = new ExcelPackage();
// Do something to populate your workbook
// Generate a new unique identifier against which the file can be stored
string handle = Guid.NewGuid().ToString();
using(MemoryStream memoryStream = new MemoryStream()){
workbook.SaveAs(memoryStream);
memoryStream.Position = 0;
//TempData[handle] = memoryStream.ToArray();
//This is an equivalent to tempdata, but requires manual cleanup
_cache.Set(handle, memoryStream.ToArray(),
new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(10)));
//(I'd recommend you revise the expiration specifics to suit your application)
}
// Note we are returning a filename as well as the handle
return new JsonResult() {
Data = new { FileGuid = handle, FileName = "TestReportOutput.xlsx" }
};
}
AJAX call remains as with the accepted answer (I made no changes):
$ajax({
cache: false,
url: '/Report/PostReportPartial',
data: _form.serialize(),
success: function (data){
var response = JSON.parse(data);
window.location = '/Report/Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
The controller action to handle the downloading of the file:
[HttpGet]
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (_cache.Get<byte[]>(fileGuid) != null)
{
byte[] data = _cache.Get<byte[]>(fileGuid);
_cache.Remove(fileGuid); //cleanup here as we don't need it in cache anymore
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
// Something has gone wrong...
return View("Error"); // or whatever/wherever you want to return the user
}
}
...
Now there is some extra code for setting up MemoryCache...
In order to use "_cache" I injected in the constructor for the controller like so:
using Microsoft.Extensions.Caching.Memory;
namespace MySolution.Project.Controllers
{
public class MyController : Controller
{
private readonly IMemoryCache _cache;
public LogController(IMemoryCache cache)
{
_cache = cache;
}
//rest of controller code here
}
}
And make sure you have the following in ConfigureServices in Startup.cs:
services.AddDistributedMemoryCache();
Adding to the accepted answer, you can used DATABASE_DEFAULT
as encoding.
This allows database to make choice for you and your code becomes more portable.
SELECT MyColumn
FROM
FirstTable a
INNER JOIN SecondTable b
ON a.MyID COLLATE DATABASE_DEFAULT = b.YourID COLLATE DATABASE_DEFAULT
Ensure you have Project | Build Automatically flagged. I ran into this issue too and turning that on fixed the problem.
You can use git log -L to view the evolution of a range of lines.
For example :
git log -L 15,23:filename.txt
means "trace the evolution of lines 15 to 23 in the file named filename.txt".
because of two way binding, To prevent error of:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was
checked.
you can call a function to change model like this:
<input [ngModel]="item.value"
(ngModelChange)="getNewValue($event)" name="inputField" type="text" />
import { UseMyPipeToFormatThatValuePipe } from './path';
constructor({
private UseMyPipeToFormatThatValue: UseMyPipeToFormatThatValuePipe,
})
getNewValue(ev: any): any {
item.value= this.useMyPipeToFormatThatValue.transform(ev);
}
it'll be good if there is a better solution to prevent this error.
Include servlet-api.jar from your server lib folder.
Do this step
In my case even after uninstalling all 2005 related components it didn't worked. I had to resort to a brute force way and remove following registry keys
32 Bit OS: HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\90
64 Bit OS: HKLM\Software\Wow6432Node\Microsoft\Microsoft SQL Server\90
If you need the port number also, you can use
Request.Url.Authority
Example:
string url = Request.Url.Authority + HttpContext.Current.Request.RawUrl.ToString();
if (Request.ServerVariables["HTTPS"] == "on")
{
url = "https://" + url;
}
else
{
url = "http://" + url;
}
Just posting the Array syntax for same column OR queries to help peeps out.
Person.where(name: ["John", "Steve"])
I encourage you to read the article: Violating Liskov Substitution Principle (LSP).
You can find there an explanation what is the Liskov Substitution Principle, general clues helping you to guess if you have already violated it and an example of approach that will help you to make your class hierarchy be more safe.
Java supports two types of comments:
/* multiline comment */
: The compiler ignores everything from /*
to */
. The comment can span over multiple lines.
// single line
: The compiler ignores everything from //
to the end of the line.
Some tool such as javadoc use a special multiline comment for their purpose. For example /** doc comment */
is a documentation comment used by javadoc when preparing the automatically generated documentation, but for Java it's a simple multiline comment.
java.util.Date.from( // Transfer the moment in UTC, truncating any microseconds or nanoseconds to milliseconds.
Instant.now() ; // Capture current moment in UTC, with resolution as fine as nanoseconds.
)
Though there was no point in that code above. Both java.util.Date
and Instant
represent a moment in UTC, always in UTC. Code above has same effect as:
new java.util.Date() // Capture current moment in UTC.
No benefit here to using ZonedDateTime
. If you already have a ZonedDateTime
, adjust to UTC by extracting a Instant
.
java.util.Date.from( // Truncates any micros/nanos.
myZonedDateTime.toInstant() // Adjust to UTC. Same moment, same point on the timeline, different wall-clock time.
)
The Answer by ssoltanid correctly addresses your specific question, how to convert a new-school java.time object (ZonedDateTime
) to an old-school java.util.Date
object. Extract the Instant
from the ZonedDateTime and pass to java.util.Date.from()
.
Note that you will suffer data loss, as Instant
tracks nanoseconds since epoch while java.util.Date
tracks milliseconds since epoch.
Your Question and comments raise other issues.
Your servers should have their host OS set to UTC as a best practice generally. The JVM picks up on this host OS setting as its default time zone, in the Java implementations that I'm aware of.
But you should never rely on the JVM’s current default time zone. Rather than pick up the host setting, a flag passed when launching a JVM can set another time zone. Even worse: Any code in any thread of any app at any moment can make a call to java.util.TimeZone::setDefault
to change that default at runtime!
Timestamp
TypeAny decent database and driver should automatically handle adjusting a passed date-time to UTC for storage. I do not use Cassandra, but it does seem to have some rudimentary support for date-time. The documentation says its Timestamp
type is a count of milliseconds from the same epoch (first moment of 1970 in UTC).
Furthermore, Cassandra accepts string inputs in the ISO 8601 standard formats. Fortunately, java.time uses ISO 8601 formats as its defaults for parsing/generating strings. The Instant
class’ toString
implementation will do nicely.
But first we need to reduce the nanosecond precision of ZonedDateTime to milliseconds. One way is to create a fresh Instant using milliseconds. Fortunately, java.time has some handy methods for converting to and from milliseconds.
Here is some example code in Java 8 Update 60.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
…
Instant instant = zdt.toInstant();
Instant instantTruncatedToMilliseconds = Instant.ofEpochMilli( instant.toEpochMilli() );
String fodderForCassandra = instantTruncatedToMilliseconds.toString(); // Example: 2015-08-18T06:36:40.321Z
Or according to this Cassandra Java driver doc, you can pass a java.util.Date
instance (not to be confused with java.sqlDate
). So you could make a j.u.Date from that instantTruncatedToMilliseconds
in the code above.
java.util.Date dateForCassandra = java.util.Date.from( instantTruncatedToMilliseconds );
If doing this often, you could make a one-liner.
java.util.Date dateForCassandra = java.util.Date.from( zdt.toInstant() );
But it would be neater to create a little utility method.
static public java.util.Date toJavaUtilDateFromZonedDateTime ( ZonedDateTime zdt ) {
Instant instant = zdt.toInstant();
// Data-loss, going from nanosecond resolution to milliseconds.
java.util.Date utilDate = java.util.Date.from( instant ) ;
return utilDate;
}
Notice the difference in all this code than in the Question. The Question’s code was trying to adjust the time zone of the ZonedDateTime instance to UTC. But that is not necessary. Conceptually:
ZonedDateTime = Instant + ZoneId
We just extract the Instant part, which is already in UTC (basically in UTC, read the class doc for precise details).
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Apparently there is not much out there. And a lot of doubt that someone would be willing to provide such a repository. So I solved the problem myself, and am sharing my dataset with anyone else who finds themselves facing the same problem.
Add the "extern" keyword to the function definitions in point.h
from within the vscode terminal,
git remote set-url origin https://<your github username>:<your password>@github.com/<your github username>/<your github repository name>.git
for the quickest, but not so encouraged way.
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';
import {Service} from "path/to/service/";
@Injectable()
export class MovieDbService implements OnInit {
userId:number=null;
constructor(private _movieDbRest: RestApiService,
private instanceMyService : Service ){
// do evreything like OnInit just on services
this._movieDbRest.callAnyMethod();
this.userId = this.instanceMyService.getUserId()
}
You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.
true, this option is not available in any version of MS ppt.Now the solution is that You put your different sized slide in other file and put a hyperlink in first file.
Run it under a different user name, using "runas" or by scheduling it under a different user in Windows Scheduled Tasks.
Well, there's an alternate way! You can use a button instead of hyperlink. Hence, when the button is clicked the web page specified in "name_of_webpage" is opened in the target frame named "name_of_iframe". It works for me!
<form method="post" action="name_of_webpage" target="name_of_iframe">
<input type="submit" value="any_name_you_want" />
</form>
<iframe name="name_of_iframe"></iframe>
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):
virtualenv
is a tool to create isolated Python environments.The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into
/usr/lib/python2.7/site-packages
(or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global
site-packages
directory? For instance, on a shared host.In all these cases,
virtualenv
can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).
That's why people consider insert(0,
to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.
Well, for me this is the expected result; adding six months to Jan. 1st July.
mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01 |
+--------------------------------------------+
These lines in your makefile,
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h
and this line in your .cpp file,
#include "StdCUtil/split.h"
are in conflict.
With your makefile in your source directory and with that -I
option you should be using #include "split.h"
in your source file, and your dependency should be ../StdCUtil/split.h
.
Another option:
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/.. # Ugly!
DEPS = $(INC_DIR)/split.h
With this your #include
directive would remain as #include "StdCUtil/split.h"
.
Yet another option is to place your makefile in the parent directory:
root
|____Makefile
|
|___Core
| |____DBC.cpp
| |____Lock.cpp
| |____Trace.cpp
|
|___StdCUtil
|___split.h
With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core
and StdCUtil
directories. Object
, for example. With this, your makefile becomes:
INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.
DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.
all: $(OBJS)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
$(CC) $(CFLAGS) -c $< -o $@
$(OBJ_DIR)/Trace.o: $(DEPS)
As others have explained, var self = this;
allows code in a closure to refer back to the parent scope.
However, it's now 2018 and ES6 is widely supported by all major web browsers. The var self = this;
idiom isn't quite as essential as it once was.
It's now possible to avoid var self = this;
through the use of arrow functions.
In instances where we would have used var self = this
:
function test() {
var self = this;
this.hello = "world";
document.getElementById("test_btn").addEventListener("click", function() {
console.log(self.hello); // logs "world"
});
};
We can now use an arrow function without var self = this
:
function test() {
this.hello = "world";
document.getElementById("test_btn").addEventListener("click", () => {
console.log(this.hello); // logs "world"
});
};
Arrow functions do not have their own this
and simply assume the enclosing scope.
Just escape the "\"
by using + "\\Tasks"
or use a verbatim string like @"\Tasks"
Try this:
It looks like you are looping for every product each time, now this is looping for each product that has the same category ID as the current category being looped
<div id="accordion1" style="text-align:justify">
@using (Html.BeginForm())
{
foreach (var category in Model.Categories)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in Model.Product.Where(m=> m.CategoryID= category.CategoryID)
{
<li>
@product.Title
@if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
{
@Html.Raw(" - ")
@Html.ActionLink("Edit", "Edit", new { id = product.ID })
}
<ul>
<li>
@product.Description
</li>
</ul>
</li>
}
</ul>
</div>
}
}
A statement contains a keyword.
An expression does not contain a keyword.
print "hello"
is statement, because print
is a keyword.
"hello"
is an expression, but list compression is against this.
The following is an expression statement, and it is true without list comprehension:
(x*2 for x in range(10))
This
PRIMARY KEY (
id
(11))
is generated automatically by phpmyadmin, change to
PRIMARY KEY (
id
)
.
these extras prove useful.. need to be executed as an administrator
sc create <service_name> binpath=<binary_path>
sc stop <service_name>
sc queryex <service_name>
sc delete <service_name>
If your service name has any spaces, enclose in "quotes".
WebApiConfig.Register(GlobalConfiguration.Configuration); should be on top.
No, you should not add them to source control since - as you said - they're user specific.
SUO (Solution User Options): Records all of the options that you might associate with your solution so that each time you open it, it includes customizations that you have made.
The .user file contains the user options for the project (while SUO is for the solution) and extends the project file name (e.g. anything.csproj.user contains user settings for the anything.csproj project).
Building on Joe's idea, here is a version which will build its own (.js
) helper and supporting time as well:
@echo off
set _TMP=%TEMP%\_datetime.tmp
echo var date = new Date(), string, tmp;> "%_TMP%"
echo tmp = ^"000^" + date.getFullYear(); string = tmp.substr(tmp.length - 4);>> "%_TMP%"
echo tmp = ^"0^" + (date.getMonth() + 1); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getDate(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getHours(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getMinutes(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getSeconds(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo WScript.Echo(string);>> "%_TMP%"
for /f %%i in ('cscript //nologo /e:jscript "%_TMP%"') do set _DATETIME=%%i
del "%_TMP%"
echo YYYYMMDDhhmmss: %_DATETIME%
echo YYYY: %_DATETIME:~0,4%
echo YYYYMM: %_DATETIME:~0,6%
echo YYYYMMDD: %_DATETIME:~0,8%
echo hhmm: %_DATETIME:~8,4%
echo hhmmss: %_DATETIME:~8,6%
Here's my suggestion:
function toCamelCase(string) {
return `${string}`
.replace(new RegExp(/[-_]+/, 'g'), ' ')
.replace(new RegExp(/[^\w\s]/, 'g'), '')
.replace(
new RegExp(/\s+(.)(\w+)/, 'g'),
($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
)
.replace(new RegExp(/\s/, 'g'), '')
.replace(new RegExp(/\w/), s => s.toLowerCase());
}
or
String.prototype.toCamelCase = function() {
return this
.replace(new RegExp(/[-_]+/, 'g'), ' ')
.replace(new RegExp(/[^\w\s]/, 'g'), '')
.replace(
new RegExp(/\s+(.)(\w+)/, 'g'),
($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
)
.replace(new RegExp(/\s/, 'g'), '')
.replace(new RegExp(/\w/), s => s.toLowerCase());
};
Test cases:
describe('String to camel case', function() {
it('should return a camel cased string', function() {
chai.assert.equal(toCamelCase('foo bar'), 'fooBar');
chai.assert.equal(toCamelCase('Foo Bar'), 'fooBar');
chai.assert.equal(toCamelCase('fooBar'), 'fooBar');
chai.assert.equal(toCamelCase('FooBar'), 'fooBar');
chai.assert.equal(toCamelCase('--foo-bar--'), 'fooBar');
chai.assert.equal(toCamelCase('__FOO_BAR__'), 'fooBar');
chai.assert.equal(toCamelCase('!--foo-¿?-bar--121-**%'), 'fooBar121');
});
});
Comment out the /etc/mongod.conf file's bind_ip
Download https://download.robomongo.org/0.9.0-rc9/windows/robomongo-0.9.0-rc9-windows-x86_64-0bb5668.exe
Connection tab:
3.1 Name (whatever)
3.2 Address (IP address of the server) : Port number (27017)
SSH tab (I used my normal PuTTY connection details)
4.1 SSH Address: (IP address of server)
4.2 SSH User Name (User Name)
4.3 User Password (password)
There isn't specifically an attribute to control that. Marquee isn't a highly reliable tag anyways. You may want to consider using jQuery and the .animate() function. If you are interested in pursuing that avenue and need code for it, just let me know.
With Ctrl + Shift + L you can open the "key assist", where you can find all the shortcuts.
I find the Code Metrics and Dependency Structure Matrix add-ins for Reflector very useful.
= f.input_field :title, as: :hidden, value: "some value"
Is also an option. Note, however, that it skips any wrapper defined for your form builder.
Set up a flux container
simple example
import alt from './../../alt.js';
class PostActions {
constructor(){
this.generateActions('setMessages');
}
setMessages(indexArray){
this.actions.setMessages(indexArray);
}
}
export default alt.createActions(PostActions);
store looks like this
class PostStore{
constructor(){
this.messages = [];
this.bindActions(MessageActions);
}
setMessages(messages){
this.messages = messages;
}
}
export default alt.createStore(PostStore);
Then every component that listens to the store can share this variable In your constructor is where you should grab it
constructor(props){
super(props);
//here is your data you get from the store, do what you want with it
var messageStore = MessageStore.getState();
}
componentDidMount() {
MessageStore.listen(this.onMessageChange.bind(this));
}
componentWillUnmount() {
MessageStore.unlisten(this.onMessageChange.bind(this));
}
onMessageChange(state){
//if the data ever changes each component listining will be notified and can do the proper processing.
}
This way, you can share you data across the app without every component having to communicate with each other.
Faced with this same problem, I discovered if you have committed and/or pushed to remote since your successful cherry-pick, and you want to remove it, you can find the cherry-pick's SHA by running:
git log --graph --decorate --oneline
Then, (after using :wq
to exit the log) you can remove the cherry-pick using
git rebase -p --onto YOUR_SHA_HERE^ YOUR_SHA_HERE
where YOUR_SHA_HERE
equals the cherry-picked commit's 40- or abbreviated 7-character SHA.
At first, you won't be able to push your changes because your remote repo and your local repo will have different commit histories. You can force your local commits to replace what's on your remote by using
git push --force origin YOUR_REPO_NAME
(I adapted this solution from Seth Robertson: See "Removing an entire commit.")
I was having this problem and added this JavaScript to the bottom of my page (read it at https://www.webtrickshome.com/faq/how-to-stop-form-resubmission-on-page-refresh) and it seemed to work. It seems much simpler a solution. Any drawbacks?
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
Thanks,
doug
git checkout BranchB
git merge BranchA
git push origin BranchB
This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.
Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.
Make sure you are in the branch where you want to copy all the changes to. git merge
will take the branch you specify and merge it with the branch you are currently in.
I used the answer that Pavel suggested and it worked for me. My difference was to do it while I was adding the remote like so: git remote add (alias) https://(name:password)@github.com/(the remote address).git
name = "John" // your variable
result = (name+" ")[:15] # this adds 15 spaces to the "name"
# but cuts it at 15 characters
Ok so I was having this issue where I tried several different options.
The font i'm using is Ubuntu-LI , I created a font folder in my working directory. under the folder fonts
I was able to apply it... eventually here is my working code
I wanted this to apply to my entire website so I put it at the top of the css doc. above all of the Div tags (not that it matters, just know that any individual fonts you assign post your script will take precedence)
@font-face{
font-family: "Ubuntu-LI";
src: url("/fonts/Ubuntu/(Ubuntu-LI.ttf"),
url("../fonts/Ubuntu/Ubuntu-LI.ttf");
}
*{
font-family:"Ubuntu-LI";
}
If i then wanted all of my H1 tags to be something else lets say sans sarif I would do something like
h1{
font-family: Sans-sarif;
}
From which case only my H1 tags would be the sans-sarif font and the rest of my page would be the Ubuntu-LI font
Very easy solution with jQuery:
$('#myFormId').attr('action', 'myNewActionTarget.html');
Your form:
<form action=get_action() id="myFormId">
...
</form>
This is my solution. It works also in Fragment.
webView.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
As ExpandoObject
inherits the IDictionary<string, object>
you can use the following check
dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();
if (((IDictionary<string, object>)myVariable).ContainsKey("MyProperty"))
//Do stuff
You can make a utility method to perform this check, that will make the code much cleaner and re-usable
To find the top 25 files in the current directory and its subdirectories:
find . -type f -exec ls -al {} \; | sort -nr -k5 | head -n 25
This will output the top 25 files by sorting based on the size of the files via the "sort -nr -k5" piped command.
Same but with human-readable file sizes:
find . -type f -exec ls -alh {} \; | sort -hr -k5 | head -n 25
To round up an integer division you can use
import static java.lang.Math.abs;
public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}
or if both numbers are positive
public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}
For multiple interval types use a nested construction as in:
UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)
For updating a given date in the column date
to 1 year + 1 day
There is the .update() method :)
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.
Of course, if you don't need really floating-point arithmetic, just arithmetic on e.g. dollar values where there are always exactly two decimal digits, you might just drop the dot (effectively multiplying by 100) and compare the resulting integers.
if [[ $((10#${num1/.})) < $((10#${num2/.})) ]]; then
...
This obviously requires you to be sure that both values have the same number of decimal places.
You can do that in this way:
ORDER BY `products`.`product_category_id` DESC ,`naam` ASC
Have a look at ORDER BY
Optimization
This is how I achieved having created and updated.
Inside my schema I added the created and updated like so:
/** * Article Schema */ var ArticleSchema = new Schema({ created: { type: Date, default: Date.now }, updated: { type: Date, default: Date.now }, title: { type: String, default: '', trim: true, required: 'Title cannot be blank' }, content: { type: String, default: '', trim: true }, user: { type: Schema.ObjectId, ref: 'User' } });
Then in my article update method inside the article controller I added:
/** * Update a article */ exports.update = function(req, res) { var article = req.article; article = _.extend(article, req.body); article.set("updated", Date.now()); article.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(article); } }); };
The bold sections are the parts of interest.
There might be several reasons for this.
You need to alias the subquery.
SELECT name FROM (SELECT name FROM agentinformation) a
or to be more explicit
SELECT a.name FROM (SELECT name FROM agentinformation) a
I am using Intellij IDEA and same error happened to me, I found that the path to genymotion
folder was not configured properly. Either open settings using File > Settings
or press Ctrl + Alt + S
then in IDE Settings
check if the path to the genymotion
folder is correct or not.
Since Android Studio
are almost similar to Intellij IDEA
so you can apply the same steps above to Android Studio
as well.
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
Here is an example using a cURL call.. This is better than the file_get_contents() function. Of course, use base64_encode()
$url = "http://example.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
?>
<img src="data:image/png;base64,<?php echo base64_encode($output);?>">
I think you can do this with the hyperref
package, although I've not tried it myself. From the relevant LaTeX Wikibook section:
The
hyperref
package introduces another useful command;\autoref{}
. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command\autoref{sec:intro}
would create a hyperlink to the\label{sec:intro}
command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining\typeautorefname
to the prefix you want, as in:
\def\subsectionautorefname{section}
Have a look at the content by type web part - http://codeplex.com/eoffice - probably the most flexible viewing web part.
I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.
TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();
And add below permission into your Androidmanifest.xml
file.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Let me know if there is any issue.
first ensure that your table storage engine type should be innoDB (you can set it using Table operations Tab)
if you are using new phpmyadmin then use new "Relation view" tab to make foreign key relation
if you are using old version of phpmyadmin then the "relation view" button will show on the bottom of the table columns
Came across this late, but I think it could use another answer.
If you're using sass, you can actually change the variables before you import bootstrap. http://twitter.github.com/bootstrap/customize.html#variables
Change any of them, such as:
$bodyBackground: red;
@import "bootstrap";
Alternatively if there isn't a variable available for what you want to change, you can override the styles or add your own.
Sass:
@import "bootstrap";
/* override anything manually, like rounded buttons */
.btn {
border-radius: 0;
}
Also see this: Proper SCSS Asset Structure in Rails
As far as I can tell after reading the docs for javadoc there is no such feature.
Don't use <code>foo</code>
as recommended in other answers; you can use {@code foo}
. This is especially good to know when you refer to a generic type such as {@code Iterator<String>}
-- sure looks nicer than <code>Iterator<String></code>
, doesn't it!
Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show
them to see the diff and use patch -R
to unapply them.
is_numeric would accept "-0.5e+12" as a valid ID.
Additionally, if you set a layout_weight
, this supersedes the numStars
attribute.
If you already have the databinding in place John Myczek answer is complete.
If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in
line with most guidelines, like MVVM)
option 1: like JohnB said. But I think you should use your own defined collection instead of a weakly typed DataTable (no offense, but you can't tell from the code what each column represents)
xaml.cs
DataContext = myCollection;
//myCollection is a `ICollection<YourType>` preferably
`ObservableCollection<YourType>
- option 2) Declare the name of the Datagrid in xaml
<WpfToolkit:DataGrid Name=dataGrid}>
in xaml.cs
CollectionView myCollectionView =
(CollectionView)CollectionViewSource.GetDefaultView(yourCollection);
dataGrid.ItemsSource = myCollectionView;
If your type has a property FirstName defined, you can then do what John Myczek pointed out.
DataGridTextColumn textColumn = new DataGridTextColumn();
dataColumn.Header = "First Name";
dataColumn.Binding = new Binding("FirstName");
dataGrid.Columns.Add(textColumn);
This obviously doesn't work if you don't know properties you will need to show in your dataGrid, but if that is the case you will have more problems to deal with, and I believe that's out of scope here.
>>> " xyz ".rstrip()
' xyz'
There is more about rstrip
in the documentation.
This I think is the simplest way to do it using JSON stringify, and it may be the best solution in some situations:
JSON.stringify(a1) === JSON.stringify(a2);
This converts the objects a1
and a2
into strings so they can be compared. The order is important in most cases, for that can sort the object using a sort algorithm shown in one of the above answers.
Please do note that you are no longer comparing the object but the string representation of the object. It may not be exactly what you want.
I just now searched for this as I'm in a similar situation, and instead of kill -9 698
I tried sudo kill 428
where 428 was the pid of the process I'm trying to kill. It worked cleanly for me, in the absence of the hyphen '-' character. I hope it helps!
IMHO you can't compare SOAP and REST where those are two different things.
SOAP is a protocol and REST is a software architectural pattern. There is a lot of misconception in the internet for SOAP vs REST.
SOAP defines XML based message format that web service-enabled applications use to communicate each other over the internet. In order to do that the applications need prior knowledge of the message contract, datatypes, etc..
REST represents the state(as resources) of a server from an URL.It is stateless and clients should not have prior knowledge to interact with server beyond the understanding of hypermedia.
I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.
In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.
The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told
<body>
<a id=id_page href ="#loving" onclick="load_services()"> loving </a>
<script>
// This script MUST BE under the "ID" that is calling
// Do not transfer it to a differ DIV than the caller "ID"
document.getElementById("id_page").addEventListener("click", function(){
document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
</script>
</body>
<div id="mainbody" class="main_body">
"here is loaded the external html file when the loving link will
be clicked. "
</div>
Suppose I have a model User
User.find(id)
Returns a row where primary key = id. The return type will be User
object.
User.find_by(email:"[email protected]")
Returns first row with matching attribute or email in this case. Return type will be User
object again.
Note :- User.find_by(email: "[email protected]")
is similar to User.find_by_email("[email protected]")
User.where(project_id:1)
Returns all users in users table where attribute matches.
Here return type will be ActiveRecord::Relation
object. ActiveRecord::Relation
class includes Ruby's Enumerable
module so you can use it's object like an array and traverse on it.
You create a form with hidden inputs that hold the values to be posted, set the action of the form to the destination url, and the form method to post. Then, when your link is clicked, trigger a JS function that submits the form.
See here, for an example. This example uses pure JavaScript, with no jQuery — you could choose this if you don't want to install anything more than you already have.
<form name="myform" action="handle-data.php" method="post">
<label for="query">Search:</label>
<input type="text" name="query" id="query"/>
<button>Search</button>
</form>
<script>
var button = document.querySelector('form[name="myform"] > button');
button.addEventListener(function() {
document.querySelector("form[name="myform"]").submit();
});
</script>
Open the php.ini file.
Search keyword like upload_max_filesize in php.ini.
Then change the size of file.
upload_max_filesize = 400M
Need to change the max post value.
post_max_size = 400M
When you select a column with type ZEROFILL
it pads the displayed value of the field with zeros up to the display width specified in the column definition. Values longer than the display width are not truncated. Note that usage of ZEROFILL
also implies UNSIGNED
.
Using ZEROFILL
and a display width has no effect on how the data is stored. It affects only how it is displayed.
Here is some example SQL that demonstrates the use of ZEROFILL
:
CREATE TABLE yourtable (x INT(8) ZEROFILL NOT NULL, y INT(8) NOT NULL);
INSERT INTO yourtable (x,y) VALUES
(1, 1),
(12, 12),
(123, 123),
(123456789, 123456789);
SELECT x, y FROM yourtable;
Result:
x y
00000001 1
00000012 12
00000123 123
123456789 123456789
You can use Take extension method
var array = new byte[] {1, 2, 3, 4};
var firstTwoItems = array.Take(2);
Little correction at Line 3
HTMLParser.HTMLParser.__init__(self)
it should be
HTMLParser.__init__(self)
The following worked for me though
import urllib2
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.recording = 0
self.data = []
def handle_starttag(self, tag, attrs):
if tag == 'required_tag':
for name, value in attrs:
if name == 'somename' and value == 'somevale':
print name, value
print "Encountered the beginning of a %s tag" % tag
self.recording = 1
def handle_endtag(self, tag):
if tag == 'required_tag':
self.recording -=1
print "Encountered the end of a %s tag" % tag
def handle_data(self, data):
if self.recording:
self.data.append(data)
p = MyHTMLParser()
f = urllib2.urlopen('http://www.someurl.com')
html = f.read()
p.feed(html)
print p.data
p.close()
`
Try this code
SELECT REPLACE([Column], char(9), '') From [dbo.Table]
char(9) is the TAB character
You are missing default density value of 160.
2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
3 px = 2 dip if dpi == 240(hdpi), 840x480 screen
In other words, if you design you layout with width equal to 160dip in portrait mode, it will be half of the screen on all ldpi/mdpi/hdpi devices(except tablets, I think)
you can put your json in a parameter and send it instead of put only your json in header:
$post_string= 'json_param=' . json_encode($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
//execute post
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
on the service side you can get your json string as a parameter:
$json_string = $_POST['json_param'];
$obj = json_decode($json_string);
then you can use your converted data as object.
One way could be by unchecking Bar Visibility "Shows Navigation Bar" In Attribute Inspector.Hope this help someone.
Use anchors.
Main Page:
<a href="/sample#sushi">Sushi</a>
<a href="/sample#bBQ">BBQ</a>
Sample Page:
<div id='sushi'><a name="sushi"></a></div>
<div id='bbq'><a name="bbq"></a></div>
go to the url about:config
and paste each line:
network.http.keep-alive.timeout;10
network.http.connection-retry-timeout;10
network.http.pipelining.read-timeout;5
network.http.connection-timeout;10
You need to follow below 2 steps instructions:
[Issue] remote: Hint: To automatically insert Change-Id, install the hook:
1) gitdir=$(git rev-parse --git-dir);
2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/
normally $gitdir = ".git". You need to update the username and the Gerrit link.
I recommend using pure JavaScript in this case, also there is no insert method in JavaScript, but we have a method which is a built-in Array method which does the job for you, it's called splice...
Let's see what's splice()...
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
OK, imagine we have this array below:
const arr = [1, 2, 3, 4, 5];
We can remove 3
like this:
arr.splice(arr.indexOf(3), 1);
It will return 3, but if we check the arr now, we have:
[1, 2, 4, 5]
So far, so good, but how we can add a new element to array using splice? Let's put back 3 in the arr...
arr.splice(2, 0, 3);
Let's see what we have done...
We use splice again, but this time for the second argument, we pass 0, means we want to delete no item, but at the same time, we add third argument which is 3 that will be added at second index...
You should be aware, that we can delete and add at the same time, for example now we can do:
arr.splice(2, 2, 3);
Which will delete 2 items at index 2, then add 3 at index 2 and result will be:
[1, 2, 3, 5];
This is showing how each item in splice work:
array.splice(start, deleteCount, item1, item2, item3 ...)
XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.
See query:
SELECT * FROM Table1 WHERE
id NOT IN (SELECT
e.id
FROM
Table1 e
INNER JOIN
Table2 s ON e.id = s.id);
Conceptually would be: Fetching the matching records in subquery and then in main query fetching the records which are not in subquery.
You can use the following script. It worked for me
The modal itself consists of a main modal container, a header, a body, and a footer. The footer contains the actions, which in this case is the OK button, the header holds the title and the close button, and the body contains the modal content.
$(function () {
modalPosition();
$(window).resize(function () {
modalPosition();
});
$('.openModal').click(function (e) {
$('.modal, .modal-backdrop').fadeIn('fast');
e.preventDefault();
});
$('.close-modal').click(function (e) {
$('.modal, .modal-backdrop').fadeOut('fast');
});
});
function modalPosition() {
var width = $('.modal').width();
var pageWidth = $(window).width();
var x = (pageWidth / 2) - (width / 2);
$('.modal').css({ left: x + "px" });
}
easier answer - put the stuff in quotes in different cells and then concatenate them!
B1: rcrCheck.asp
C1: =D1&B1&E1
D1: "code in quotes" and "more code in quotes"
E1: "
it comes out perfect (can't show you because I get a stupid dialog box about code)
easy peasy!!
Context means Android get to know in which activity I should go for or act in.
1 - Toast.makeText(context, "Enter All Details", Toast.LENGTH_SHORT).show();
it used in this.
Context context = ActivityName.this;
2 -startActivity(new Intent(context,LoginActivity.class));
in this context means from which activity you wanna go to other activity. context or ActivityName.this is faster then , getContext and getApplicatinContext.
PAGEIOLATCH_SH
wait type usually comes up as the result of fragmented or unoptimized index.
Often reasons for excessive PAGEIOLATCH_SH
wait type are:
In order to try and resolve having high PAGEIOLATCH_SH
wait type, you can check:
PAGEIOLATCH_SH
wait typesAlways keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH
can be expected.
You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types
In one answer above:
The simplest & the best solution:
mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s));
There is an syntax error, ,null
must be added:
mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s,null));
When a web browser moves from one website to another and between pages of a website, it can optionally pass the URL it came from. This is called the HTTP_REFERER, So if you don't redirect from one page to another it might be missing
If the HTTP_REFERER has been set then it will be displayed. If it is not then you won't see anything. If it's not set and you have error reporting set to show notices, you'll see an error like this instead:
Notice: Undefined index: HTTP_REFERER in /path/to/filename.php
To prevent this error when notices are on (I always develop with notices on), you can do this:
if(isset($_SERVER['HTTP_REFERER'])) {
echo $_SERVER['HTTP_REFERER'];
}
OR
echo isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
It can be useful to use the HTTP_REFERER variable for logging etc purposes using the $_SERVER['HTTP_REFERER'] superglobal variable. However it is important to know it's not always set so if you program with notices on then you'll need to allow for this in your code
Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)
Ok, this is not a very serious review, but here is what I can say:
I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:
#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis
import sys, time
stdout = sys.stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
class Iterator(object) :
def __init__(self):
print 'Rendering...'
for y in xrange(-39, 39):
stdout.write('\n')
for x in xrange(-39, 39):
if self.mandelbrot(x/40.0, y/40.0) :
stdout.write(' ')
else:
stdout.write('*')
def mandelbrot(self, x, y):
cr = y - 0.5
ci = x
zi = 0.0
zr = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
if zi2 + zr2 > BAILOUT:
return i
return 0
t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)
As a result:
PyChecker
is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.PyFlakes
is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.PyLint
has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).Strong points of PyLint
:
Cons of Pylint:
Corrected script (with lazy doc strings and variable names):
#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""
import time
from sys import stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
def mandelbrot(dim_1, dim_2):
"""
function doc string
"""
cr1 = dim_1 - 0.5
ci1 = dim_2
zi1 = 0.0
zr1 = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr1 * zi1
zr2 = zr1 * zr1
zi2 = zi1 * zi1
zr1 = zr2 - zi2 + cr1
zi1 = temp + temp + ci1
if zi2 + zr2 > BAILOUT:
return i
return 0
def execute() :
"""
func doc string
"""
print 'Rendering...'
for dim_1 in xrange(-39, 39):
stdout.write('\n')
for dim_2 in xrange(-39, 39):
if mandelbrot(dim_1/40.0, dim_2/40.0) :
stdout.write(' ')
else:
stdout.write('*')
START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)
Thanks to Rudiger Wolf, I discovered pep8
that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.
Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.
To give you a little idea of their output:
pep8:
./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3
Pylint:
************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C: 1: Missing docstring
C: 5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
[...] and a very long report with useful stats like :
Duplication
-----------
+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+
Facebook sharing from a share dialog fails even with @Matthieu answer (which is 100% correct for the rest of social URLs). I had to add a set of URL i reversed from Facebook SDK.
<array>
<string>fbapi</string>
<string>fbauth2</string>
<string>fbshareextension</string>
<string>fb-messenger-api</string>
<string>twitter</string>
<string>whatsapp</string>
<string>wechat</string>
<string>line</string>
<string>instagram</string>
<string>kakaotalk</string>
<string>mqq</string>
<string>vk</string>
<string>comgooglemaps</string>
<string>fbapi20130214</string>
<string>fbapi20130410</string>
<string>fbapi20130702</string>
<string>fbapi20131010</string>
<string>fbapi20131219</string>
<string>fbapi20140410</string>
<string>fbapi20140116</string>
<string>fbapi20150313</string>
<string>fbapi20150629</string>
</array>
If child class has more members, than parent, it could be done not very clean, but short way:
@Data
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class User extends BaseEntity {
private @NonNull String fullName;
private @NonNull String email;
...
public User(Integer id, String fullName, String email, ....) {
this(fullName, email, ....);
this.id = id;
}
}
@Data
@AllArgsConstructor
abstract public class BaseEntity {
protected Integer id;
public boolean isNew() {
return id == null;
}
}
An addition to the solution by @Rafael Teles. The syntactic sugar Collectors.mapping
does the same in one step:
//...
List<Employee> employees = persons.stream()
.filter(p -> p.getLastName().equals("l1"))
.collect(
Collectors.mapping(
p -> new Employee(p.getName(), p.getLastName(), 1000),
Collectors.toList()));
Detailed example can be found here
I got this issue when i wrote :
export default connect (mapDispatchToProps,mapStateToProps)(SearchInsectsComponent);
instead of
export default connect (mapStateToProps,mapDispatchToProps)(SearchInsectsComponent);
This is my way to solve your task:
str = "0b110100001100101011011000110110001101111"
str = "0" + str[2:]
message = ""
while str != "":
i = chr(int(str[:8], 2))
message = message + i
str = str[8:]
print message
With the forcats package from the tidyverse this is easy, too.
mutate(dat, x = fct_recode(x, "B" = "A"))
You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()
).
If so, just use unset()
:
unset($arr[1]);
public static void reverseString(String s){
System.out.println("---------");
for(int i=s.length()-1; i>=0;i--){
System.out.print(s.charAt(i));
}
System.out.println();
}
For me, three steps solved this problem on windows 10:
I downloaded MySQL server community edition zip and extracted it in the D drive. After that I went to bin
folder and did cmd
on that folder. I followed the below steps and all works:
D:\tools\mysql-8.0.17-winx64\bin>mysqld -install
Service successfully installed.
D:\tools\mysql-8.0.17-winx64\bin>mysqld --initialize
D:\tools\mysql-8.0.17-winx64\bin>net start mysql
The MySQL service is starting...
The MySQL service was started successfully.
I can show you how I used it
function GetDenierValue() {
var denierid = $("#productDenierid").val() == '' ? 0 : $("#productDenierid").val();
var param = { 'productDenierid': denierid };
$.ajax({
url: "/Admin/ProductComposition/GetDenierValue",
dataType: "json",
contentType: "application/json;charset=utf-8",
type: "POST",
data: JSON.stringify(param),
success: function (msg) {
if (msg != null) {
return msg.URL;
}
}
});
}
Try to enter the full-path of the dll. If it doesn't work, try to copy the dll into the system32 folder.
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
Compiler shows following error :
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Storyboard (<UIStoryboard: 0x7fedf2d5c9a0>) doesn't contain a
ViewController with identifier 'SBAddEmployeeVC''
Here the object of the storyboard created is not the main storyboard which contains our ViewControllers. As storyboard file on which we work is named as Main.storyboard. So we need to have reference of object of the Main.storyboard.
Use following code for that :
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
Here storyboardWithName
is the name of the storyboard file we are working with and bundle
specifies the bundle in which our storyboard is (i.e. mainBundle
).
What I do is:
Set the td width:
<td width="200" height="50"><!--blaBlaBla Contents here--></td>
Set the td width with CSS:
<td style="width:200px; height:50px;">
Set the width again as max and min with CSS:
<td style="max-width:200px; min-width:200px; max-height:50px; min-height:50px; width:200px; height:50px;">
It sounds little bit repetitive but it gives me the desired result. To achieve this with much ease, you may need put the CSS values in a class in your style-sheet:
.td_size {
width:200px;
height:50px;
max-width:200px;
min-width:200px;
max-height:50px;
min-height:50px;
**overflow:hidden;** /*(Optional)This might be useful for some overflow contents*/
}
then:
<td class="td_size">
Place the class attribute to any <td>
you want.
The ":PATH" part in the accepted answer can be omitted. This syntax may be more memorable:
cmake -DCMAKE_INSTALL_PREFIX=/usr . && make all install
...as used in the answers here.
I fixed this by adding "Gradle-aware make" before launch in my launch configuration.
My initial theory about the difference was that library
loads the packages whether it is already loaded or not, i.e. it might reload an already loaded package, while require
just checks that it is loaded, or loads it if it isn't (thus the use in functions that rely on a certain package). The documentation refutes this, however, and explicitly states that neither function will reload an already loaded package.
before comparing the two or more strings first execute the following commands
alter session set NLS_COMP=LINGUISTIC;
alter session set NLS_SORT=BINARY_CI;
after those two statements executed then you may compare the strings and there will be case insensitive.for example you had two strings s1='Apple' and s2='apple', if yow want to compare the two strings before executing the above statements then those two strings will be treated as two different strings but when you compare the strings after the execution of the two alter statements then those two strings s1 and s2 will be treated as the same string
reasons for using those two statements
We need to set NLS_COMP=LINGUISTIC and NLS_SORT=BINARY_CI in order to use 10gR2 case insensitivity. Since these are session modifiable, it is not as simple as setting them in the initialization parameters. We can set them in the initialization parameters but they then only affect the server and not the client side.
Some time when we use Environ()
function we may get the Library or property not found error. Use VBA.Environ()
or VBA.Environ$()
to avoid the error.
using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("[email protected]");
smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("[email protected]");
try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}
You may use the above code.
Here is the basis of a more secure version of the accepted answer, using PHP's filter_input function, which also makes up for the potential lack of $_SERVER['REQUEST_URI']
:
$protocol_https = filter_input(INPUT_SERVER, 'HTTPS', FILTER_SANITIZE_STRING);
$host = filter_input(INPUT_SERVER, 'HTTP_HOST', FILTER_SANITIZE_URL);
$request_uri = filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL);
if(strlen($request_uri) == 0)
{
$request_uri = filter_input(INPUT_SERVER, 'SCRIPT_NAME', FILTER_SANITIZE_URL);
$query_string = filter_input(INPUT_SERVER, 'QUERY_STRING', FILTER_SANITIZE_URL);
if($query_string)
{
$request_uri .= '?' . $query_string;
}
}
$full_url = ($protocol_https ? 'https' : 'http') . '://' . $host . $request_uri;
You could use some different filters to tweak it to your liking.
Following could be one of ways:
dataframe = dataframe.sample(frac=1, random_state=42).reset_index(drop=True)
where
frac=1 means all rows of a dataframe
random_state=42 means keeping same order in each execution
reset_index(drop=True) means reinitialize index for randomized dataframe
It should be (new minus old)/mod avg of old and new With a special case when both val are zeros
This will do the trick:
public void itemClicked(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(MyAndroidAppActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}
}
Apache commons StringEscapeUtils.escapeEcmaScript(String)
returns a string with unicode characters escaped using the \u
notation.
"Art of Beer " -> "Art of Beer \u1F3A8 \u1F37A"
The HAVING option can be used for this purpose and query should be
SELECT word, COUNT(*) FROM words
GROUP BY word
HAVING COUNT(*) > 1;
I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.
A valid JSON always starts with either curly braces {
or square brackets [
, nothing else.
{
will start an object
:{ "key": value, "another key": value }
Hint: although javascript accepts single quotes
'
, JSON only takes double ones"
.
[
will start an array
:[value, value]
Hint: spaces among elements are always ignored by any JSON parser.
value
is an object
, array
, string
, number
, bool
or null
:So yeah, ["a", "b"]
is a perfectly valid JSON, like you could try on the link Manish pointed.
Here are a few extra valid JSON examples, one per block:
{}
[0]
{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}
[{ "why":null} ]
{
"not true": [0, false],
"true": true,
"not null": [0, 1, false, true, {
"obj": null
}, "a string"]
}
You can use this method also it will act like that
thadari=[1,2,3,4,5,6]
#Front Two(Left)
print(thadari[:2])
[1,2]
#Last Two(Right)# edited
print(thadari[-2:])
[5,6]
#mid
mid = len(thadari) //2
lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]
Hope it will help
Thought I'd add an answer since your question title looks like it is asking how to create or update, rather than get or create as described in the question body.
If you did want to create or update an object, the .save() method already has this behaviour by default, from the docs:
Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save(), Django follows this algorithm:
If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.
It's worth noting that when they say 'if the UPDATE didn't update anything' they are essentially referring to the case where the id you gave the object doesn't already exist in the database.
app._router.stack.forEach(function(r){
if (r.route && r.route.path){
console.log(r.route.path)
}
})
You have to do both:
SELECT * FROM Table WHERE Text IS NULL or Text LIKE ''
There's no way to do this with any built-in functions, because it would be terribly inefficient. You'd need to shift the existing contents of the file down each time you add a line at the front.
There's a Unix/Linux utility tail
which can read from the end of a file. Perhaps you can find that useful in your application.
it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :
wrong :
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')
correct:
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')
It's possible to decide which reactor projects to build by specifying the -pl
command line argument:
$ mvn --help
[...]
-pl,--projects <arg> Build specified reactor projects
instead of all projects
[...]
It accepts a comma separated list of parameters in one of the following forms:
[groupId]:artifactId
Thus, given the following structure:
project-root [com.mycorp:parent]
|
+ --- server [com.mycorp:server]
| |
| + --- orm [com.mycorp.server:orm]
|
+ --- client [com.mycorp:client]
You can specify the following command line:
mvn -pl .,server,:client,com.mycorp.server:orm clean install
to build everything. Remove elements in the list to build only the modules you please.
EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el
flag that excludes projects from the reactor, similarly to what -pl
does:
You can also do that from inteface builder like this.
I think it's helpful.
Highlight the cell(s)/column which you want as Duration, right click on the mouse to "Format Cells". Go to "Custom" and look for "h:mm" if you want to input duration in hour and minutes format. If you want to include seconds as well, click on "h:mm:ss". You can even add up the total duration after that.
Hope this helps.
ngClick directive (as well as all other event directives) creates $event
variable which is available on same scope. This variable is a reference to JS event
object and can be used to call stopPropagation()
:
<table>
<tr ng-repeat="user in users" ng-click="showUser(user)">
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td>
<button class="btn" ng-click="deleteUser(user.id, $index); $event.stopPropagation();">
Delete
</button>
</td>
</tr>
</table>
You need an Oracle Client: http://www.oracle.com/technology/oramag/oracle/08-nov/o68odpnet.html
There are several options for defining the handling of white spaces and line breaks.
If one can put the content in e.g. a <p>
tag it is pretty easy to get whatever one wants.
For preserving line breaks but not white spaces use pre-line
(not pre
) like in:
<style>
p {
white-space: pre-line; /* collapse WS, preserve LB */
}
</style>
<p>hello
How are you</p>
If another behavior is wanted choose among one of these (WS=WhiteSpace, LB=LineBreak):
white-space: normal; /* collapse WS, wrap as necessary, collapse LB */
white-space: nowrap; /* collapse WS, no wrapping, collapse LB */
white-space: pre; /* preserve WS, no wrapping, preserve LB */
white-space: pre-wrap; /* preserve WS, wrap as necessary, preserve LB */
white-space: inherit; /* all as parent element */
This is called a correlated update
UPDATE table1 t1
SET (name, desc) = (SELECT t2.name, t2.desc
FROM table2 t2
WHERE t1.id = t2.id)
WHERE EXISTS (
SELECT 1
FROM table2 t2
WHERE t1.id = t2.id )
Assuming the join results in a key-preserved view, you could also
UPDATE (SELECT t1.id,
t1.name name1,
t1.desc desc1,
t2.name name2,
t2.desc desc2
FROM table1 t1,
table2 t2
WHERE t1.id = t2.id)
SET name1 = name2,
desc1 = desc2
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
action attribute in <form method="post" action="action=""">
should be just action=""
I would not have expected this case to be optimized at all. It can't be very often where an expression contains subexpressions that can be regrouped to remove entire operations. I would expect compiler writers to invest their time in areas which would be more likely to result in noticeable improvements, rather than covering a rarely encountered edge case.
I was surprised to learn from the other answers that this expression could indeed be optimized with the proper compiler switches. Either the optimization is trivial, or it is an edge case of a much more common optimization, or the compiler writers were extremely thorough.
There's nothing wrong with providing hints to the compiler as you've done here. It's a normal and expected part of the micro-optimization process to rearrange statements and expressions to see what differences they will bring.
While the compiler may be justified in considering the two expressions to deliver inconsistent results (without the proper switches), there's no need for you to be bound by that restriction. The difference will be incredibly tiny - so much so that if the difference matters to you, you should not be using standard floating point arithmetic in the first place.
There are 8 bits in a byte (normally speaking in Windows).
However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.
In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.
EDITED
Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.
This is a fundamental understanding in Java, but can be a little tricky to new programmers. Do a little research on the difference between a static and instance method. The basic difference is the instance method do() is only accessible to a instance of the class foo.
You must instantiate (create an instance of) the class, creating an object, that you use to call the instance method.
I have included your example with a couple comments and example.
public class SomeName {
//this is a static method and cannot call an instance method without a object
public static void main(String[] args){
// can't do this from this static method, no object reference
// someMethod();
//create instance of object
SomeName thisObj = new SomeName();
//call instance method using object
thisObj.someMethod();
}
//instance method
public void someMethod(){
System.out.print("some message...");
}
}// end class SomeName
you can use following these component to float right
alignItems aligns children in the cross direction. For example, if children are flowing vertically, alignItems controls how they align horizontally.
alignItems: 'flex-end'
justifyContent aligns children in the main direction. For example, if children are flowing vertically, justifyContent controls how they align vertically.
justifyContent: 'flex-end'
alignSelf controls how a child aligns in the cross direction,
alignSelf : 'flex-end'
You may try using services of angular js, it has worked for me..giving the code snippets below
Controller code:
$scope.total = 0;
var aCart = new CartService();
$scope.addItemToCart = function (product) {
aCart.addCartTotal(product.Price);
};
$scope.showCart = function () {
$scope.total = aCart.getCartTotal();
};
Service Code:
app.service("CartService", function () {
Total = [];
Total.length = 0;
return function () {
this.addCartTotal = function (inTotal) {
Total.push( inTotal);
}
this.getCartTotal = function () {
var sum = 0;
for (var i = 0; i < Total.length; i++) {
sum += parseInt(Total[i], 10);
}
return sum;
}
};
});
This is what I ended up using. Temporarily sets target to _blank, then sets it back.
OnClientClick="var originalTarget = document.forms[0].target; document.forms[0].target = '_blank'; setTimeout(function () { document.forms[0].target = originalTarget; }, 3000);"
UPDATE 2
@Override
protected void onResume() {
super.onResume();
mUserNameEdit.requestFocus();
mUserNameEdit.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
InputMethodManager keyboard = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(mUserNameEdit, 0);
}
},200); //use 300 to make it run when coming back from lock screen
}
I tried very hard and found out a solution ... whenever a new activity starts then keyboard cant open but we can use Runnable in onResume and it is working fine so please try this code and check...
UPDATE 1
add this line in your AppLogin.java
mUserNameEdit.requestFocus();
and this line in your AppList.java
listview.requestFocus()'
after this check your application if it is not working then add this line in your AndroidManifest.xml
file
<activity android:name=".AppLogin" android:configChanges="keyboardHidden|orientation"></activity>
<activity android:name=".AppList" android:configChanges="keyboard|orientation"></activity>
ORIGINAL ANSWER
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
for hide keyboard
imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
for show keyboard
imm.showSoftInput(ed, 0);
for focus on EditText
ed.requestFocus();
where ed is EditText
This is the best way I've seen to find the last cell.
MsgBox ActiveSheet.UsedRage.SpecialCells(xlCellTypeLastCell).Row
One of the disadvantages to using this is that it's not always accurate. If you use it then delete the last few rows and use it again, it does not always update. Saving your workbook before using this seems to force it to update though.
Using the next bit of code after updating the table (or refreshing the query that feeds the table) forces everything to update before finding the last row. But, it's been reported that it makes excel crash. Either way, calling this before trying to find the last row will ensure the table has finished updating first.
Application.CalculateUntilAsyncQueriesDone
Another way to get the last row for any given column, if you don't mind the overhead.
Function GetLastRow(col, row)
' col and row are where we will start.
' We will find the last row for the given column.
Do Until ActiveSheet.Cells(row, col) = ""
row = row + 1
Loop
GetLastRow = row
End Function
Tuples aren't supported in JavaScript
If you're looking for an immutable list, Object.freeze() can be used to make an array immutable.
The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.
Source: Mozilla Developer Network - Object.freeze()
Assign an array as usual but lock it using 'Object.freeze()
> tuple = Object.freeze(['Bob', 24]);
[ 'Bob', 24 ]
Use the values as you would a regular array (python multi-assignment is not supported)
> name = tuple[0]
'Bob'
> age = tuple[1]
24
Attempt to assign a new value
> tuple[0] = 'Steve'
'Steve'
But the value is not changed
> console.log(tuple)
[ 'Bob', 24 ]
section {
position: relative;
width: 50%;
border: 1px solid;
}
h1 {
display: inline;
}
div {
position: relative;
float:right;
top: 0;
right: 0;
}
You can run ruby commands in one line with the -e
flag:
ruby -e "puts 'hi'"
Check the man page for more information.
I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->
return .Cell(i,1) <> Empty
-(void)addStuffToView
{
UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 20, 20)]; //(x, y, width, height of button on screen
[aButton setTitle:@"Button" forState:UIControlStateNormal];//puts the text on the button
aButton.titleLabel.font = somefont;//sets the font if one is already stated
aButton.titleLabel.font = [UIFont fontWithName:@"Arial-MT" size:12];//sets the font type and size
[aButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];//see back method below
[aButton setBackgroundImage:[UIImage imageNamed:@"someImage.png"] forState:UIControlStateNormal];//sets the image of the button
[self.view addSubview:back];
}
-(void)back
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle.....]
}
-(void)viewDidLoad
{
[super viewDidLoad];
[self addStuffToView];//adds all items built in this method to the view
}
I added these configuration in web.xml and it works well for me!
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Additionally, the most ranked answer give me clues to prevent application from panic at the first run.
I fixed this issue by installing: sudo apt-get install libstdc++6
In my case, I ran into this issue after installing MongoDB 3.0.1
mongo: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.18' not found (required by mongo)
You can use the IndexOf
method and the Substring
method like so:
string output = input.Substring(input.IndexOf('.') + 1);
The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.
I had to use the \COPY because I received the error message:
ERROR: could not open file "/filepath/places.csv" for writing: Permission denied
So I used:
\Copy (Select address, zip From manjadata) To '/filepath/places.csv' With CSV;
and it is functioning
For windows 8, just type "py".
Problem behind the error: If you are trying to access Oracle database you will not able to access inserted data until the transaction has been successful and to complete the transaction you have to fire a commit
query after inserting the data into the table. Because Oracle database is not on auto commit mode by default.
Solution:
Go to SQL PLUS and follow the following queries..
SQL*Plus: Release 11.2.0.1.0 Production on Tue Nov 28 15:29:43 2017
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Enter user-name: scott
Enter password:
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> desc empdetails;
Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NUMBER(38)
ENAME VARCHAR2(20)
SAL FLOAT(126)
SQL> insert into empdetails values(1010,'John',45000.00);
1 row created.
SQL> commit;
Commit complete.
You can use Localstorage
1- Add dependency to pubspec.yaml
(Change the version based on the last)
dependencies:
...
localstorage: ^3.0.0
2- Then run the following command
flutter packages get
3- import the localstorage :
import 'package:localstorage/localstorage.dart';
4- create an instance
class MainApp extends StatelessWidget {
final LocalStorage storage = new LocalStorage('localstorage_app');
...
}
Add item to lcoalstorage :
void addItemsToLocalStorage() {
storage.setItem('name', 'Abolfazl');
storage.setItem('family', 'Roshanzamir');
final info = json.encode({'name': 'Darush', 'family': 'Roshanzami'});
storage.setItem('info', info);
}
Get an item from lcoalstorage:
void getitemFromLocalStorage() {
final name = storage.getItem('name'); // Abolfazl
final family = storage.getItem('family'); // Roshanzamir
Map<String, dynamic> info = json.decode(storage.getItem('info'));
final info_name=info['name'];
final info_family=info['family'];
}
Delete an item from localstorage :
void removeItemFromLocalStorage() {
storage.deleteItem('name');
storage.deleteItem('family');
storage.deleteItem('info');
}