The answer appears to be solely related to application size. I created a simple "hello world" app with nothing special in the manifest file, uploaded it to the Play store, and it was reported as compatible with my device.
I changed nothing in this app except for adding more content into the res/drawable
directory. When the .apk
size reached about 32 MB, the Play store started reporting that my app was incompatible with my phone.
I will attempt to contact Google developer support and ask for clarification on the reason for this limit.
UPDATE: Here is Google developer support response to this:
Thank you for your note. Currently the maximum file size limit for an app upload to Google Play is approximately 50 MB.
However, some devices may have smaller than 50 MB cache partition making the app unavailable for users to download. For example, some of HTC Wildfire devices are known for having 35-40 MB cache partitions. If Google Play is able to identify such device that doesn't have cache large enough to store the app, it may filter it from appearing for the user.
I ended up solving my problem by converting all the PNG files to JPG, with a small loss of quality. The .apk
file is now 28 MB, which is below whatever threshold Google Play is enforcing for my phone.
I also removed all the <uses-feature>
stuff, and now have just this:
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />
You cant get a decimal value by dividing one integer with another, you'll allways get an integer that way (result truncated to integer). You need at least one value to be a decimal number.
This trick works for me:
grd.DataSource = DT;
// Set your desired AutoSize Mode:
grd.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
grd.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
grd.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
// Now that DataGridView has calculated it's Widths; we can now store each column Width values.
for (int i = 0; i <= grd.Columns.Count - 1; i++)
{
// Store Auto Sized Widths:
int colw = grd.Columns[i].Width;
// Remove AutoSizing:
grd.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
// Set Width to calculated AutoSize value:
grd.Columns[i].Width = colw;
}
In the Code above: You set the Columns AutoSize Property to whathever AutoSizeMode you need. Then (Column by Column) you store each column Width value (from AutoSize value); Disable the AutoSize Property and finally, set the Column Width to the Width value you previously stored.
As Peter already pointed out:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
In C# it is
public class AdminForumUser : UserBase, IUser
Java would say
public class AdminForumUser extends User implements ForumUserInterface
Because of that, I don't think conventions are nearly as important in java for interfaces, since there is an explicit difference between inheritance and interface implementation. I would say just choose any naming convention you would like, as long as you are consistant and use something to show people that these are interfaces. Haven't done java in a few years, but all interfaces would just be in their own directory, and that was the convention. Never really had any issues with it.
css files do not support conditional statements.
If you want something to look one of two ways, depending on some condition, give it a suitable class using your server side scripting language or javascript. eg
<div class="oh-yes"></div>
<div class="hell-no"></div>
Devise uses some generators to generate views and stuff it needs into your application. If you have run this generator, you can easily undo it with
rails destroy <name_of_generator>
The uninstallation of the gem works as described in the other posts.
In addition to the above answer I also want to highlight a case of striked out property which really surprised me.
If you are adding a background image to a div :
<div class = "myBackground">
</div>
You want to scale the image to fit in the dimensions of the div so this would be your normal class definition.
.myBackground {
height:100px;
width:100px;
background: url("/img/bck/myImage.jpg") no-repeat;
background-size: contain;
}
but if you interchange the order as :-
.myBackground {
height:100px;
width:100px;
background-size: contain; //before the background
background: url("/img/bck/myImage.jpg") no-repeat;
}
then in chrome you ll see background-size as striked out. I am not sure why this is , but yeah you dont want to mess with it.
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
TL;DR: Yes, the only Swift language implementation is slow, right now. If you need fast, numeric (and other types of code, presumably) code, just go with another one. In the future, you should re-evaluate your choice. It might be good enough for most application code that is written at a higher level, though.
From what I'm seeing in SIL and LLVM IR, it seems like they need a bunch of optimizations for removing retains and releases, which might be implemented in Clang (for Objective-C), but they haven't ported them yet. That's the theory I'm going with (for now… I still need to confirm that Clang does something about it), since a profiler run on the last test-case of this question yields this “pretty” result:
As was said by many others, -Ofast
is totally unsafe and changes language semantics. For me, it's at the “If you're going to use that, just use another language” stage. I'll re-evaluate that choice later, if it changes.
-O3
gets us a bunch of swift_retain
and swift_release
calls that, honestly, don't look like they should be there for this example. The optimizer should have elided (most of) them AFAICT, since it knows most of the information about the array, and knows that it has (at least) a strong reference to it.
It shouldn't emit more retains when it's not even calling functions which might release the objects. I don't think an array constructor can return an array which is smaller than what was asked for, which means that a lot of checks that were emitted are useless. It also knows that the integer will never be above 10k, so the overflow checks can be optimized (not because of -Ofast
weirdness, but because of the semantics of the language (nothing else is changing that var nor can access it, and adding up to 10k is safe for the type Int
).
The compiler might not be able to unbox the array or the array elements, though, since they're getting passed to sort()
, which is an external function and has to get the arguments it's expecting. This will make us have to use the Int
values indirectly, which would make it go a bit slower. This could change if the sort()
generic function (not in the multi-method way) was available to the compiler and got inlined.
This is a very new (publicly) language, and it is going through what I assume are lots of changes, since there are people (heavily) involved with the Swift language asking for feedback and they all say the language isn't finished and will change.
Code used:
import Cocoa
let swift_start = NSDate.timeIntervalSinceReferenceDate();
let n: Int = 10000
let x = Int[](count: n, repeatedValue: 1)
for i in 0..n {
for j in 0..n {
let tmp: Int = x[j]
x[i] = tmp
}
}
let y: Int[] = sort(x)
let swift_stop = NSDate.timeIntervalSinceReferenceDate();
println("\(swift_stop - swift_start)s")
P.S: I'm not an expert on Objective-C nor all the facilities from Cocoa, Objective-C, or the Swift runtimes. I might also be assuming some things that I didn't write.
It's all about context, and also who is responsible for handling duplicates in requests (server or client or both)
If server just point the duplicate, look at 4xx:
For implicit handling of duplicates, look at 2XX:
if the server is expected to return something, look at 3XX:
when the server is able to point the existing resource, it implies a redirection.
If the above is not enough, it's always a good practice to prepare some error message in the body of the response.
This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
im = ax.imshow(data, cmap='bone')
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
Here is some simple code to give output as currentdate
+ D days
= some 'x' date
(future date):
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 5);
System.out.println(dateFormat.format(c.getTime()));
insert into table1(id1) select (max(id1)+1) from table1;
$(document).ready(function() {
$("#aDateFrom").datepicker({
onSelect: function() {
//- get date from another datepicker without language dependencies
var minDate = $('#aDateFrom').datepicker('getDate');
$("#aDateTo").datepicker("change", { minDate: minDate });
}
});
$("#aDateTo").datepicker({
onSelect: function() {
//- get date from another datepicker without language dependencies
var maxDate = $('#aDateTo').datepicker('getDate');
$("#aDateFrom").datepicker("change", { maxDate: maxDate });
}
});
});
Found a solution to Excel Mac2016 as having to paste the code into the relevant cell, enter, then go to the end of the formula within the header bar and enter the following:
Enter a formula as an array formula Image + SHIFT + RETURN or CONTROL + SHIFT + RETURN
You need to start the script with a preceding dot, this will put the exported variables in the current environment.
#!/bin/bash
...
export output="SUCCESS"
Then execute it like so
chmod +x /tmp/test.sh
. /tmp/test.sh
When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate
Both isVisible()
and isAdded()
return true
as soon as the Fragment
is created, and not even actually visible. The only solution that actually works is:
if (isAdded() && isVisible() && getUserVisibleHint()) {
// ... do your thing
}
This does the job. Period.
NOTICE: getUserVisibleHint() is now deprecated. be careful.
Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows
function:
public class InfoWindow
{
public IntPtr Handle = IntPtr.Zero;
public FileInfo File = new FileInfo( Application.ExecutablePath );
public string Title = Application.ProductName;
public override string ToString() {
return File.Name + "\t>\t" + Title;
}
}//CLASS
/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{
internal static event EventHandler WindowActivatedChanged;
internal static Timer TimerWatcher = new Timer();
internal static InfoWindow WindowActive = new InfoWindow();
internal static void DoStartWatcher() {
TimerWatcher.Interval = 500;
TimerWatcher.Tick += TimerWatcher_Tick;
TimerWatcher.Start();
}
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
/// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
{
IntPtr shellWindow = GetShellWindow();
Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();
EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
if ( hWnd == shellWindow ) return true;
if ( !IsWindowVisible( hWnd ) ) return true;
int length = GetWindowTextLength( hWnd );
if ( length == 0 ) return true;
StringBuilder builder = new StringBuilder( length );
GetWindowText( hWnd , builder , length + 1 );
var info = new InfoWindow();
info.Handle = hWnd;
info.File = new FileInfo( GetProcessPath( hWnd ) );
info.Title = builder.ToString();
windows[hWnd] = info;
return true;
} ) , 0 );
return windows;
}
private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );
public static string GetProcessPath( IntPtr hwnd )
{
uint pid = 0;
GetWindowThreadProcessId( hwnd , out pid );
if ( hwnd != IntPtr.Zero ) {
if ( pid != 0 ) {
var process = Process.GetProcessById( (int) pid );
if ( process != null ) {
return process.MainModule.FileName.ToString();
}
}
}
return "";
}
[DllImport( "USER32.DLL" )]
private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowTextLength( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern bool IsWindowVisible( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern IntPtr GetShellWindow();
[DllImport( "user32.dll" )]
private static extern IntPtr GetForegroundWindow();
//WARN: Only for "Any CPU":
[DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );
static void TimerWatcher_Tick( object sender , EventArgs e )
{
var windowActive = new InfoWindow();
windowActive.Handle = GetForegroundWindow();
string path = GetProcessPath( windowActive.Handle );
if ( string.IsNullOrEmpty( path ) ) return;
windowActive.File = new FileInfo( path );
int length = GetWindowTextLength( windowActive.Handle );
if ( length == 0 ) return;
StringBuilder builder = new StringBuilder( length );
GetWindowText( windowActive.Handle , builder , length + 1 );
windowActive.Title = builder.ToString();
if ( windowActive.ToString() != WindowActive.ToString() ) {
//fire:
WindowActive = windowActive;
if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
Console.WriteLine( "Window: " + WindowActive.ToString() );
}
}
}//CLASS
Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...
If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.
Images can be placed in place of radio buttons by using label and span elements.
<div class="customize-radio">
<label>Favourite Smiley</label>
<br>
<label for="hahaha">
<input type="radio" name="smiley" id="hahaha">
<span class="haha-img"></span>
HAHAHA
</label>
<label for="kiss">
<input type="radio" name="smiley" id="kiss">
<span class="kiss-img"></span>
Kiss
</label>
<label for="tongueOut">
<input type="radio" name="smiley" id="tongueOut">
<span class="tongueout-img"></span>
TongueOut
</label>
</div>
Radio button should be hidden,
.customize-radio label > input[type = 'radio'] {
visibility: hidden;
position: absolute;
}
Image can be given in the span tag,
.customize-radio label > input[type = 'radio'] ~ span{
cursor: pointer;
width: 27px;
height: 24px;
display: inline-block;
background-size: 27px 24px;
background-repeat: no-repeat;
}
.haha-img {
background-image: url('hahabefore.png');
}
.kiss-img{
background-image: url('kissbefore.png');
}
.tongueout-img{
background-image: url('tongueoutbefore.png');
}
To change the image on click of radio button, add checked state to the input tag,
.customize-radio label > input[type = 'radio']:checked ~ span.haha-img{
background-image: url('haha.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.kiss-img{
background-image: url('kiss.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.tongueout-img{
background-image: url('tongueout.png');
}
If you have any queries, Refer to the following link, As I have taken solution from the below blog, http://frontendsupport.blogspot.com/2018/06/cool-radio-buttons-with-images.html
You can override the default behavior in following registry:
Key : HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319
Value: SchUseStrongCrypto
Type: REG_DWORD
Data : 1
and
Key : HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v4.0.30319
Value: SchUseStrongCrypto
Type: REG_DWORD
Data : 1
For details, please see the implementation of ServicePointManager
.
Because userString is empty. You only declare it
vector<string> userString;
but never add anything, so the for loop won't even run.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}
My solution is not efficient but helped me in situation where the values (bank cheque numbers and wire transfer ref no.) were stored as varchar where some entries had alpha numeric values with them and I had to pad if length is smaller than 6 chars.
Thought to share if someone comes across same situation
declare @minlen int = 6
declare @str varchar(20)
set @str = '123'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 000123
set @str = '1234'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 001234
set @str = '123456'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456
set @str = '123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456789
set @str = '123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456789
set @str = 'NEFT 123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: NEFT 123456789
setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.
CODE:
var im = document.getElementById("img");
var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;
function changeImage()
{
im.setAttribute("src", images[index]);
index++;
if(index >= images.length)
{
index=0;
}
}
setInterval(changeImage, 30000);
Honestly basename
and dirname
solutions are easier, but you can also check this out :
find . -type f | grep -oP "[^/]*$"
or
find . -type f | rev | cut -d '/' -f1 | rev
or
find . -type f | sed "s/.*\///"
So I had a similar situation with the same error. I forgot I changed the compatibility mode on my dev machine and I had a console.log command in my javascript as well. I changed compatibility mode back in IE, and removed the console.log command. No more issue.
It's worth mentioning that you may have been able to read this in directly e.g. if you were using read_csv
using parse_dates=[['Date', 'Time']]
.
Assuming these are just strings you could simply add them together (with a space), allowing you to apply to_datetime
:
In [11]: df['Date'] + ' ' + df['Time']
Out[11]:
0 01-06-2013 23:00:00
1 02-06-2013 01:00:00
2 02-06-2013 21:00:00
3 02-06-2013 22:00:00
4 02-06-2013 23:00:00
5 03-06-2013 01:00:00
6 03-06-2013 21:00:00
7 03-06-2013 22:00:00
8 03-06-2013 23:00:00
9 04-06-2013 01:00:00
dtype: object
In [12]: pd.to_datetime(df['Date'] + ' ' + df['Time'])
Out[12]:
0 2013-01-06 23:00:00
1 2013-02-06 01:00:00
2 2013-02-06 21:00:00
3 2013-02-06 22:00:00
4 2013-02-06 23:00:00
5 2013-03-06 01:00:00
6 2013-03-06 21:00:00
7 2013-03-06 22:00:00
8 2013-03-06 23:00:00
9 2013-04-06 01:00:00
dtype: datetime64[ns]
Note: surprisingly (for me), this works fine with NaNs being converted to NaT, but it is worth worrying that the conversion (perhaps using the raise
argument).
.block1 {_x000D_
color: red;_x000D_
width: 100px;_x000D_
border: 1px solid green;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.block2 {_x000D_
color: blue;_x000D_
width: 70px;_x000D_
border: 2px solid black;_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
}
_x000D_
<div class='block1'>_x000D_
<p>text</p>_x000D_
<p>text2</p>_x000D_
<div class='block2'>block2</div>_x000D_
</div>
_x000D_
Should do it. Assuming you don't need it to flow.
If you're looking for a way to group constants in a class, you can use a static inner class:
public class OuterClass {
public void exit(boolean isTrue){
if(isTrue){
System.exit(ExitCode.A);
}else{
System.exit(ExitCode.B);
}
}
public static class ExitCode{
public static final int A = 203;
public static final int B = 204;
}
}
Adding the correct link here Kebab Case
which is All lowercase with - separating words.
public ActionResult CreatePerson(int id) //controller
window.location.href = '@Url.Action("CreatePerson", "Person")?id=' + id;
Or
var id = 'some value';
window.location.href = '@Url.Action("CreatePerson", "Person", new {id = id})';
In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.
Example:
function a() {
if (global_block) //syntax error is actually here - missing opening brace
return;
} //this unintentionally ends the function
if (global_somethingelse) {
//Chrome will show the error occurring here,
//but actually the error is in the previous statement
return;
}
//do something
}
dropdownlist.Items.Insert(0, new Listitem("--Select One--", "0");
In android gradle 0.4.0 you can just do:
println System.env.HOME
classpath com.android.tools.build:gradle-experimental:0.4.0
To remove a scrollbar from a view (and its subclass) via xml:
android:scrollbars="none"
http://developer.android.com/reference/android/view/View.html#attr_android:scrollbars
This example shows of how to use default value in the dropdown calendar and value in the text box. It also shows how to set default value to previous date.
selectedDate is another variable that holds current selected date of the calendar control
var date = new Date();
date.setDate(date.getDate() - 1);
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
defaultDate: date,
onSelect: function () {
selectedDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
}
});
$("#datepicker").datepicker("setDate", date);
Answers are simple. No and No (No).
By the time javascript is running the concept of source files/urls from which the come is gone.
There is also no way to determine a line number because again by the time of execution the notion of code "lines" is no longer meaningful in Javascript.
Specific implementations may provide API hooks to allow priviledged code access to such details for the purpose of debugging but these APIs are not exposed to ordinary standard Javascript code.
A literal translation of the mathematical definition is quite adequate in a lot of cases (remembering that Python will automatically use big number arithmetic):
from math import factorial
def calculate_combinations(n, r):
return factorial(n) // factorial(r) // factorial(n-r)
For some inputs I tested (e.g. n=1000 r=500) this was more than 10 times faster than the one liner reduce
suggested in another (currently highest voted) answer. On the other hand, it is out-performed by the snippit provided by @J.F. Sebastian.
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
the only solution for me was:
click on window->close all perspective (you can try also close perspective)
after this, in the top right corner click on: open perspective->resource
done
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
for single line comment add # at starting of a line
for multiple line comments add ' (single quote) from where you want to start & add ' (again single quote) at the point where you want to end the comment line.
Here is my function, uses binary search to find item and then inserts appropriately:
function binaryInsert(val, arr){_x000D_
let mid, _x000D_
len=arr.length,_x000D_
start=0,_x000D_
end=len-1;_x000D_
while(start <= end){_x000D_
mid = Math.floor((end + start)/2);_x000D_
if(val <= arr[mid]){_x000D_
if(val >= arr[mid-1]){_x000D_
arr.splice(mid,0,val);_x000D_
break;_x000D_
}_x000D_
end = mid-1;_x000D_
}else{_x000D_
if(val <= arr[mid+1]){_x000D_
arr.splice(mid+1,0,val);_x000D_
break;_x000D_
}_x000D_
start = mid+1;_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
_x000D_
console.log(binaryInsert(16, [_x000D_
5, 6, 14, 19, 23, 44,_x000D_
35, 51, 86, 68, 63, 71,_x000D_
87, 117_x000D_
]));
_x000D_
I know my case is rare, but I'll still add it here for someone who troubleshoots it later. I had a Linux Kernel module target in my Makefile and I tried to compile my user space program together with the kernel module that doesn't have stdio. Making it a separate target solved the problem.
What is wrong here is that your session management configuration is set to close session when you commit transaction. Check if you have something like:
<property name="current_session_context_class">thread</property>
in your configuration.
In order to overcome this problem you could change the configuration of session factory or open another session and only than ask for those lazy loaded objects. But what I would suggest here is to initialize this lazy collection in getModelByModelGroup itself and call:
Hibernate.initialize(subProcessModel.getElement());
when you are still in active session.
And one last thing. A friendly advice. You have something like this in your method:
for (Model m : modelList) {
if (m.getModelType().getId() == 3) {
model = m;
break;
}
}
Please insted of this code just filter those models with type id equal to 3 in the query statement just couple of lines above.
Some more reading:
Easy:
SELECT question_id, wm_concat(element_id) as elements
FROM questions
GROUP BY question_id;
Pesonally tested on 10g ;-)
From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
As of Sept 2018, Apple seems to (or a bug) block the normal way to get your XS and XS Max's UDID. Even XCode could not properly register new phones for you.
After a couple hours of digging, I figure it out:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Example
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());
This turns out to be a pretty deep area of theory, but the basic outline is simple.
Essentially, a hash function is just a function that takes things from one space (say strings of arbitrary length) and maps them to a space useful for indexing (unsigned integers, say).
If you only have a small space of things to hash, you might get away with just interpreting those things as integers, and you're done (e.g. 4 byte strings)
Usually, though, you've got a much larger space. If the space of things you allow as keys is bigger than the space of things you are using to index (your uint32's or whatever) then you can't possibly have a unique value for each one. When two or more things hash to the same result, you'll have to handle the redundancy in an appropriate way (this is usually referred to as a collision, and how you handle it or don't will depend a bit on what you are using the hash for).
This implies you want it to be unlikely to have the same result, and you probably also would really like the hash function to be fast.
Balancing these two properties (and a few others) has kept many people busy!
In practice you usually should be able to find a function that is known to work well for your application and use that.
Now to make this work as a hashtable: Imagine you didn't care about memory usage. Then you can create an array as long as your indexing set (all uint32's, for example). As you add something to the table, you hash it's key and look at the array at that index. If there is nothing there, you put your value there. If there is already something there, you add this new entry to a list of things at that address, along with enough information (your original key, or something clever) to find which entry actually belongs to which key.
So as you go a long, every entry in your hashtable (the array) is either empty, or contains one entry, or a list of entries. Retrieving is a simple as indexing into the array, and either returning the value, or walking the list of values and returning the right one.
Of course in practice you typically can't do this, it wastes too much memory. So you do everything based on a sparse array (where the only entries are the ones you actually use, everything else is implicitly null).
There are lots of schemes and tricks to make this work better, but that's the basics.
I've taken @meouw's answer, added in the clientLeft that allows for the border, and then created three versions:
getAbsoluteOffsetFromBody - similar to @meouw's, this gets the absolute position relative to the body or html element of the document (depending on quirks mode)
getAbsoluteOffsetFromGivenElement - returns the absolute position relative to the given element (relativeEl). Note that the given element must contain the element el, or this will behave the same as getAbsoluteOffsetFromBody. This is useful if you have two elements contained within another (known) element (optionally several nodes up the node tree) and want to make them the same position.
getAbsoluteOffsetFromRelative - returns the absolute position relative to the first parent element with position: relative. This is similar to getAbsoluteOffsetFromGivenElement, for the same reason but will only go as far as the first matching element.
getAbsoluteOffsetFromBody = function( el )
{ // finds the offset of el from the body or html element
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
getAbsoluteOffsetFromGivenElement = function( el, relativeEl )
{ // finds the offset of el from relativeEl
var _x = 0;
var _y = 0;
while( el && el != relativeEl && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
getAbsoluteOffsetFromRelative = function( el )
{ // finds the offset of el from the first parent with position: relative
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
if (el != null)
{
if (getComputedStyle !== 'undefined')
valString = getComputedStyle(el, null).getPropertyValue('position');
else
valString = el.currentStyle['position'];
if (valString === "relative")
el = null;
}
}
return { top: _y, left: _x };
}
If you are still having problems, particularly relating to scrolling, you could try looking at http://www.greywyvern.com/?post=331 - I noticed at least one piece of questionable code in getStyle which should be fine assuming browsers behave, but haven't tested the rest at all.
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".
http://www.w3schools.com/html5/tag_iframe.asp
or you can use
<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>
In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.
Lets have a look at following snippet of code
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] s = new String[t];
for (int i = 0; i < t; i++) {
s[i] = in.next();
}
when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as
Input as :- abcd abcd or
Input as :-
abcd
abcd
Output will be like abcd
abcd
But if in same code we replace next() method by nextLine()
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] s = new String[t];
for (int i = 0; i < t; i++) {
s[i] = in.nextLine();
}
Then if you enter input on prompt as - abcd abcd
Output is :-
abcd abcd
and if you enter the input on prompt as abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)
Output is:-
abcd
The answer for how to do this can be found here
>>> generator = (i for i in xrange(10))
>>> list(next(generator) for _ in range(4))
[0, 1, 2, 3]
>>> list(next(generator) for _ in range(4))
[4, 5, 6, 7]
>>> list(next(generator) for _ in range(4))
[8, 9]
Notice that the last call asks for the next 4 when only 2 are remaining. The use of the list()
instead of []
is what gets the comprehension to terminate on the StopIteration
exception that is thrown by next()
.
1) How do I make it so that the whole column is "checked" by default?
var doWork = new DataGridViewCheckBoxColumn();
doWork.Name = "IncludeDog" //Added so you can find the column in a row
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
//Make the default checked
doWork.CellTemplate.Value = true;
doWork.CellTemplate.Style.NullValue = true;
dataGridView1.Columns.Insert(0, doWork);
2) How can I make sure I'm only getting values from the "checked" rows?
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) continue;//If editing is enabled, skip the new row
//The Cell's Value gets it wrong with the true default, it will return
//false until the cell changes so use FormattedValue instead.
if (Convert.ToBoolean(row.Cells["IncludeDog"].FormattedValue))
{
//Do stuff with row
}
}
figure;
plot(something);
or
figure(2);
plot(something);
...
figure(3);
plot(something else);
...
etc.
You can get the desired result with the code below. Two'H' in HH
is for 24-hour format.
return fechaHora.Value.ToString("HH:mm");
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
If you just want to apply a function to each element and put the results in an output array, you can use arrayfun
.
As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.
If you use Python 2, don't forget to add the UTF-8 file encoding comment on the first line of your script.
# -*- coding: UTF-8 -*-
This will fix some Unicode problems and make your life easier.
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
I typically have a secrets.py
that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>
. This way you can rely on the operating systems in-built file security system without re-inventing your own.
Using Base64
encoding/decoding is also another way to obfuscate the password though not completely secure
More here - Hiding a password in a python script (insecure obfuscation only)
I'm a little confused about custom made completion handlers. In your example:
Say you have a download function to download a file from network,and want to be notified when download task has finished.
typealias CompletionHandler = (success:Bool) -> Void
func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {
// download code.
let flag = true // true if download succeed,false otherwise
completionHandler(success: flag)
}
Your // download code
will still be ran asynchronously. Why wouldn't the code go straight to your let flag = true
and completion Handler(success: flag)
without waiting for your download code to be finished?
You often will want to examine the particular properties of an instance of an object, without all of it's shared prototype methods and properties:
Obj.prototype.toString= function(){
var A= [];
for(var p in this){
if(this.hasOwnProperty(p)){
A[A.length]= p+'='+this[p];
}
}
return A.join(', ');
}
For scala
import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))
No, it isn't valid HTML5 according to the HTML5 Spec Document from W3C:
Content model: Transparent, but there must be no interactive content descendant.
The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).
In other words, you can nest any elements inside an <a>
except the following:
<a>
<audio>
(if the controls attribute is present)
<button>
<details>
<embed>
<iframe>
<img>
(if the usemap attribute is present)
<input>
(if the type attribute is not in the hidden state)
<keygen>
<label>
<menu>
(if the type attribute is in the toolbar state)
<object>
(if the usemap attribute is present)
<select>
<textarea>
<video>
(if the controls attribute is present)
If you are trying to have a button that links to somewhere, wrap that button inside a <form>
tag as such:
<form style="display: inline" action="http://example.com/" method="get">
<button>Visit Website</button>
</form>
However, if your <button>
tag is styled using CSS and doesn't look like the system's widget... Do yourself a favor, create a new class for your <a>
tag and style it the same way.
I know these answers are enough, but I'll show the place that's throwing an error.
If you have the structure like the below:
./Src/Master.cs
- (Master Form Page)./Invoice/SubFolder/InvoiceEdit.aspx
- (Sub Form Page)If you enter the sub form page, you'll get an error when you use similar like that you've used in master page: Page.ResolveClientUrl("~/Style/img/logo_small.png")
.
Now ResolveClientUrl
is situated in the master page and trying to serve the root folder. But since you are in the subfolder, the function returns something like ../../Style/img/logo_small.png
. This is the wrong way.
Because when you're up two levels, you are not in the right place; you need to go up only one level, so something like ../
.
1G=G
. That should indent all the lines in the file. 1G
takes you the first line, =
will start the auto-indent and the final G
will take you the last line in the file.
I already found the solution to this problem which I forgot to post here.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {
@Mock
Person person;
@Test
public void testPrintName() throws Exception {
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Test test= new Test();
test.testMethod();
}
}
Key points to this solution are:
Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)
Instruct Powermock to prepare Test.class
for manipulation of private fields: @PrepareForTest({ Test.class })
And finally mock the constructor for Person class:
PowerMockito.mockStatic(Person.class);
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
ADD
instruction copies files or folders from a local or remote source and adds them to the container's file system. It used to copy local files, those must be in the working directory. ADD
instruction unpacks local .tar
files to the destination image directory.
Example
ADD http://someserver.com/filename.pdf /var/www/html
COPY
copies files from the working directory and adds them to the container's file system. It is not possible to copy a remote file using its URL
with this Dockerfile instruction.
Example
COPY Gemfile Gemfile.lock ./
COPY ./src/ /var/www/html/
Copy structure only (copy all the columns)
Select Top 0 * into NewTable from OldTable
Copy structure only (copy some columns)
Select Top 0 Col1,Col2,Col3,Col4,Col5 into NewTable from OldTable
Copy structure with data
Select * into NewTable from OldTable
If you already have a table with same structure and you just want to copy data then use this
Insert into NewTable Select * from OldTable
Use the following to delete all the tables in a linux environment.
hive -e 'show tables' | xargs -I '{}' hive -e 'drop table {}'
One method:
System.AppDomain.CurrentDomain.BaseDirectory
Another way to do it would be:
System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
With Postgres 9.6 this can be done using the option if not exists
ALTER TABLE table_name ADD COLUMN IF NOT EXISTS column_name INTEGER;
I would emphasize the importance of limiting the ::ng-deep
to only children of a component by requiring the parent to be an encapsulated css class.
For this to work it's important to use the ::ng-deep
after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.
Using the :host
keyword before ::ng-deep
will handle this automatically:
:host ::ng-deep .mat-checkbox-layout
Alternatively you can achieve the same behavior by adding a component scoped CSS class before the ::ng-deep
keyword:
.my-component ::ng-deep .mat-checkbox-layout {
background-color: aqua;
}
Component template:
<h1 class="my-component">
<mat-checkbox ....></mat-checkbox>
</h1>
Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:
.my-component[_ngcontent-c1] .mat-checkbox-layout {
background-color: aqua;
}
For some reason the Android doc doesnt cover this, and the method used isnt even in the docs... took me a while to find it.
To detect if your scroll is at the top you would use this.
public boolean checkAtTop()
{
if(listView.getChildCount() == 0) return true;
return listView.getChildAt(0).getTop() == 0;
}
This will check if your scroller is at the top. Now, in order to do it for the bottom, you would have to pass it the number of children that you have, and check against that number. You might have to figure out how many are on the screen at one time, and subtract that from your number of children. I've never had to do that. Hope this helps
In the Fish Shell the length of an array can be found with:
$ set a 1 2 3 4
$ count $a
4
CSS code:
.hide{
display:none;
}
.show{
display:block;
}
Html code:
<button onclick="block_none()">Check Availability</button>
Javascript Code:
function block_none(){
document.getElementById('hidden-div').classList.add('show');
document.getElementById('button-id').classList.add('hide');
}
You can get pretty formatted xml with xml-beautify
var prettyXmlText = new XmlBeautify().beautify(xmlText,
{indent: " ",useSelfClosingElement: true});
indent:indent pattern like white spaces
useSelfClosingElement: true=>use self-closing element when empty element.
Original(Before)
<?xml version="1.0" encoding="utf-8"?><example version="2.0">
<head><title>Original aTitle</title></head>
<body info="none" ></body>
</example>
Beautified(After)
<?xml version="1.0" encoding="utf-8"?>
<example version="2.0">
<head>
<title>Original aTitle</title>
</head>
<body info="none" />
</example>
var test = {_x000D_
depth00: {_x000D_
depth10: 'string'_x000D_
, depth11: 11_x000D_
, depth12: {_x000D_
depth20:'string'_x000D_
, depth21:21_x000D_
}_x000D_
, depth13: [_x000D_
{_x000D_
depth22:'2201'_x000D_
, depth23:'2301'_x000D_
}_x000D_
, {_x000D_
depth22:'2202'_x000D_
, depth23:'2302'_x000D_
}_x000D_
]_x000D_
}_x000D_
,depth01: {_x000D_
depth10: 'string'_x000D_
, depth11: 11_x000D_
, depth12: {_x000D_
depth20:'string'_x000D_
, depth21:21_x000D_
}_x000D_
, depth13: [_x000D_
{_x000D_
depth22:'2201'_x000D_
, depth23:'2301'_x000D_
}_x000D_
, {_x000D_
depth22:'2202'_x000D_
, depth23:'2302'_x000D_
}_x000D_
]_x000D_
}_x000D_
, depth02: 'string'_x000D_
, dpeth03: 3_x000D_
};_x000D_
_x000D_
_x000D_
function traverse(result, obj, preKey) {_x000D_
if(!obj) return [];_x000D_
if (typeof obj == 'object') {_x000D_
for(var key in obj) {_x000D_
traverse(result, obj[key], (preKey || '') + (preKey ? '[' + key + ']' : key))_x000D_
}_x000D_
} else {_x000D_
result.push({_x000D_
key: (preKey || '')_x000D_
, val: obj_x000D_
});_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
document.getElementById('textarea').value = JSON.stringify(traverse([], test), null, 2);
_x000D_
<textarea style="width:100%;height:600px;" id="textarea"></textarea>
_x000D_
When you write "tests defined as class methods", do you really mean class methods (methods which receive its class as first parameter) or just regular methods (methods which receive an instance as first parameter)?
Since your example uses self
for the test methods I'm assuming the latter, so you just need to use setup_method
instead:
class Test:
def setup_method(self, test_method):
# configure self.attribute
def teardown_method(self, test_method):
# tear down self.attribute
def test_buttons(self):
# use self.attribute for test
The test method instance is passed to setup_method
and teardown_method
, but can be ignored if your setup/teardown code doesn't need to know the testing context. More information can be found here.
I also recommend that you familiarize yourself with py.test's fixtures, as they are a more powerful concept.
To check the entire string and not allow empty strings, try
^[A-Za-z0-9_]+$
Try
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">
Total: {{num1 + num2}}
and in js :
parseInt($scope.num1) + parseInt($scope.num2)
If you really don't want to use numpy
you can do something like this:
def matmult(a,b):
zip_b = zip(*b)
# uncomment next line if python 3 :
# zip_b = list(zip_b)
return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b))
for col_b in zip_b] for row_a in a]
x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
y = [[1,2],[1,2],[3,4]]
import numpy as np # I want to check my solution with numpy
mx = np.matrix(x)
my = np.matrix(y)
Result:
>>> matmult(x,y)
[[12, 18], [27, 42], [42, 66], [57, 90]]
>>> mx * my
matrix([[12, 18],
[27, 42],
[42, 66],
[57, 90]])
Here, Something about abstract class...
Real time example--
If you want to make a new car(WagonX) in which all the another car's properties are included like color,size, engine etc.and you want to add some another features like model,baseEngine in your car.Then simply you create a abstract class WagonX where you use all the predefined functionality as abstract and another functionalities are concrete, which is is defined by you.
Another sub class which extend the abstract class WagonX,By default it also access the abstract methods which is instantiated in abstract class.SubClasses also access the concrete methods by creating the subclass's object.
For reusability the code, the developers use abstract class mostly.
abstract class WagonX
{
public abstract void model();
public abstract void color();
public static void baseEngine()
{
// your logic here
}
public static void size()
{
// logic here
}
}
class Car extends WagonX
{
public void model()
{
// logic here
}
public void color()
{
// logic here
}
}
sentence.sub! 'Robert', 'Joe'
Won't cause an exception if the replaced word isn't in the sentence (the []=
variant will).
The above replaces only the first instance of "Robert".
To replace all instances use gsub
/gsub!
(ie. "global substitution"):
sentence.gsub! 'Robert', 'Joe'
The above will replace all instances of Robert with Joe.
I made the following code so that even beginners can understand. Just copy the code and read comments. Note that message to be send is declared as a global variable which you can change just before sending the message. General changes can be done in Handler function.
multiplayerConnect.java
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class multiplayerConnect extends AppCompatActivity {
public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;
String bluetooth_message="00";
@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
@Override
public void handleMessage(Message msg_type) {
super.handleMessage(msg_type);
switch (msg_type.what){
case MESSAGE_READ:
byte[] readbuf=(byte[])msg_type.obj;
String string_recieved=new String(readbuf);
//do some task based on recieved string
break;
case MESSAGE_WRITE:
if(msg_type.obj!=null){
ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
connectedThread.write(bluetooth_message.getBytes());
}
break;
case CONNECTED:
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
break;
case CONNECTING:
Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
break;
case NO_SOCKET_FOUND:
Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplayer_bluetooth);
initialize_layout();
initialize_bluetooth();
start_accepting_connection();
initialize_clicks();
}
public void start_accepting_connection()
{
//call this on button click as suited by you
AcceptThread acceptThread = new AcceptThread();
acceptThread.start();
Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Object[] objects = set_pairedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) objects[position];
ConnectThread connectThread = new ConnectThread(device);
connectThread.start();
Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
}
});
}
public void initialize_layout()
{
lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
lv_paired_devices.setAdapter(adapter_paired_devices);
}
public void initialize_bluetooth()
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
finish();
}
//Add these permisions before
// <uses-permission android:name="android.permission.BLUETOOTH" />
// <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
// <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else {
set_pairedDevices = bluetoothAdapter.getBondedDevices();
if (set_pairedDevices.size() > 0) {
for (BluetoothDevice device : set_pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
}
}
}
}
public class AcceptThread extends Thread
{
private final BluetoothServerSocket serverSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
} catch (IOException e) { }
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null)
{
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(CONNECTED).sendToTarget();
}
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mHandler.obtainMessage(CONNECTING).sendToTarget();
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// bluetooth_message = "Initial message"
// mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[2]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
multiplayer_bluetooth.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Challenge player"/>
<ListView
android:id="@+id/lv_paired_devices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</ListView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Make sure Device is paired"/>
</LinearLayout>
A developer accidentally wrote code that generated and ran the following SQL statement CREATE OR REPLACE PUBLIC SYNONYM "DUAL" FOR "DUAL";
which caused select * from dba_synonyms where table_name = 'DUAL';
to return PUBLIC DUAL SOME_USER DUAL
rather than PUBLIC DUAL SYS DUAL
.
We were able to fix it (thanks to How to recreate public synonym "DUAL"?) by running
ALTER SYSTEM SET "_SYSTEM_TRIG_ENABLED"=FALSE SCOPE=MEMORY;
CREATE OR REPLACE PUBLIC SYNONYM DUAL FOR SYS.DUAL;
ALTER SYSTEM SET "_SYSTEM_TRIG_ENABLED"=true SCOPE=MEMORY;
you should use "exit" after header-call
header('Location: http://www.example.com/?blabla=blubb');
exit;
For Oracle (PL/SQL)
SELECT column_name
FROM user_tab_cols
WHERE table_name = 'myTableName'
For MySQL
SHOW COLUMNS FROM table_name
I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:
if l:
print "list has items"
elif not l:
print "list is empty"
the error will be:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Just wanted to add a comment in BRPocock, but I don't have the sufficient privilegies.
So my contribution was for everyone trying to install IBM Integration Toolkit from IBM's Integration Bus bundle.
When you try to run "Installation Manager" command from folder /Integration_Toolkit/IM_Linux (the file to run is "install") you get the error showed in this post.
Further instructions to fix this problem you'll find in this IBM's web page: https://www-304.ibm.com/support/docview.wss?uid=swg21459143
Hope this helps for anybody trying to install that.
You can use Q objects for this. They can be negated with the ~
operator and combined much like normal Python expressions:
from myapp.models import Entry
from django.db.models import Q
Entry.objects.filter(~Q(id=3))
will return all entries except the one(s) with 3
as their ID:
[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
$?
is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep
command succeeded.
The grep
manpage states:
The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)
So in this case it's checking whether any ERROR lines were found.
make sure that your composer is up to date. write in the cmd
composer create-project –-prefer-dist laravel/laravel NameOfProject "Version"
If you like to count duplicates on particular column(s):
len(df['one'])-len(df['one'].drop_duplicates())
If you want to count duplicates on entire dataframe:
len(df)-len(df.drop_duplicates())
Or simply you can use DataFrame.duplicated(subset=None, keep='first'):
df.duplicated(subset='one', keep='first').sum()
where
subset : column label or sequence of labels(by default use all of the columns)
keep : {‘first’, ‘last’, False}, default ‘first’
Like others have mentioned, I think of roles as containers for more granular permissions.
Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.
I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.
Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST
These permissions are relatively static, but the relationship of roles to them may be dynamic.
Example -
@Autowired
RolePermissionsRepository repository;
public void setup(){
String roleName = "ROLE_ADMIN";
List<String> permissions = new ArrayList<String>();
permissions.add("CREATE");
permissions.add("READ");
permissions.add("UPDATE");
permissions.add("DELETE");
repository.save(new RolePermissions(roleName, permissions));
}
You may create APIs to manage the relationship of these permissions to a role.
I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685
To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions
select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;
This is the fastest way to retrieve the row counts but there are a few important caveats:
ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE
(the default), or in earlier versions with ESTIMATE_PERCENT => 100
. See this post for an explanation of how
the AUTO_SAMPLE_SIZE algorithm works in 11g.LAST_ANALYZED
, the current results may be different."commentLine" is the name of function you are looking for. This function coment and uncoment with the same keybinding
You just have to put the <form ... >
tag before the <table>
tag and the </form>
at the end.
Hopte it helps.
Like this, using .limit():
var q = models.Post.find({published: true}).sort('date', -1).limit(20);
q.execFind(function(err, posts) {
// `posts` will be of length 20
});
I have found following way to fix this issue... I hope this can help you.
json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
1) I'd add a /n after init. i.e. write( USB, "init\n", 5);
2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.
3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?
Edited to Add:
Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.
int tmp, serialLines;
cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);
cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
This may be a way to do it too. Inspired from these links Experts-exchange and alinalexander
function slugifier($txt){
/* Get rid of accented characters */
$search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
$replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");
$txt = str_replace($search, $replace, $txt);
/* Lowercase all the characters */
$txt = strtolower($txt);
/* Avoid whitespace at the beginning and the ending */
$txt = trim($txt);
/* Replace all the characters that are not in a-z or 0-9 by a hyphen */
$txt = preg_replace("/[^a-z0-9]/", "-", $txt);
/* Remove hyphen anywhere it's more than one */
$txt = preg_replace("/[\-]+/", '-', $txt);
return $txt;
}
Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:
<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin" />
<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />
The outcome would be
$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'],
'city' => [ 'Berlin' , 'New York'] ];
To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:
<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin" />
<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />
The outcome would be
$POST = [ 'address' => [
1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
2 => ['street' => 'Wallstreet', 'city' => 'New York'],
]
]
I would rather keep my watchers a less as possible. My reason is based on my experiences and one might argue it theoretically.
The issue with using watchers is that you can use any property on scope to call any of the methods in any component or service you like.
In a real world project, pretty soon you'll end up with a non-tracable (better said hard to trace) chain of methods being called and values being changed which specially makes the on-boarding process tragic.
It is not good to manipulate with DOM (including checking of attributes) in any place except directives. You can add into scope some value indicating if link should be disabled.
But other problem is that ngDisabled does not work on anything except form controls, so you can't use it with <a>, but you can use it with <button> and style it as link.
Another way is to use lazy evaluation of expressions like isDisabled || action()
so action wouold not be called if isDisabled
is true.
Here goes both solutions: http://plnkr.co/edit/5d5R5KfD4PCE8vS3OSSx?p=preview
See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page)
You may be looking for following code:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Same page...lower down.
You can do forward typedef. But to do
typedef A B;
you must first forward declare A
:
class A;
typedef A B;
If by any chance you were using
D3.js
You could do
d3.set(["foo", "bar", "foo", "baz"]).values() ==> ["foo", "bar", "baz"]
Try this one. Hope this is working fine.. :)
@ECHO off
cls
ECHO.
set drvltr=
set /p drvltr=Enter Drive letter:
attrib -s -h -a /s /d %drvltr%:\*.*
ECHO Unhide Completed
pause
white spaces matter. when block is finished, that's when the function definition is finished.
when function runs, it keeps going until it finishes, or until return
or yield
statement is encountered. If function finishes without encountering return
or yield
statements None
is returned implicitly.
there is plenty more information in the tutorial.
This is the best solution for Java 7+
:
public static void deleteDirectory(String directoryFilePath) throws IOException
{
Path directory = Paths.get(directoryFilePath);
if (Files.exists(directory))
{
Files.walkFileTree(directory, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException
{
Files.delete(path);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException
{
Files.delete(directory);
return FileVisitResult.CONTINUE;
}
});
}
}
I think, this is the simplest technique to beautify the json data,
String indented = (new JSONObject(Response)).toString(4);
where Response is a String.
Simply pass the 4(indentSpaces) in toString()
method.
Note: It works fine in the android without any library. But in java you have to use the org.json library.
Did you, by any chance, deleted stuff from your workspace, or moved it around?
When you create a server for the first time, either globally or through the project's "run on server" settings, Eclipse creates a project in the Servers view, as BalusC pointed out. Eclipse stores this server inside your workspace, in a project called Servers. The project needs to be open for tomcat to run.
(If you want, you can store the server settings elsewher. You can right click and open the server instance from the Servers view and configure various parameters and locations)
--SQL Server 2005+
CREATE TABLE dbo.Students
(
StudentId INT
, Name VARCHAR(50)
, CONSTRAINT PK_Students PRIMARY KEY (StudentId)
);
CREATE TABLE dbo.Subjects
(
SubjectId INT
, Name VARCHAR(50)
, CONSTRAINT PK_Subjects PRIMARY KEY (SubjectId)
);
CREATE TABLE dbo.Schedules
(
StudentId INT
, SubjectId INT
, CONSTRAINT PK__Schedule PRIMARY KEY (StudentId, SubjectId)
, CONSTRAINT FK_Schedule_Students FOREIGN KEY (StudentId) REFERENCES dbo.Students (StudentId)
, CONSTRAINT FK_Schedule_Subjects FOREIGN KEY (SubjectId) REFERENCES dbo.Subjects (SubjectId)
);
INSERT dbo.Students (StudentId, Name) VALUES
(1, 'Mary')
, (2, 'John')
, (3, 'Sam')
, (4, 'Alaina')
, (5, 'Edward')
;
INSERT dbo.Subjects (SubjectId, Name) VALUES
(1, 'Physics')
, (2, 'Geography')
, (3, 'French')
, (4, 'Gymnastics')
;
INSERT dbo.Schedules (StudentId, SubjectId) VALUES
(1, 1) --Mary, Physics
, (2, 1) --John, Physics
, (3, 1) --Sam, Physics
, (4, 2) --Alaina, Geography
, (5, 2) --Edward, Geography
;
SELECT
sub.SubjectId
, sub.Name AS [SubjectName]
, ISNULL( x.Students, '') AS Students
FROM
dbo.Subjects sub
OUTER APPLY
(
SELECT
CASE ROW_NUMBER() OVER (ORDER BY stu.Name) WHEN 1 THEN '' ELSE ', ' END
+ stu.Name
FROM
dbo.Students stu
INNER JOIN dbo.Schedules sch
ON stu.StudentId = sch.StudentId
WHERE
sch.SubjectId = sub.SubjectId
ORDER BY
stu.Name
FOR XML PATH('')
) x (Students)
;
This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here
You should convert the stream into byte array and then you can read file content
Please refer following link
http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]
Hope this helps
UPDATE :
The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.
Taken from here
// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
string result = System.Text.Encoding.UTF8.GetString(binData);
The Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?
It's a way that an attacker can potentially hijack sessions without even knowing session tokens.
Scenario:
CSRF solution:
Block 2 doesn't work because it doesn't reset the Error Handler potentially causing an endless loop. For Error Handling to work properly in VBA, you need a Resume
statement to clear the Error Handler. The Resume
also reactivates the previous Error Handler. Block 2 fails because a new error would go back to the previous Error Handler causing an infinite loop.
Block 3 fails because there is no Resume
statement so any attempt at error handling after that will fail.
Every error handler must be ended by exiting the procedure or a Resume
statement. Routing normal execution around an error handler is confusing. This is why error handlers are usually at the bottom.
But here is another way to handle an error in VBA. It handles the error inline like Try/Catch in VB.net There are a few pitfalls, but properly managed it works quite nicely.
Sub InLineErrorHandling()
'code without error handling
BeginTry1:
'activate inline error handler
On Error GoTo ErrHandler1
'code block that may result in an error
Dim a As String: a = "Abc"
Dim c As Integer: c = a 'type mismatch
ErrHandler1:
'handle the error
If Err.Number <> 0 Then
'the error handler has deactivated the previous error handler
MsgBox (Err.Description)
'Resume (or exit procedure) is the only way to get out of an error handling block
'otherwise the following On Error statements will have no effect
'CAUTION: it also reactivates the previous error handler
Resume EndTry1
End If
EndTry1:
'CAUTION: since the Resume statement reactivates the previous error handler
'you must ALWAYS use an On Error GoTo statement here
'because another error here would cause an endless loop
'use On Error GoTo 0 or On Error GoTo <Label>
On Error GoTo 0
'more code with or without error handling
End Sub
Sources:
The key to making this work is to use a Resume
statement immediately followed by another On Error
statement. The Resume
is within the error handler and diverts code to the EndTry1
label. You must immediately set another On Error
statement to avoid problems as the previous error handler will "resume". That is, it will be active and ready to handle another error. That could cause the error to repeat and enter an infinite loop.
To avoid using the previous error handler again you need to set On Error
to a new error handler or simply use On Error Goto 0
to cancel all error handling.
Following is the method I found:
1) Make a list of files with relative paths in a file (say FilesList.txt) as follows (either space separated or line separated):
foo/AccessTestInterface.java
foo/goo/AccessTestInterfaceImpl.java
2) Use the command:
javac @FilesList.txt -d classes
This will compile all the files and put the class files inside classes directory.
Now easy way to create FilesList.txt is this: Go to your source root directory.
dir *.java /s /b > FilesList.txt
But, this will populate absolute path. Using a text editor "Replace All" the path up to source directory (include \ in the end) with "" (i.e. empty string) and Save.
worked for me
let returnPayments = [ ...this.payments ];
returnPayments[this.payments.findIndex(x => x.id == this.payment.id)] = this.payment;
Here it is how to use MockHttpServletRequest:
// given
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServerName("www.example.com");
request.setRequestURI("/foo");
request.setQueryString("param1=value1¶m");
// when
String url = request.getRequestURL() + '?' + request.getQueryString(); // assuming there is always queryString.
// then
assertThat(url, is("http://www.example.com:80/foo?param1=value1¶m"));
// using System.Xml;
String rawXml =
@"<root>
<person firstname=""Riley"" lastname=""Scott"" />
<person firstname=""Thomas"" lastname=""Scott"" />
</root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);
I think this should work.
Code:
using System;
using System.Diagnostics;
namespace playSound
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(args[0]);
Process amixerMediaProcess = new Process();
amixerMediaProcess.StartInfo.CreateNoWindow = false;
amixerMediaProcess.StartInfo.UseShellExecute = false;
amixerMediaProcess.StartInfo.ErrorDialog = false;
amixerMediaProcess.StartInfo.RedirectStandardOutput = false;
amixerMediaProcess.StartInfo.RedirectStandardInput = false;
amixerMediaProcess.StartInfo.RedirectStandardError = false;
amixerMediaProcess.EnableRaisingEvents = true;
amixerMediaProcess.StartInfo.Arguments = string.Format("{0}","-ssh username@"+args[0]+" -pw password -m commands.txt");
amixerMediaProcess.StartInfo.FileName = "plink.exe";
amixerMediaProcess.Start();
Console.Write("Presskey to continue . . . ");
Console.ReadKey(true);
}
}
}
Sample commands.txt:
ps
From MSDN
To execute a stored procedure returning rows programmatically using a command object
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
someVar = reader(0)
someVar2 = reader(1)
someVar3 = reader("NamedField")
End If
sqlConnection1.Close()
If you just want to stop further code from executing without "throwing" any error, you can temporarily override window.onerror
as shown in cross-exit
:
function exit(code) {
const prevOnError = window.onerror
window.onerror = () => {
window.onerror = prevOnError
return true
}
throw new Error(`Script termination with code ${code || 0}.`)
}
console.log("This message is logged.");
exit();
console.log("This message isn't logged.");
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
You can use like this:
public static String executeHttpPost1(String url,
HashMap<String, String> postParameters) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
HttpClient client = getNewHttpClient();
try{
request = new HttpPost(url);
}
catch(Exception e){
e.printStackTrace();
}
if(postParameters!=null && postParameters.isEmpty()==false){
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
String k, v;
Iterator<String> itKeys = postParameters.keySet().iterator();
while (itKeys.hasNext())
{
k = itKeys.next();
v = postParameters.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(nameValuePairs);
request.setEntity(urlEntity);
}
try {
Response = client.execute(request,localContext);
HttpEntity entity = Response.getEntity();
int statusCode = Response.getStatusLine().getStatusCode();
Log.i(TAG, ""+statusCode);
Log.i(TAG, "------------------------------------------------");
try{
InputStream in = (InputStream) entity.getContent();
//Header contentEncoding = Response.getFirstHeader("Content-Encoding");
/*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
response = str.toString();
Log.i(TAG, "response"+response);
}
catch(IllegalStateException exc){
exc.printStackTrace();
}
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+response);
}
finally {
}
return response;
}
There are several solutions depending on what you need...
If you want to add a custom header (or set of headers) to an individual request then just add the headers
property:
// Request with custom header
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});
If you want to add a default header (or set of headers) to every request then use $.ajaxSetup()
:
$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
If you want to add a header (or set of headers) to every request then use the beforeSend
hook with $.ajaxSetup()
:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
Edit (more info): One thing to be aware of is that with ajaxSetup
you can only define one set of default headers and you can only define one beforeSend
. If you call ajaxSetup
multiple times, only the last set of headers will be sent and only the last before-send callback will execute.
Please try using following way.
@Html.Hidden("hdnFlag",(object) Convert.ToInt32(ViewBag.page_Count))
You can avoid adding extra markup. This works everywhere except IE for Desktop (but works in IE for Windows Phone and Microsoft Edge) via setting CSS appearance
:
input[type="checkbox"] {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
_x000D_
/* Styling checkbox */_x000D_
width: 16px;_x000D_
height: 16px;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked {_x000D_
background-color: green;_x000D_
}
_x000D_
<input type="checkbox" />
_x000D_
DO this :
Create libs folder under the application folder. Add .jar files to libs folder. Then add .jar files to app's build.gradle dependency. Finally Sync project with Gradle files.
Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):
$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});
"This is my string with date in specified format $($theDate.ToString('u'))"
or
"This is my string with date in specified format $(Get-Date -format 'u')"
The sub-expression ($(...)
) can include arbitrary expressions calls.
MSDN Documents both standard and custom DateTime
format strings.
Use not
, for example:
return not myval
I would suggest (jQuery needed) :
/*
* windowSize
* call this function to get windowSize any time
*/
function windowSize() {
windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
}
//Init Function of init it wherever you like...
windowSize();
// For example, get window size on window resize
$(window).resize(function() {
windowSize();
console.log('width is :', windowWidth, 'Height is :', windowHeight);
if (windowWidth < 768) {
console.log('width is under 768px !');
}
});
Added in CodePen : http://codepen.io/moabi/pen/QNRqpY?editors=0011
Then you can get easily window's width with the var : windowWidth and Height with : windowHeight
otherwise, get a js library : http://wicky.nillia.ms/enquire.js/
In Linux file system , Edit below file as this steps
Path - /opt/glassfish3/glassfish/config
File Name - asenv.conf
Add the JAVA HOME path as below to the end of file.
AS_JAVA=/opt/jdk1.8.0_201
Now start the glassfish server.
You can use GROUP_CONCAT to perform that, e.g. something like
SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id, p.name;
http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Matchers.html
anyObject()
should fit your needs.
Also, you can always consider implementing hashCode()
and equals()
for the Bazoo
class. This would make your code example work the way you want.
const el = document.getElementById("editable");
el.focus()
let char = 1, sel; // character at which to place caret
if (document.selection) {
sel = document.selection.createRange();
sel.moveStart('character', char);
sel.select();
}
else {
sel = window.getSelection();
sel.collapse(el.lastChild, char);
}
Speaking for current (2021-2) Java versions there is still the old ISO-8859-1 function utils.Properties#load.
Allow me to quote from the official doc.
PropertyResourceBundle
PropertyResourceBundle can be constructed either from an InputStream or a Reader, which represents a property file. Constructing a PropertyResourceBundle instance from an InputStream requires that the input stream be encoded in UTF-8. By default, if a MalformedInputException or an UnmappableCharacterException occurs on reading the input stream, then the PropertyResourceBundle instance resets to the state before the exception, re-reads the input stream in ISO-8859-1, and continues reading. If the system property java.util.PropertyResourceBundle.encoding is set to either "ISO-8859-1" or "UTF-8", the input stream is solely read in that encoding, and throws the exception if it encounters an invalid sequence. If "ISO-8859-1" is specified, characters that cannot be represented in ISO-8859-1 encoding must be represented by Unicode Escapes as defined in section 3.3 of The Java™ Language Specification whereas the other constructor which takes a Reader does not have that limitation. Other encoding values are ignored for this system property. The system property is read and evaluated when initializing this class. Changing or removing the property has no effect after the initialization.
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/PropertyResourceBundle.html
Properties#load
Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.
SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
FROM all_constraints cons, all_cons_columns cols
WHERE cols.table_name = 'TABLE_NAME'
AND cons.constraint_type = 'P'
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner
ORDER BY cols.table_name, cols.position;
Make sure that 'TABLE_NAME' is in upper case since Oracle stores table names in upper case.
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
MacOS High Sierra is very crazy to update openssl command suddenly.
Possible in last month:
$ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts
MAC verified OK
But now:
$ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts -password pass:
MAC verified OK
You can use jQuery UI and do something like this
Html:
<button id="callConfirm">Confirm!</button>
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>?
Javascript:
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons : {
"Confirm" : function() {
alert("You have confirmed!");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#callConfirm").on("click", function(e) {
e.preventDefault();
$("#dialog").dialog("open");
});
?
Quick and dirty technique:
static byte[] StreamToByteArray(Stream inputStream)
{
if (!inputStream.CanRead)
{
throw new ArgumentException();
}
// This is optional
if (inputStream.CanSeek)
{
inputStream.Seek(0, SeekOrigin.Begin);
}
byte[] output = new byte[inputStream.Length];
int bytesRead = inputStream.Read(output, 0, output.Length);
Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
return output;
}
Test:
static void Main(string[] args)
{
byte[] data;
string path = @"C:\Windows\System32\notepad.exe";
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
{
data = StreamToByteArray(fs);
}
Debug.Assert(data.Length > 0);
Debug.Assert(new FileInfo(path).Length == data.Length);
}
I would ask, why do you want to read a stream into a byte[], if you are wishing to copy the contents of a stream, may I suggest using MemoryStream and writing your input stream into a memory stream.
The metacharacter \b
is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.
There are three different positions that qualify as word boundaries:
Simply put: \b
allows you to perform a "whole words only" search using a regular expression in the form of \bword\b
. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".
In all flavors, the characters [a-zA-Z0-9_]
are word characters. These are also matched by the short-hand character class \w
. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.
\w
stands for "word character", usually [A-Za-z0-9_]
. Notice the inclusion of the underscore and digits.
\B
is the negated version of \b
. \B
matches at every position where \b
does not. Effectively, \B
matches at any position between two word characters as well as at any position between two non-word characters.
\W
is short for [^\w]
, the negated version of \w
.
Here is a little work around that I created. I checked it with R and it works correct.
import numpy as np
import statsmodels.api as sm
y = [1,2,3,4,3,4,5,4,5,5,4,5,4,5,4,5,6,5,4,5,4,3,4]
x = [
[4,2,3,4,5,4,5,6,7,4,8,9,8,8,6,6,5,5,5,5,5,5,5],
[4,1,2,3,4,5,6,7,5,8,7,8,7,8,7,8,7,7,7,7,7,6,5],
[4,1,2,5,6,7,8,9,7,8,7,8,7,7,7,7,7,7,6,6,4,4,4]
]
def reg_m(y, x):
ones = np.ones(len(x[0]))
X = sm.add_constant(np.column_stack((x[0], ones)))
for ele in x[1:]:
X = sm.add_constant(np.column_stack((ele, X)))
results = sm.OLS(y, X).fit()
return results
Result:
print reg_m(y, x).summary()
Output:
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.535
Model: OLS Adj. R-squared: 0.461
Method: Least Squares F-statistic: 7.281
Date: Tue, 19 Feb 2013 Prob (F-statistic): 0.00191
Time: 21:51:28 Log-Likelihood: -26.025
No. Observations: 23 AIC: 60.05
Df Residuals: 19 BIC: 64.59
Df Model: 3
==============================================================================
coef std err t P>|t| [95.0% Conf. Int.]
------------------------------------------------------------------------------
x1 0.2424 0.139 1.739 0.098 -0.049 0.534
x2 0.2360 0.149 1.587 0.129 -0.075 0.547
x3 -0.0618 0.145 -0.427 0.674 -0.365 0.241
const 1.5704 0.633 2.481 0.023 0.245 2.895
==============================================================================
Omnibus: 6.904 Durbin-Watson: 1.905
Prob(Omnibus): 0.032 Jarque-Bera (JB): 4.708
Skew: -0.849 Prob(JB): 0.0950
Kurtosis: 4.426 Cond. No. 38.6
pandas
provides a convenient way to run OLS as given in this answer:
The problem is on this line:
oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"
Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:
oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
You also have a typo in S:Claims\Sound.wav
, should be S:\Claims\Sound.wav
.
I also assume the apostrophe before Dim oShell
and after Set oShell = Nothing
are typos as well.
I would suggest, one should not make object of an Activity type class.
MainActivity mActivity = new MainActivity(); // BIG NO TO THIS.
All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them.
By treating an Activity as a normal Java class, you end up with a null context. As most methods in an Activity are called on its Context, you will get a null pointer exception, which is why your app crashes.
Instead, move all such methods which need to be called from other classes into a Utility class which accepts a valid context in its constructor, and then use that context in the methods to do the work.
This should do the trick:
$('#thisElement').find('.classToSelect')
You can use
document.querySelector('your-element').scrollIntoView({behavior: 'smooth'});
If you want to scroll top the top of the page, you can just place an empty element in the top, and smooth scroll to that one.
File -> Spreadsheet Settings -> (Tab) Calculation -> Recalculation (3 Options)
- On change
- On change and every minute
- On change and every hour
This affects how often NOW, TODAY, RAND, and RANDBETWEEN are updated.
but..
.. it updates only, if the functions arguments (their ranges, cells) are affected by that.
from my example
I use google spreadsheet to find out the age of a person. I have his birthday date in the format (dd.mm.yyyy) -> it's the used format here in Switzerland.
=ARRAYFORMULA(IF(ISTEXT(K4:K), IF(TODAY() - DATE(YEAR(TODAY()), MONTH(REGEXREPLACE(K4:K, "[.]", "/")), DAY(REGEXREPLACE(K4:K, "[.]", "/"))) > 0, YEAR(TODAY()) - YEAR(REGEXREPLACE(K4:K, "[.]", "/")) + 1, YEAR(TODAY()) - YEAR(REGEXREPLACE(K4:K, "[.]", "/"))), IF(LEN(K4:K) > 0, IF(TODAY() - DATE(YEAR(TODAY()), MONTH(K4:K), DAY(K4:K)) > 0, YEAR(TODAY()) - YEAR(K4:K) + 1, YEAR(TODAY()) - YEAR(K4:K)), "")))
I'm using TODAY()
and I did the recalculation settings described above. -> but no automatically refresh. :-(
It updates only, if I change some value inside the ranges where the function is looking for.
So I wrote a Google Script (Tools -> Script Editor..) for that purpose.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetMaster = ss.getSheetByName("Master");
var sortRange = sheetMaster.getRange(firstRow, firstColumn, lastRow, lastColumn);
sortRange.getCell(1, 2).setValue(sortRange.getCell(1, 2).getValue());
}
You need to set numbers for firstRow
, firstColumn
, lastRow
, lastColumn
The Script get active when the spreadsheets open, writes the content of one cell into the same cell again. That's enough to trigger the TODAY()
function.
Look for more information on that link from Edward Moffett. Force google sheet formula to recalculate
Best regards,
Christoph
Please use chomp()
or chomp()
with STDIN
i.e. test1.rb
print 'Enter File name: '
fname = STDIN.gets.chomp() # or fname = gets.chomp()
fname_read = File.open(fname)
puts fname_read.read()
Here is an easy one:
$myVar > "c:\myfilepath\myfilename.myextension"
You can also try:
Get-content "c:\someOtherPath\someOtherFile.myextension" > "c:\myfilepath\myfilename.myextension"
There are a lot of insightful answers there already, but still, I would to direct to a slightly different situation: Instead of precondition, that should be put on top of a function indeed, think of a step-by-step initialization, where you have to check for each step to succeed and then continue with the next. In this case, you cannot check everything at the top.
I found my code really unreadable when writing an ASIO host application with Steinberg's ASIOSDK, as I followed the nesting paradigm. It went like eight levels deep, and I cannot see a design flaw there, as mentioned by Andrew Bullock above. Of course, I could have packed some inner code to another function, and then nested the remaining levels there to make it more readable, but this seems rather random to me.
By replacing nesting with guard clauses, I even discovered a misconception of mine regarding a portion of cleanup-code that should have occurred much earlier within the function instead of at the end. With nested branches, I would never have seen that, you could even say they led to my misconception.
So this might be another situation where inverted ifs can contribute to a clearer code.
I'm adding Bard Park's comment here for that was the real answer for me:
Since mvim is simply a shell script, you can download it directly from the MacVim source at GitHub here: http://raw.github.com/b4winckler/macvim/master/src/MacVim/mvim
<ImageButton
android:background="@drawable/action_button_bg"
android:layout_width="56dp"
android:layout_height="56dp"
android:padding="16dp"
android:src="@drawable/ic_add_black_48dp"
android:scaleType="fitXY"
android:elevation="8dp"/>
With the background you provided it results in below button on my device (Nexus 7 2012)
Looks good to me.
import urllib2
for line in urllib2.urlopen("http://www.myhost.com/SomeFile.txt"):
print line
Use the following code:
import numpy as np
myArray=np.array([1,2,4]) #func used to convert [1,2,3] list into an array
print(myArray)
I got tired of seeing this page with its by-now stale references to defunct Codehaus pages so I asked on the Maven Users mailing list and got some more up-to-date answers.
I would say that the best (and most authoritative) answer contained in my link above is the one contributed by Hervé BOUTEMY:
here is the core reference: http://maven.apache.org/ref/3-LATEST/maven-model-builder/
it does not explain everyting that can be found in POM or in settings, since there are so much info available but it points to POM and settings descriptors and explains everything that is not POM or settings
You cannot safely do what you want since the default hashCode() may not return the address, and has been mentioned, multiple objects with the same hashCode are possible. The only way to accomplish what you want, is to actually override the hashCode() method for the objects in question and guarantee that they all provide unique values. Whether this is feasible in your situation is another question.
For the record, I have experienced multiple objects with the same default hashcode in an IBM VM running in a WAS server. We had a defect where objects being put into a remote cache would get overwritten because of this. That was an eye opener for me at that point since I assumed the default hashcode was the objects memory address as well.
Rather than using a proxy, I'm using the Firefox plugin "Modify Headers" to insert headers (in my case, to fake a login using the Single Sign On so I can test as different people).
Do this.
var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);
list.stream().map(x -> x.getName()).forEach(System.out::println);
Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> **$dte = Get-Date**
PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
PS C:\Windows\system32> **$PastDueDate**
Sunday, March 1, 2020 12:00:00 AM
PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
PS C:\Windows\system32> **$NewDateFormat 03012020**
There're few additional methods available as well e.g.: $dte.AddDays(-45).Day
Problem: Even I was facing the problem where we were sending '£' with some string in POST request to CRM System, but when we were doing the GET call from CRM , it was returning '£' with some string content. So what we have analysed is that '£' was getting converted to '£'.
Analysis: The glitch which we have found after doing research is that in POST call we have set HttpWebRequest ContentType as "text/xml" while in GET Call it was "text/xml; charset:utf-8".
Solution: So as the part of solution we have included the charset:utf-8 in POST request and it works.
I had the same problem on my LG-E730 with 2.3.4 Android. The error appears before I've updated Google Play Service on my phone.
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
I had the following problem where I was fetching data from a database and wanted to display a string containing \n
. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208
It is now possible with the HTML5 webapp manifest. See below.
Original answer:
You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.
You can detect the device orientation with CSS3 media queries like this:
@media screen and (orientation:portrait) {
// CSS applied when the device is in portrait mode
}
@media screen and (orientation:landscape) {
// CSS applied when the device is in landscape mode
}
Or by binding a JavaScript orientation change event like this:
document.addEventListener("orientationchange", function(event){
switch(window.orientation)
{
case -90: case 90:
/* Device is in landscape mode */
break;
default:
/* Device is in portrait mode */
}
});
Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.
As explained on html5rocks.com, you can now force the orientation mode using a manifest.json
file.
You need to include those line into the json file:
{
"display": "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
"orientation": "landscape", /* Could be "landscape" or "portrait" */
...
}
And you need to include the manifest into your html file like this:
<link rel="manifest" href="manifest.json">
Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.
You don't need to create a user-defined setting. The built-in setting "Preprocessor Macros" works just fine. alt text http://idisk.mac.com/cdespinosa/Public/Picture%204.png
If you have multiple targets or projects that use the same prefix file, use Preprocessor Macros Not Used In Precompiled Headers instead, so differences in your macro definition don't trigger an unnecessary extra set of precompiled headers.
don't need regex just use classlist
var id=document.getElementById('myButton');
function toggle(el,classname){
if(el.classList.contains(classname)){
el.classList.remove(classname)
}
else{
el.classList.add(classname)
}
}
id.addEventListener('click',(e)=>{
toggle(e.target,'red')
})
_x000D_
.red{
background:red
}
_x000D_
<button id="myButton">Switch</button>
_x000D_
Simple Usage above Example
var id=document.getElementById('myButton');
function toggle(el,classname){
el.classList.toggle(classname)
}
id.addEventListener('click',(e)=>{
toggle(e.target,'red')
})
_x000D_
.red{
background:red
}
_x000D_
<button id="myButton">Switch</button>
_x000D_
ksh93:
dt=${ printf "%(%a %d/%m/%Y)T" yesterday; }
or:
dt=$(printf "%(%a %d/%m/%Y)T" yesterday)
The first one runs in the same process, the second one in a subshell.
If you get the .idb
recreated again after you delete it, then read this answer.
This how it worked with me. I had the .idb
file without it's corresponding .frm
and whenever I delete the .idb
file, the database recreate it again. and I found the solution in one line in MySQL documentation (Tablespace Does Not Exist part)
1- Create a matching .frm file in some other database directory and copy it to the database directory where the orphan table is located.
2- Issue DROP TABLE for the original table. That should successfully drop the table and InnoDB should print a warning to the error log that the .ibd file was missing.
I copied another table .frm
file and name it like my missing table, then make a normal drop table query and voila, it worked and the table is dropped normally!
my system is XAMPP on windows MariaDB v 10.1.8
var top = event.target.offsetTop + 'px';
Parent element top position like we are adding elemnt inside div
var rect = event.target.offsetParent;
rect.offsetTop;
Without enumerate()
:
>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]
Why would you make it VARCHAR? It doesn't vary. It's always 64 characters, which can be determined by running anything into one of the online SHA-256 calculators.
You can use the round
function to compute the value.
Yes in python as many have pointed when we compute the value of a cube root, it will give you an output with a little bit of error. To check if the value is a whole number you can use the following function:
def cube_integer(n):
if round(n**(1.0/3.0))**3 == n:
return True
return False
But remember that int(n)
is equivalent to math.floor
and because of this if you find the int(41063625**(1.0/3.0))
you will get 344 instead of 345.
So please be careful when using int
withe cube roots.
Your best bet is probably waitForCondition
and writing a javascript function that returns true when the map is loaded.
Actually, I think the "ls" may be faster. There are definitely some issues in Java dealing with getting File info. Unfortunately there is no equivalent safe method of recursive ls for Windows. (cmd.exe's DIR /S can get confused and generate errors in infinite loops)
On XP, accessing a server on the LAN, it takes me 5 seconds in Windows to get the count of the files in a folder (33,000), and the total size.
When I iterate recursively through this in Java, it takes me over 5 minutes. I started measuring the time it takes to do file.length(), file.lastModified(), and file.toURI() and what I found is that 99% of my time is taken by those 3 calls. The 3 calls I actually need to do...
The difference for 1000 files is 15ms local versus 1800ms on server. The server path scanning in Java is ridiculously slow. If the native OS can be fast at scanning that same folder, why can't Java?
As a more complete test, I used WineMerge on XP to compare the modified date, and size of the files on the server versus the files locally. This was iterating over the entire directory tree of 33,000 files in each folder. Total time, 7 seconds. java: over 5 minutes.
So the original statement and question from the OP is true, and valid. Its less noticeable when dealing with a local file system. Doing a local compare of the folder with 33,000 items takes 3 seconds in WinMerge, and takes 32 seconds locally in Java. So again, java versus native is a 10x slowdown in these rudimentary tests.
Java 1.6.0_22 (latest), Gigabit LAN, and network connections, ping is less than 1ms (both in the same switch)
Java is slow.
Here is what I find works
form name
Use a default select option
, for example...
<option value="-1" selected>Please Select</option>
So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.
This input
<input type="submit">
should be
<input name="Submit" type="submit" value="Submit">
whenever I use a form that fails, it is a failure due to the difference in calling the button name submit
and name as Submit
.
You should also set your enctype attribute for your form as forms fail on my web host if it's not set.
I know this question assumes just a Collection
, and not more specifically any List
. But for those reading this question who are indeed working with a List
reference, you can avoid ConcurrentModificationException
with a while
-loop (while modifying within it) instead if you want to avoid Iterator
(either if you want to avoid it in general, or avoid it specifically to achieve a looping order different from start-to-end stopping at each element [which I believe is the only order Iterator
itself can do]):
*Update: See comments below that clarify the analogous is also achievable with the traditional-for-loop.
final List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; ++i){
list.add(i);
}
int i = 1;
while(i < list.size()){
if(list.get(i) % 2 == 0){
list.remove(i++);
} else {
i += 2;
}
}
No ConcurrentModificationException from that code.
There we see looping not start at the beginning, and not stop at every element (which I believe Iterator
itself can't do).
FWIW we also see get
being called on list
, which could not be done if its reference was just Collection
(instead of the more specific List
-type of Collection
) - List
interface includes get
, but Collection
interface does not. If not for that difference, then the list
reference could instead be a Collection
[and therefore technically this Answer would then be a direct Answer, instead of a tangential Answer].
FWIWW same code still works after modified to start at beginning at stop at every element (just like Iterator
order):
final List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; ++i){
list.add(i);
}
int i = 0;
while(i < list.size()){
if(list.get(i) % 2 == 0){
list.remove(i);
} else {
++i;
}
}
Use next
:
(1..10).each do |a|
next if a.even?
puts a
end
prints:
1
3
5
7
9
For additional coolness check out also redo
and retry
.
Works also for friends like times
, upto
, downto
, each_with_index
, select
, map
and other iterators (and more generally blocks).
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.
By calling fork() you've created a child process. If the fork is successful (fork returned a non-zero PID) execution will continue from this point from within the child process. In this case we want to gracefully exit the parent process and then continue our work in the child process.
Maybe this will help: http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html
Yes, you have to copy all 387 constructors. You can do some reuse by redirecting them:
public Bar(int i): base(i) {}
public Bar(int i, int j) : base(i, j) {}
but that's the best you can do.
I had this problem and after check my code line by line i saw this
<textarea class="form-control" type="text" ng-model="WallDesc" placeholder="Enter Your Description"/>
i just changed it to
<textarea class="form-control" type="text" ng-model="WallDesc" placeholder="Enter Your Description"></textarea>
and it's worked. so check your tags.
This is answered in the comments; package-lock.json
is a feature in npm
v5 and higher. npm shrinkwrap
is how you create a lockfile in all versions of npm
.
Below steps worked out successfully.
1) In the dynamic library install name had to be "@loader_path"
2) In main project the Runpath Search Path has to be "@loader_path" and "@loader_path/Frameworks"
3) From keychain used view-->show expired certificates and removed everything.
4) Deleted the Distribution certificate and reinstalled.
5) Downloaded developer.apple.com/certificationauthority/AppleWWDRCA.cer and installed.
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>
It is the directory from where you start the batch file. E.g. if your batch is in c:\dir1\dir2
and you do cd c:\dir3
, then run the batch, the current directory will be c:\dir3
.