length of string ==how many bits that string having, size==size of those bits, In strings both are same if the editor allocates size of character is 1 byte
You can do this by setting a style in your paragraph tag. For example if you wanted to change the font size to 28px.
<p style="font-size: 28px;"> Hello, World! </p>
You can also set the color by setting:
<p style="color: blue;"> Hello, World! </p>
However, if you want to preview font sizes and colors (which I recommend doing) before you add them to your website and use them. I recommend testing them out beforehand so you pick a good font size and color that contrasts well with the background. I recommend using this site if you wish to do so, couldn't find anything else: http://fontpreview.herokuapp.com/
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
I had an excel file 24MB in Size, thanks to over a 100 images within. I reduced the size to less than 5MB by the following steps:
It took me 2 days to figure this out as this wasnt listed in any help forum. Hope this response helps someone
BR Gautam Dalal (India)
Using openCV and numpy it is as easy as this:
import cv2
img = cv2.imread('path/to/img',0)
height, width = img.shape[:2]
Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List<Float> unindexedVectors = new ArrayList<Float>();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);
Minimal settings to prevent resize events
form1.FormBorderStyle = FormBorderStyle.FixedDialog;
form1.MaximizeBox = false;
You cannot load images directly with @2x
or @3x
, system selects appropriate image automatically, just specify the name using UIImage
:
UIImage(named: "green-square-Retina")
Here is the code for you`r class . but this also contains lot of refactoring. Please add a for each rather than for. cheers :)
static int isLeft(ArrayList<String> left, ArrayList<String> right)
{
int f = 0;
for (int i = 0; i < left.size(); i++) {
for (int j = 0; j < right.size(); j++)
{
if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
System.out.println("Grammar is left recursive");
f = 1;
}
}
}
return f;
}
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter no of prod");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("enter left prod");
String leftText = sc.next();
left.add(leftText);
System.out.println("enter right prod");
String rightText = sc.next();
right.add(rightText);
}
System.out.println("the productions are");
for (int i = 0; i < n; i++) {
System.out.println(left.get(i) + "->" + right.get(i));
}
int flag;
flag = isLeft(left, right);
if (flag == 1) {
System.out.println("Removing left recursion");
} else {
System.out.println("No left recursion");
}
}
Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:
JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper);
//displayPanel.add(titleText);
To achieve this feat, define a outer linear layout with a weightSum={amount of weight to distribute}
.
it defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.Another example would be set weightSum=2, and if the two children set layout_weight=1
then each would get 50% of the available space.
WeightSum is dependent on the amount of children in the parent layout.
This worked for me:
export _JAVA_OPTIONS="-Xmx1g"
It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:
java -XshowSettings:vm
and it will tell you:
Picked up _JAVA_OPTIONS: -Xmx1g
Add this to the your code:
import pyspark
def spark_shape(self):
return (self.count(), len(self.columns))
pyspark.sql.dataframe.DataFrame.shape = spark_shape
Then you can do
>>> df.shape()
(10000, 10)
But just remind you that .count()
can be very slow for very large table that has not been persisted.
private void HandleResizeArray()
{
int[] aa = new int[2];
aa[0] = 0;
aa[1] = 1;
aa = MyResizeArray(aa);
aa = MyResizeArray(aa);
}
private int[] MyResizeArray(int[] aa)
{
Array.Resize(ref aa, aa.GetUpperBound(0) + 2);
aa[aa.GetUpperBound(0)] = aa.GetUpperBound(0);
return aa;
}
Based on @dzimney answer and similar to @Crisman answer (but different)
That answer is good but has indention problem (bullets appear inside of li
scope). Probably you don't want this. See simple example list below (this is a default HTML list):
Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.
Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.
But if you use the mentioned answer the list will be like below (ignoring the size of the bullets):
• Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.
• Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.
So I recommend this approach that resolves the issue:
li {_x000D_
list-style-type: none;_x000D_
position: relative; /* It's needed for setting position to absolute in the next rule. */_x000D_
}_x000D_
_x000D_
li::before {_x000D_
content: '¦';_x000D_
position: absolute;_x000D_
left: -0.8em; /* Adjust this value so that it appears where you want. */_x000D_
font-size: 1.1em; /* Adjust this value so that it appears what size you want. */_x000D_
}
_x000D_
<ul>_x000D_
<li>Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.</li>_x000D_
<li>Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.</li>_x000D_
</ul>
_x000D_
If you want to call a different size for the button inline, you would probably do it like this:
<div class="button" style="width:60px;height:100px;">This is a button</div>
Or, a better way to have different sizes (say there will be 3 standard sizes for the button) would be to have classes just for size.
For example, you would call your button like this:
<div class="button small">This is a button</div>
And in your CSS
.button.small { width: 60px; height: 100px; }
and just create classes for each size you wish to have. That way you still have the perks of using a stylesheet in case say, you want to change the size of all the small buttons at once.
You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.
Simply adding the following line of code should fix your problems:
mainFrame.setLayout(new BorderLayout());
(Do this before adding components to the JFrame)
you also need to identify the columns to set dimensions:
foreach (range('A', $phpExcelObject->getActiveSheet()->getHighestDataColumn()) as $col) {
$phpExcelObject
->getActiveSheet()
->getColumnDimension($col)
->setAutoSize(true);
}
You should read Supporting multiple screens. You must define dpi on your emulator. 240 is hdpi, 160 is mdpi and below that are usually ldpi.
Extract from Android Developer Guide link above:
320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
Yes numpy has a size function, and shape and size are not quite the same.
Input
import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)
print(data)
print(arrData.size)
print(arrData.shape)
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
8 # size
(2, 4) # shape
1. Response to the main question
The script $(window).height()
does work well (showing the viewport's height and not the document with scrolling height), BUT it needs that you put correctly the doctype tag in your document, for example these doctypes:
For HTML 5:
<!DOCTYPE html>
For transitional HTML4:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Probably the default doctype assumed by some browsers is such, that $(window).height()
takes the document's height and not the browser's height. With the doctype specification, it's satisfactorily solved, and I'm pretty sure you peps will avoid the "changing scroll-overflow to hidden and then back", which is, I'm sorry, a bit dirty trick, specially if you don't document it on the code for future programmer's usage.
2. An ADDITIONAL tip, note aside: Moreover, if you are doing a script, you can invent tests to help programmers in using your libraries, let me invent a couple:
$(document).ready(function() {
if(typeof $=='undefined') {
alert("PROGRAMMER'S Error: you haven't called JQuery library");
} else if (typeof $.ui=='undefined') {
alert("PROGRAMMER'S Error: you haven't installed the UI Jquery library");
}
if(document.doctype==null || screen.height < parseInt($(window).height()) ) {
alert("ERROR, check your doctype, the calculated heights are not what you might expect");
}
});
EDIT: about the part 2, "An ADDITIONAL tip, note aside": @Machiel, in yesterday's comment (2014-09-04), was UTTERLY right: the check of the $ can not be inside the ready event of Jquery, because we are, as he pointed out, assuming $ is already defined. THANKS FOR POINTING THAT OUT, and do please the rest of you readers correct this, if you used it in your scripts. My suggestion is: in your libraries put an "install_script()" function which initializes the library (put any reference to $ inside such init function, including the declaration of ready()) and AT THE BEGINNING of such "install_script()" function, check if the $ is defined, but make everything independent of JQuery, so your library can "diagnose itself" when JQuery is not yet defined. I prefer this method rather than forcing the automatic creation of a JQuery bringing it from a CDN. Those are tiny notes aside for helping out other programmers. I think that people who make libraries must be richer in the feedback to potential programmer's mistakes. For example, Google Apis need an aside manual to understand the error messages. That's absurd, to need external documentation for some tiny mistakes that don't need you to go and search a manual or a specification. The library must be SELF-DOCUMENTED. I write code even taking care of the mistakes I might commit even six months from now, and it still tries to be a clean and not-repetitive code, already-written-to-prevent-future-developer-mistakes.
The recommended way to create random integers with NumPy these days is to use numpy.random.Generator.integers
. (documentation)
import numpy as np
import pandas as pd
rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))
df
----------------------
A B C D
0 58 96 82 24
1 21 3 35 36
2 67 79 22 78
3 81 65 77 94
4 73 6 70 96
... ... ... ... ...
95 76 32 28 51
96 33 68 54 77
97 76 43 57 43
98 34 64 12 57
99 81 77 32 50
100 rows × 4 columns
You can use os.stat(path)
call
if you have
<span class="label label-default">New</span>
just add the style="font-size:XXpx;", ej.
<span class="label label-default" style="font-size:15px;">New</span>
From http://msdn.microsoft.com/en-us/library/ms176089.aspx
varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.
1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.
The Range object has both width and height properties, which are measured in points.
First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
find . -size +10000k -exec ls -sd {} +
If your version of find
won't accept the +
notation (which acts rather like xargs
does), then you might use (GNU find
and xargs
, so find
probably supports +
anyway):
find . -size +10000k -print0 | xargs -0 ls -sd
or you might replace the +
with \;
(and live with the relative inefficiency of this), or you might live with problems caused by spaces in names and use the portable:
find . -size +10000k -print | xargs ls -sd
The -d
on the ls
commands ensures that if a directory is ever found (unlikely, but...), then the directory information will be printed, not the files in the directory. And, if you're looking for files more than 1 MB (as a now-deleted comment suggested), you need to adjust the +10000k
to 1000k
or maybe +1024k
, or +2048
(for 512-byte blocks, the default unit for -size
). This will list the size and then the file name. You could avoid the need for -d
by adding -type f
to the find
command, of course.
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
If you know that your InputStream
is a FileInputStream
or a ByteArrayInputStream
, you can use a little reflection to get at the stream size without reading the entire contents. Here's an example method:
static long getInputLength(InputStream inputStream) {
try {
if (inputStream instanceof FilterInputStream) {
FilterInputStream filtered = (FilterInputStream)inputStream;
Field field = FilterInputStream.class.getDeclaredField("in");
field.setAccessible(true);
InputStream internal = (InputStream) field.get(filtered);
return getInputLength(internal);
} else if (inputStream instanceof ByteArrayInputStream) {
ByteArrayInputStream wrapper = (ByteArrayInputStream)inputStream;
Field field = ByteArrayInputStream.class.getDeclaredField("buf");
field.setAccessible(true);
byte[] buffer = (byte[])field.get(wrapper);
return buffer.length;
} else if (inputStream instanceof FileInputStream) {
FileInputStream fileStream = (FileInputStream)inputStream;
return fileStream.getChannel().size();
}
} catch (NoSuchFieldException | IllegalAccessException | IOException exception) {
// Ignore all errors and just return -1.
}
return -1;
}
This could be extended to support additional input streams, I am sure.
The guarantees the standard gives you go like this:
1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)
So it's perfectly valid for sizeof (int)
and sizeof (long)
to be equal, and many platforms choose to go with this approach. You will find some platforms where int
is 32 bits, long
is 64 bits, and long long
is 128 bits, but it seems very common for sizeof (long)
to be 4.
(Note that long long
is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.)
It would depend on the implementation, but the limit is not defined by the List
interface.
The interface however defines the size()
method, which returns an int
.
Returns the number of elements in this list. If this list contains more than
Integer.MAX_VALUE
elements, returnsInteger.MAX_VALUE
.
So, no limit, but after you reach Integer.MAX_VALUE
, the behaviour of the list changes a bit
ArrayList
(which is tagged) is backed by an array, and is limited to the size of the array - i.e. Integer.MAX_VALUE
Sure it is OK. Actually you can see for yourself easily:
l = range(12000)
l = sorted(l, reverse=True)
Running the those lines on my machine took:
real 0m0.036s
user 0m0.024s
sys 0m0.004s
But sure as everyone else said. The larger the array the slower the operations will be.
This is how I did it.
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SAP Multiple Entries");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(10,10,10,10));
frame.setLayout(new FlowLayout());
frame.setSize(512, 512);
JButton button = new JButton("Select File");
button.setPreferredSize(new Dimension(256, 256));
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
keep = selectedFile.getAbsolutePath();
// System.out.println(keep);
//out.println(file.flag);
if(file.flag==true) {
JOptionPane.showMessageDialog(null, "It is done! \nLocation: " + file.path , "Success Message", JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null, "failure", "not okay", JOptionPane.INFORMATION_MESSAGE);
}
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
The answer from Lauri Oherd works well for most strings seen in the wild, but will fail if the string contains lone characters in the surrogate pair range, 0xD800 to 0xDFFF. E.g.
byteCount(String.fromCharCode(55555))
// URIError: URI malformed
This longer function should handle all strings:
function bytes (str) {
var bytes=0, len=str.length, codePoint, next, i;
for (i=0; i < len; i++) {
codePoint = str.charCodeAt(i);
// Lone surrogates cannot be passed to encodeURI
if (codePoint >= 0xD800 && codePoint < 0xE000) {
if (codePoint < 0xDC00 && i + 1 < len) {
next = str.charCodeAt(i + 1);
if (next >= 0xDC00 && next < 0xE000) {
bytes += 4;
i++;
continue;
}
}
}
bytes += (codePoint < 0x80 ? 1 : (codePoint < 0x800 ? 2 : 3));
}
return bytes;
}
E.g.
bytes(String.fromCharCode(55555))
// 3
It will correctly calculate the size for strings containing surrogate pairs:
bytes(String.fromCharCode(55555, 57000))
// 4 (not 6)
The results can be compared with Node's built-in function Buffer.byteLength
:
Buffer.byteLength(String.fromCharCode(55555), 'utf8')
// 3
Buffer.byteLength(String.fromCharCode(55555, 57000), 'utf8')
// 4 (not 6)
yourArray.Length
:)
You can set an individual font size for the legend by adjusting the prop
keyword.
plot.legend(loc=2, prop={'size': 6})
This takes a dictionary of keywords corresponding to matplotlib.font_manager.FontProperties
properties. See the documentation for legend:
Keyword arguments:
prop: [ None | FontProperties | dict ] A matplotlib.font_manager.FontProperties instance. If prop is a dictionary, a new instance will be created with prop. If None, use rc settings.
It is also possible, as of version 1.2.1, to use the keyword fontsize
.
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
Try this, its working in FF
body,
input,
select,
button {
font-family: Arial,Helvetica,sans-serif;
font-size: 14px;
}
This code is worked for me without setAutoResizeModes.
TableColumnModel columnModel = jTable1.getColumnModel();
columnModel.getColumn(1).setPreferredWidth(170);
columnModel.getColumn(1).setMaxWidth(170);
columnModel.getColumn(2).setPreferredWidth(150);
columnModel.getColumn(2).setMaxWidth(150);
columnModel.getColumn(3).setPreferredWidth(40);
columnModel.getColumn(3).setMaxWidth(40);
Why not just use this?
var interopHelper = new WindowInteropHelper(System.Windows.Application.Current.MainWindow);
var activeScreen = Screen.FromHandle(interopHelper.Handle);
Of course there is! Win CMD can do a lot more than just split text files :)
Split a text file into separate files of 'max' lines each:
Split text file (max lines each):
: Initialize
set input=file.txt
set max=10000
set /a line=1 >nul
set /a file=1 >nul
set out=!file!_%input%
set /a max+=1 >nul
echo Number of lines in %input%:
find /c /v "" < %input%
: Split file
for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (
if !line!==%max% (
set /a line=1 >nul
set /a file+=1 >nul
set out=!file!_%input%
echo Writing file: !out!
)
REM Write next file
set a=%i
set a=!a:*]=]!
echo:!a:~1!>>out!
set /a line+=1 >nul
)
If above code hangs or crashes, this example code splits files faster (by writing data to intermediate files instead of keeping everything in memory):
eg. To split a file with 7,600 lines into smaller files of maximum 3000 lines.
set
command to be fed to /g
flag of findstr
list1.txt
\[[0-9]\]
\[[0-9][0-9]\]
\[[0-9][0-9][0-9]\]
\[[0-2][0-9][0-9][0-9]\]
list2.txt
\[[3-5][0-9][0-9][0-9]\]
list3.txt
\[[6-9][0-9][0-9][0-9]\]
type "%input%" | find /v /n "" | findstr /b /r /g:list1.txt > file1.txt type "%input%" | find /v /n "" | findstr /b /r /g:list2.txt > file2.txt type "%input%" | find /v /n "" | findstr /b /r /g:list3.txt > file3.txt
for /f "tokens=* delims=[" %i in ('type "%cd%\file1.txt"') do ( set a=%i set a=!a:*]=]! echo:!a:~1!>>file_1.txt)
Notes:
Works with leading whitespace, blank lines & whitespace lines.
Tested on Win 10 x64 CMD, on 4.4GB text file, 5651982 lines.
if you want to find it in MB do this
SELECT table_schema "DB Name",
Round(Sum(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB"
FROM information_schema.tables
GROUP BY table_schema;
.. I found the above solutions didn't work for me (on current versions of firefox and safari at least).
In my case I'm actually trying to do it with an img tag, not background-image, though it should also work for background-image if you use z-height:
<img src='$url' style='position:absolute; top,left:0px; width,max-height:100%; border:0;' >
This scales the image to be 'fullscreen' (probably breaking the aspect ratio) which was what I wanted to do but had a hard-time finding.
It may also work for background-image though I gave up on trying that kind of solution after cover/contain didn't work for me.
I found contain behaviour didn't seem to match the documentation I could find anywhere - I understood the documentation to say contain should make the largest dimension get contained within the screen (maintained aspect). I found contain always made my image tiny (original image was large).
Contain was with some hacks closer to what I wanted than cover, which seems to be that the aspect is maintained but image is scaled to make the smallest-dimension match the screen - i.e. always make the image as big as it can until one of the dimensions would go offscreen...
I tried a bunch of different things, starting over included, but found height was essentially always ignored and would overflow. (I've been trying to scale a non-widescreen image to be fullscreen on both, broken-aspect is ok for me). Basically, the above is what worked for me, hope it helps someone.
display
settingIt is of course possible - JSFiddle proof of concept where you can see all three possible solutions:
display: inline-block
- this is the one you're not aware of
position: absolute
float: left/right
Array's has
array.length
whereas List has
list.size()
Replace array.size()
to array.length
JLabel label = new JLabel("Hello World");
label.setFont(new Font("Calibri", Font.BOLD, 20));
Many of the solutions found here have some limitation: some not working in IE ( object-fit) or older browsers, other solutions do not scale up the images (only shrink it), many solution do not support resize of the window and many are not generic, either expect fix resolution or layout(portrait or landscape)
If using javascript and jquery is not a problem I have this solution based on the code of @Tatu Ulmanen. I fixed some issues, and added some code in case the image is loaded dinamically and not available at begining. Basically the idea is to have two different css rules and apply them when required: one when the limitation is the height, so we need to show black bars at the sides, and othe css rule when the limitation is the width, so we need to show black bars at the top/bottom.
function applyResizeCSS(){
var $i = $('img#imageToResize');
var $c = $i.parent();
var i_ar = Oriwidth / Oriheight, c_ar = $c.width() / $c.height();
if(i_ar > c_ar){
$i.css( "width","100%");
$i.css( "height","auto");
}else{
$i.css( "height","100%");
$i.css( "width","auto");
}
}
var Oriwidth,Oriheight;
$(function() {
$(window).resize(function() {
applyResizeCSS();
});
$("#slide").load(function(){
Oriwidth = this.width,
Oriheight = this.height;
applyResizeCSS();
});
$(window).resize();
});
For an HTML element like:
<img src="images/loading.gif" name="imageToResize" id="imageToResize"/>
Note: This doesn't apply to Angular 6 and above as ElementRef
became ElementRef<T>
with T
denoting the type of nativeElement
.
I would like to add that if you are using ElementRef
, as recommended by all answers, then you will immediately encounter the problem that ElementRef
has an awful type declaration that looks like
export declare class ElementRef {
nativeElement: any;
}
this is stupid in a browser environment where nativeElement is an HTMLElement
.
To workaround this you can use the following technique
import {Inject, ElementRef as ErrorProneElementRef} from '@angular/core';
interface ElementRef {
nativeElement: HTMLElement;
}
@Component({...}) export class MyComponent {
constructor(@Inject(ErrorProneElementRef) readonly elementRef: ElementRef) { }
}
Go to the Declaration of the desired object and mark it Shared.
Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX
Hope this helps somebody!
<style> html { scroll-behavior: smooth;} </style>
<a id="top"></>
<!--content here-->
<a href="#top">Back to top..</a>
Try using different quotes for "y" as the identifier quote character is the backtick (“`”). Otherwise MySQL "thinks" that you point to a column named "y".
See also MySQL 5 Documentation
I had an embarrassing problem...
I got this error because I was rushing and forgot to put the app in INSTALLED_APPS
. You would think Django would raise a more descriptive error.
Here one check is required that the url going to be open is able to open by device or simulator or not. Because some times (majority in simulator) i found it causes crashes.
Objective-C
NSURL *url = [NSURL URLWithString:@"some url"];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
Swift 2.0
let url : NSURL = NSURL(string: "some url")!
if UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
}
Swift 4.2
guard let url = URL(string: "some url") else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
I would suggest in taking a look into JWE using special algorithms which is not present in jwt.io to decrypt
Reference link: https://www.npmjs.com/package/node-webtokens
jwt.generate('PBES2-HS512+A256KW', 'A256GCM', payload, pwd, (error, token) => {
jwt.parse(token).verify(pwd, (error, parsedToken) => {
// other statements
});
});
This answer may be too late or you might have already found out the way, but still, I felt it would be helpful for you and others as well.
A simple example which I have created: https://github.com/hansiemithun/jwe-example
actually, your answer is not complete as the values also depend on the wrapping container. In case of relative or linear layouts, the values behave like this:
In case of an horizontal scroll view, your code will work.
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:textColor="@color/black"
android:textColorHint="@color/grey"/>
</android.support.design.widget.TextInputLayout>
Use textColorHint to set the color that you want as the Hint color for the EditText. The thing is that Hint in the EditText disappears not when you type something, but immediately when the EditText gets focus (with a cool animation). You will notice this clearly when you switch focus away and to the EditText.
As a best practice, especially if you have multiple date pickers, you should not hardcode the element's scope variable name.
Instead, you should get the clicked input's ng-model
and update its corresponding scope variable inside the onSelect
method.
app.directive('jqdatepicker', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
$(element).datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(date) {
var ngModelName = this.attributes['ng-model'].value;
// if value for the specified ngModel is a property of
// another object on the scope
if (ngModelName.indexOf(".") != -1) {
var objAttributes = ngModelName.split(".");
var lastAttribute = objAttributes.pop();
var partialObjString = objAttributes.join(".");
var partialObj = eval("scope." + partialObjString);
partialObj[lastAttribute] = date;
}
// if value for the specified ngModel is directly on the scope
else {
scope[ngModelName] = date;
}
scope.$apply();
}
});
}
};
});
EDIT
To address the issue that @Romain raised up (Nested Elements), I have modified my answer
You can also try this:
CREATE function [dbo].[fn_FormatPhone](@Phone varchar(30))
returns varchar(30)
As
Begin
declare @FormattedPhone varchar(30)
set @Phone = replace(@Phone, '.', '-') --alot of entries use periods instead of dashes
set @FormattedPhone =
Case
When isNumeric(@Phone) = 1 Then
case
when len(@Phone) = 10 then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 4, 3)+ '-' +substring(@Phone, 7, 4)
when len(@Phone) = 7 then substring(@Phone, 1, 3)+ '-' +substring(@Phone, 4, 4)
else @Phone
end
When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 8, 4)
When @phone like '[0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
Else @Phone
End
return @FormattedPhone
end
use on it select
(SELECT [dbo].[fn_FormatPhone](f.coffphone)) as 'Phone'
Output will be
Make the radio component as dumb component and pass props to from parent.
import React from "react";
const Radiocomponent = ({ value, setGender }) => (
<div onChange={setGender.bind(this)}>
<input type="radio" value="MALE" name="gender" defaultChecked={value ==="MALE"} /> Male
<input type="radio" value="FEMALE" name="gender" defaultChecked={value ==="FEMALE"}/> Female
</div>
);
export default Radiocomponent;
Better solution, as str.split("\n") function creates new array of strings split by "\n" which is heavier than str.match(/\n\g). str.match(/\n\g) creates array of matching elements only. Which is "\n" in our case.
var totalLines = (str.match(/\n/g) || '').length + 1;
I also needed this once, and I did a check on the window title of the process. If it is the one you expect, you can be sure the application is running. The application I was checking needed some time for startup and this method worked fine for me.
var process = Process.Start("popup.exe");
while(process.MainWindowTitle != "Title")
{
Thread.Sleep(10);
}
I think your issue is the line:**
sp.DataReceived += port_OnReceiveDatazz;
Shouldn't it be:
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).
I've also seen suggestions that you should turn the following options on for your serial port:
sp.DtrEnable = true; // Data-terminal-ready
sp.RtsEnable = true; // Request-to-send
You may also have to set the handshake to RequestToSend (via the handshake enumeration).
UPDATE:
Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?
So instead of this:
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();
Do this:
sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
Let me know how that goes.
Do you have an idea about the expected output? For example, will this do?
>>> f = FileItem("/foo/bar")
>>> magic(f)
'{"fname": "/foo/bar"}'
In that case you can merely call json.dumps(f.__dict__)
.
If you want more customized output then you will have to subclass JSONEncoder
and implement your own custom serialization.
For a trivial example, see below.
>>> from json import JSONEncoder
>>> class MyEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
>>> MyEncoder().encode(f)
'{"fname": "/foo/bar"}'
Then you pass this class into the json.dumps()
method as cls
kwarg:
json.dumps(cls=MyEncoder)
If you also want to decode then you'll have to supply a custom object_hook
to the JSONDecoder
class. For example:
>>> def from_json(json_object):
if 'fname' in json_object:
return FileItem(json_object['fname'])
>>> f = JSONDecoder(object_hook = from_json).decode('{"fname": "/foo/bar"}')
>>> f
<__main__.FileItem object at 0x9337fac>
>>>
Even though OutputDebugString
indeed prints a string of characters to the debugger console, it's not exactly like printf
with regard to the latter being able to format arguments using the %
notation and a variable number of arguments, something OutputDebugString
does not do.
I would make the case that the _RPTFN
macro, with _CRT_WARN
argument at least, is a better suitor in this case -- it formats the principal string much like printf
, writing the result to debugger console.
A minor (and strange, in my opinion) caveat with it is that it requires at least one argument following the format string (the one with all the %
for substitution), a limitation printf
does not suffer from.
For cases where you need a puts
like functionality -- no formatting, just writing the string as-is -- there is its sibling _RPTF0
(which ignores arguments following the format string, another strange caveat). Or OutputDebugString
of course.
And by the way, there is also everything from _RPT1
to _RPT5
but I haven't tried them. Honestly, I don't understand why provide so many procedures all doing essentially the same thing.
using System;
using System.IO;
// Get the current directory and make it a DirectoryInfo object.
// Do not use Environment.CurrentDirectory, vistual studio
// and visual studio code will return different result:
// Visual studio will return @"projectDir\bin\Release\netcoreapp2.0\", yet
// vs code will return @"projectDir\"
var currentDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
// On windows, the current directory is the compiled binary sits,
// so string like @"bin\Release\netcoreapp2.0\" will follow the project directory.
// Hense, the project directory is the great grand-father of the current directory.
string projectDirectory = currentDirectory.Parent.Parent.Parent.FullName;
public static String ecapse(String jsString) {
jsString = jsString.replace("\\", "\\\\");
jsString = jsString.replace("\"", "\\\"");
jsString = jsString.replace("\b", "\\b");
jsString = jsString.replace("\f", "\\f");
jsString = jsString.replace("\n", "\\n");
jsString = jsString.replace("\r", "\\r");
jsString = jsString.replace("\t", "\\t");
jsString = jsString.replace("/", "\\/");
return jsString;
}
Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,
+----------+
| _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|
I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.
df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")
Here I'm creating a temporary view and store the year values using this single line and the output will be,
+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
| 1872|
| 1873|
| 1874|
| 1875|
| 1876|
| 1876|
| 1877|
| 1877|
| 1878|
| 1878|
| 1879|
| 1879|
| 1879|
Yes, it is. Declare parameter as so:
@Sort varchar(50) = NULL
Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).
This works well for specific articles where the text is all wrapped in <p>
tags. Since the web is an ugly place, it's not always the case.
Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span>
or a <div>
, or an <li>
).
To find all text nodes in the DOM, you can use soup.find_all(text=True)
.
This is going to return some undesired text, like the contents of <script>
and <style>
tags. You'll need to filter out the text contents of elements you don't want.
blacklist = [
'style',
'script',
# other elements,
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]
If you are working with a known set of tags, you can tag the opposite approach:
whitelist = [
'p'
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]
Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.
The android documents have been edited to correct the errors.
The view inside the AlertDialog is called android.R.id.custom
http://developer.android.com/reference/android/app/AlertDialog.html
ORA-03113: end-of-file on communication channel
Is the database letting you know that the network connection is no more. This could be because:
For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME
. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.
For 1) (network) speak to your network admin (connection could be unreliable)
For 2) Check the alert.log
for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.
Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)
var pause_menu = {
pause_button : { someProperty : "prop1", someOther : "prop2" },
resume_button : { resumeProp : "prop", resumeProp2 : false },
quit_button : false
};
then:
pause_menu.pause_button.someProperty //evaluates to "prop1"
etc etc.
I haven't tried implementing a FSM in C# yet, but these all sound (or look) very complicated to the way I handled FSM's in the past in low-level languages like C or ASM.
I believe the method I've always known is called something like an "Iterative Loop". In it, you essentially have a 'while' loop that periodically exits based on events (interrupts), then returns to the main loop again.
Within the interrupt handlers, you would pass a CurrentState and return a NextState, which then overwrites the CurrentState variable in the main loop. You do this ad infinitum until the program closes (or the microcontroller resets).
What I'm seeing other answers all look very complicated compared with how a FSM is, in my mind, intended to be implemented; its beauty lies in its simplicity and FSM can be very complicated with many, many states and transitions, but they allow complicated process to be easily broken down and digested.
I realize my response shouldn't include another question, but I am forced to ask: why do these other proposed solutions appear to be so complicated?
They seem to be akin to hitting a small nail with a giant sledge hammer.
The clue is in the error message - if you look at the documentation for json_decode
note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.
So change your call to
$json = json_decode(file_get_contents($file), true);
And it'll return an associative array and your code should work fine.
The code example is exactly this:
from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
You'll need to create book1.xls to test, but you get the idea.
Create a listview item
ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")
You can get the parameters you are asking for by typing:
dir /?
For the full list, try:
dir /s /b /a:d
Try the sp_foreachdb procedure.
String str = (String)Class.forName("java.lang.String").newInstance();
I found three fixes:
This:
var bootstrapButton = $.fn.button.noConflict();
$.fn.bootstrapBtn = bootstrapButton;
helps. But other buttons look terrible. And now we don't have bootstrap buttons.
I just want to use bootsrap styles and also I want to have close button with an icon. I've done following:
How close button looks after fix
.ui-dialog-titlebar-close {
padding:0 !important;
}
.ui-dialog-titlebar-close:after {
content: '';
width: 20px;
height: 20px;
display: inline-block;
/* Change path to image*/
background-image: url(themes/base/images/ui-icons_777777_256x240.png);
background-position: -96px -128px;
background-repeat: no-repeat;
}
You can't, you'll have to do something like
<script type="text/javascript">
var php_var = "<?php echo $php_var; ?>";
</script>
You can also load it with AJAX
rhino is right, the snippet lacks of a type for the sake of brevity.
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900
If your date is text and you need to convert it then DATEVALUE
will do this:
Note if you are on certain shared hosting sites like Dreamhost you can't disable PHP output buffering at all without going through different routes:
Changing the output buffer cache If you are using PHP FastCGI, the PHP functions flush(), ob_flush(), and ob_implicit_flush() will not function as expected. By default, output is buffered at a higher level than PHP (specifically, by the Apache module mod_deflate which is similar in form/function to mod_gzip).
If you need unbuffered output, you must either use CGI (instead of FastCGI) or contact support to request that mod_deflate is disabled for your site.
https://help.dreamhost.com/hc/en-us/articles/214202188-PHP-overview
var divss = 0;
$(function(){
$("#foo div").each(function(){
divss++;
});
console.log(divss);
});
<div id="foo">
<div id="bar" class="1"></div>
<div id="baz" class="1"></div>
<div id="bam" class="1"></div>
</div>
If you don't want the text to wrap and you don't want the size of the column to get bigger then set a width and height on the column and set "overflow: hidden" in your stylesheet.
To do this on only one column you will want to add a class to that column on each row. Otherwise you can set it on all columns, that is up to you.
Html:
<table width="300px">
<tr>
<td>Column 1</td><td>Column 2</td>
</tr>
<tr>
<td class="column-1">this is the text in column one which wraps</td>
<td>this is the column two test</td>
</tr>
</table>
stylsheet:
.column-1
{
overflow: hidden;
width: 150px;
height: 1.2ex;
}
An ex unit is the relative font size for height, if you are using pixels to set the font size you may wish to use that instead.
How about this: location.href.slice(0, - ((location.search + location.hash).length))
Try new_list = a[0:2] + [a[4]] + a[6:]
.
Or more generally, something like this:
from itertools import chain
new_list = list(chain(a[0:2], [a[4]], a[6:]))
This works with other sequences as well, and is likely to be faster.
Or you could do this:
def chain_elements_or_slices(*elements_or_slices):
new_list = []
for i in elements_or_slices:
if isinstance(i, list):
new_list.extend(i)
else:
new_list.append(i)
return new_list
new_list = chain_elements_or_slices(a[0:2], a[4], a[6:])
But beware, this would lead to problems if some of the elements in your list were themselves lists.
To solve this, either use one of the previous solutions, or replace a[4]
with a[4:5]
(or more generally a[n]
with a[n:n+1]
).
variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')
The [p]
is a neat trick to remove the search from showing from ps
@Jeremy
If you post the output of ps -ef | grep "port 10"
, and what you need from the line, it would be more easy to help you getting correct syntax
In Swift:
For example, name of your custom class is InfoView
At first, you create files InfoView.xib
and InfoView.swift
like this:
import Foundation
import UIKit
class InfoView: UIView {
class func instanceFromNib() -> UIView {
return UINib(nibName: "InfoView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}
Then set File's Owner
to UIViewController
like this:
Rename your View
to InfoView
:
Right-click to File's Owner
and connect your view
field with your InfoView
:
Make sure that class name is InfoView
:
And after this you can add the action to button in your custom class without any problem:
And usage of this custom class in your MainViewController
:
func someMethod() {
var v = InfoView.instanceFromNib()
v.frame = self.view.bounds
self.view.addSubview(v)
}
Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.
$ man memset
MEMSET(3) BSD Library Functions Manual MEMSET(3)
NAME
memset -- fill a byte string with a byte value
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
void *
memset(void *b, int c, size_t len);
Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>
/<cstdio>
/<cstdlib>
/etc, rather than C's <string.h>
/<stdio.h>
/<stdlib.h>
/etc.
Based on audiodude's answer, but simplified by using the built-in CSV library
require 'nokogiri'
require 'csv'
doc = Nokogiri::HTML(table_string)
csv = CSV.open("output.csv", 'w')
doc.xpath('//table//tr').each do |row|
tarray = [] #temporary array
row.xpath('td').each do |cell|
tarray << cell.text #Build array of that row of data.
end
csv << tarray #Write that row out to csv file
end
csv.close
I did wonder if there was any way to take the Nokogiri NodeSet (row.xpath('td')
) and write this out as an array to the csv file in one step. But I could only figure out doing it by iterating over each cell and building the temporary array of each cell's content.
Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.
What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.
http://developer.android.com/guide/topics/ui/custom-components.html
You can use .sortBy
, it will always return an ascending list:
_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
But you can use the .reverse method to get it descending:
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
Or when dealing with numbers add a negative sign to the return to descend the list:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
Under the hood .sortBy
uses the built in .sort([handler])
:
// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]
// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
Try starting the project using the python_boilerplate template. It largely follows the best practices (e.g. those here), but is better suited in case you find yourself willing to split your project into more than one egg at some point (and believe me, with anything but the simplest projects, you will. One common situation is where you have to use a locally-modified version of someone else's library).
Where do you put the source?
PROJECT_ROOT/src/<egg_name>
.Where do you put application startup scripts?
entry_point
in one of the eggs.Where do you put the IDE project cruft?
PROJECT_ROOT/.<something>
in the root of the project, and this is fine.Where do you put the unit/acceptance tests?
PROJECT_ROOT/src/<egg_name>/tests
directory. I personally prefer to use py.test
to run them.Where do you put non-Python data such as config files?
pkg_resources
package from setuptools
, or since Python 3.7 via the importlib.resources
module from the standard library.PROJECT_ROOT/config
. For deployment there can be various options. On Windows one can use %APP_DATA%/<app-name>/config
, on Linux, /etc/<app-name>
or /opt/<app-name>/config
.PROJECT_ROOT/var
during development, and under /var
during Linux deployment.PROJECT_ROOT/src/<egg_name>/native
Documentation would typically go into PROJECT_ROOT/doc
or PROJECT_ROOT/src/<egg_name>/doc
(this depends on whether you regard some of the eggs to be a separate large projects). Some additional configuration will be in files like PROJECT_ROOT/buildout.cfg
and PROJECT_ROOT/setup.cfg
.
I had the same question when I migrated to python from Matlab. With the help of this thread I was able to construct an exact analog of the Matlab tic()
and toc()
functions. Simply insert the following code at the top of your script.
import time
def TicTocGenerator():
# Generator that returns time differences
ti = 0 # initial time
tf = time.time() # final time
while True:
ti = tf
tf = time.time()
yield tf-ti # returns the time difference
TicToc = TicTocGenerator() # create an instance of the TicTocGen generator
# This will be the main function through which we define both tic() and toc()
def toc(tempBool=True):
# Prints the time difference yielded by generator instance TicToc
tempTimeInterval = next(TicToc)
if tempBool:
print( "Elapsed time: %f seconds.\n" %tempTimeInterval )
def tic():
# Records a time in TicToc, marks the beginning of a time interval
toc(False)
That's it! Now we are ready to fully use tic()
and toc()
just as in Matlab. For example
tic()
time.sleep(5)
toc() # returns "Elapsed time: 5.00 seconds."
Actually, this is more versatile than the built-in Matlab functions. Here, you could create another instance of the TicTocGenerator
to keep track of multiple operations, or just to time things differently. For instance, while timing a script, we can now time each piece of the script seperately, as well as the entire script. (I will provide a concrete example)
TicToc2 = TicTocGenerator() # create another instance of the TicTocGen generator
def toc2(tempBool=True):
# Prints the time difference yielded by generator instance TicToc2
tempTimeInterval = next(TicToc2)
if tempBool:
print( "Elapsed time 2: %f seconds.\n" %tempTimeInterval )
def tic2():
# Records a time in TicToc2, marks the beginning of a time interval
toc2(False)
Now you should be able to time two separate things: In the following example, we time the total script and parts of a script separately.
tic()
time.sleep(5)
tic2()
time.sleep(3)
toc2() # returns "Elapsed time 2: 5.00 seconds."
toc() # returns "Elapsed time: 8.00 seconds."
Actually, you do not even need to use tic()
each time. If you have a series of commands that you want to time, then you can write
tic()
time.sleep(1)
toc() # returns "Elapsed time: 1.00 seconds."
time.sleep(2)
toc() # returns "Elapsed time: 2.00 seconds."
time.sleep(3)
toc() # returns "Elapsed time: 3.00 seconds."
# and so on...
I hope that this is helpful.
Use org.apache.commons.lang.StringUtils' split method which can split strings based on the character or string you want to split.
Method signature:
public static String[] split(String str, char separatorChar);
In your case, you want to split a string when there is a "-".
You can simply do as follows:
String str = "004-034556";
String split[] = StringUtils.split(str,"-");
Output:
004
034556
Assume that if -
does not exists in your string, it returns the given string, and you will not get any exception.
For me, this error "Experimental support for decorators is a feature that is subject to change in a future release. (etc)" only happened in VS Code in an Angular project and only when creating a new Service.
The solution above: "In Visual Code Studio Go to File >> Preferences >> Settings, Search "decorator" in search field and Checking the option JavaScript › Implicit Project Config: Experimental Decorators" solved the problem.
Also, stopping the ng serve in the terminal window and restarting it made the error disappear after recompile.
double[] arr = new double[] {1.38, 2.56, 4.3};
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( new Supplier<ArrayList<Double>>() {
public ArrayList<Double> get() {
return( new ArrayList<Double>() );
}
} ) );
You can also use RedirectMatch directive to deny access to a folder.
To deny access to a folder, you can use the following RedirectMatch in htaccess :
RedirectMatch 403 ^/folder/?$
This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.
To deny access to everything inside the folder, You can use this :
RedirectMatch 403 ^/folder/.*$
This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.
Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx
Set-ExecutionPolicy RemoteSigned
Run this python script on your powershell script helloworld.py
:
# -*- coding: iso-8859-1 -*-
import subprocess, sys
p = subprocess.Popen(["powershell.exe",
"C:\\Users\\USER\\Desktop\\helloworld.ps1"],
stdout=sys.stdout)
p.communicate()
This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.
C:\Users\MacEwin\Desktop>python helloworld.py
Hello World
1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage()
and FormsAuthentication.RedirectFromLoginPage()
!
2) You should just use RedirectToAction("action", "controller") in regular scenarios..
You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception)
Use the [Authorize]
attribute on your controller or method instead :)
UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)
Response.StatusCode = 403;
Response.End();
This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)
Response.Redirect(Url.Action("action", "controller"));
No need to specify the full url. This should be enough. If you completely insist on the full url:
Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());
How about something like:
<a href="\\DangerServer\Downloads\MyVirusArchive.exe"
type="application/octet-stream">Don't download this file!</a>
# I like using the codecs opening in a with
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
logger = csv.DictWriter(logfile, fieldnames=field_names)
logger.writeheader()
# some more code stuff
for video in aList:
video_result = {}
video_result['date'] = video['snippet']['publishedAt']
video_result['user'] = video['id']
video_result['text'] = video['snippet']['description'].encode('utf8')
logger.writerow(video_result)
$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.
It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.
EDIT: I don't think I explained this well enough originally, but $resource
does some funky stuff with returns. Todo.get()
and Todo.query()
both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save()
before the get()
callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then()
or the callback method.
var Todo = $resource('/api/1/todo/:id');
//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();
//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();
//which is basically the same as...
Todo.get({id: 123}, function(todo) {
todo.foo += '!';
todo.$save();
});
//get a list of todos
Todo.query(function(todos) {
//do something with todos
angular.forEach(todos, function(todo) {
todo.foo += ' something';
todo.$save();
});
});
//delete a todo
Todo.$delete({id: 123});
Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):
var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();
I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource
, you should probably just be using $http
on it's own.
As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.
To leverage promises with $resource
, you need to use the $promise
property on the returned value.
var Todo = $resource('/api/1/todo/:id');
Todo.get({id: 123}).$promise.then(function(todo) {
// success
$scope.todos = todos;
}, function(errResponse) {
// fail
});
Todo.query().$promise.then(function(todos) {
// success
$scope.todos = todos;
}, function(errResponse) {
// fail
});
Just keep in mind that the $promise
property is a property on the same values it was returning above. So you can get weird:
var todo = Todo.get({id: 123}, function() {
$scope.todo = todo;
});
Todo.get({id: 123}, function(todo) {
$scope.todo = todo;
});
Todo.get({id: 123}).$promise.then(function(todo) {
$scope.todo = todo;
});
var todo = Todo.get({id: 123});
todo.$promise.then(function() {
$scope.todo = todo;
});
Place your scripts in this order:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
you might be referring two jquery scripts which is giving the above error.
I've found a one-liner solution on ETH Zurich Department of Physics wiki page (close to the end of that page). Just do a git gc
to remove stale junk, and then
git rev-list --objects --all \
| grep "$(git verify-pack -v .git/objects/pack/*.idx \
| sort -k 3 -n \
| tail -10 \
| awk '{print$1}')"
will give you the 10 largest files in the repository.
There's also a lazier solution now available, GitExtensions now has a plugin that does this in UI (and handles history rewrites as well).
I usually do this in the thread handling the json response:
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.
let str = "My String"
String at index
let index = str.index(str.startIndex, offsetBy: 3)
String(str[index]) // "S"
Substring
let startIndex = str.index(str.startIndex, offsetBy: 3)
let endIndex = str.index(str.startIndex, offsetBy: 7)
String(str[startIndex...endIndex]) // "Strin"
First n chars
let startIndex = str.index(str.startIndex, offsetBy: 3)
String(str[..<startIndex]) // "My "
Last n chars
let startIndex = str.index(str.startIndex, offsetBy: 3)
String(str[startIndex...]) // "String"
str = "My String"
**String At Index **
Swift 2
let charAtIndex = String(str[str.startIndex.advancedBy(3)]) // charAtIndex = "S"
Swift 3
str[str.index(str.startIndex, offsetBy: 3)]
SubString fromIndex toIndex
Swift 2
let subStr = str[str.startIndex.advancedBy(3)...str.startIndex.advancedBy(7)] // subStr = "Strin"
Swift 3
str[str.index(str.startIndex, offsetBy: 3)...str.index(str.startIndex, offsetBy: 7)]
First n chars
let first2Chars = String(str.characters.prefix(2)) // first2Chars = "My"
Last n chars
let last3Chars = String(str.characters.suffix(3)) // last3Chars = "ing"
If you want to call functions on components from outside React, you can call them on the return value of renderComponent:
var Child = React.createClass({…});
var myChild = React.renderComponent(Child);
myChild.someMethod();
The only way to get a handle to a React Component instance outside of React is by storing the return value of React.renderComponent. Source.
According to Troubleshooting Push Certificate Problems
The SSL certificate available in your Apple Developer Program account contains a public key but not a private key. The private key exists only on the Mac that created the Certificate Signing Request uploaded to Apple. Both the public and private keys are necessary to export the Privacy Enhanced Mail (PEM) file.
Chances are the reason you can't export a working PEM from the certificate provided by the client is that you do not have the private key. The certificate contains the public key, while the private key probably only exists on the Mac that created the original CSR.
You can either:
or
As we all know that IPv4 address for
localhost
is127.0.0.1
(loopback address).
Actually, any IPv4 address in 127.0.0.0/8
is a loopback address.
In IPv6, the direct analog of the loopback range is ::1/128
. So ::1
(long form 0:0:0:0:0:0:0:1
) is the one and only IPv6 loopback address.
While the hostname localhost
will normally resolve to 127.0.0.1
or ::1
, I have seen cases where someone has bound it to an IP address that is not a loopback address. This is a bit crazy ... but sometimes people do it.
I say "this is crazy" because you are liable to break applications assumptions by doing this; e.g. an application may attempt to do a reverse lookup on the loopback IP and not get the expected result. In the worst case, an application may end up sending sensitive traffic over an insecure network by accident ... though you probably need to make other mistakes as well to "achieve" that.
Blocking 0.0.0.0
makes no sense. In IPv4 it is never routed. The equivalent in IPv6 is the ::
address (long form 0:0:0:0:0:0:0:0
) ... which is also never routed.
The 0.0.0.0
and ::
addresses are reserved to mean "any address". So, for example a program that is providing a web service may bind to 0.0.0.0
port 80 to accept HTTP connections via any of the host's IPv4 addresses. These addresses are not valid as a source or destination address for an IP packet.
Finally, some comments were asking about ::/128
versus ::/0
versus ::
.
What is this difference?
Strictly speaking, the first two are CIDR notation not IPv6 addresses. They are actually specifying a range of IP addresses. A CIDR consists of a IP address and an additional number that specifies the number of bits in a netmask. The two together specify a range of addresses; i.e. the set of addresses formed by ignoring the bits masked out of the given address.
So:
::
means just the IPv6 address 0:0:0:0:0:0:0:0
::/128
means 0:0:0:0:0:0:0:0
with a netmask consisting of 128 bits. This gives a network range with exactly one address in it.::/0
means 0:0:0:0:0:0:0:0
with a netmask consisting of 0 bits. This gives a network range with 2128 addresses in it.; i.e. it is the entire IPv6 address space!For more information, read the Wikipedia pages on IPv4 & IPv6 addresses, and CIDR notation:
I got same problem. So I looked into the axios document. I found it. you can do it like this. this is easiest way. and super simple.
https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
You can use .then,.catch.
This worked for me.
I have searched a lot for a solution in which I can compare two array of objects with different attribute names (something like a left outer join). I came up with this solution. Here I used Lodash. I hope this will help you.
var Obj1 = [
{id:1, name:'Sandra'},
{id:2, name:'John'},
];
var Obj2 = [
{_id:2, name:'John'},
{_id:4, name:'Bobby'}
];
var Obj3 = lodash.differenceWith(Obj1, Obj2, function (o1, o2) {
return o1['id'] === o2['_id']
});
console.log(Obj3);
// {id:1, name:'Sandra'}
In order to build a more-or-less reliable list of applications that appear in the "Programs and Feautres" in the Control Panel, you have to consider that not all applications were installed using MSI. WMI only provides the ones installed with MSI.
Here is a short summary of what I've found out:
MSI applications always have a Product Code (GUID) subkey under HKLM\...\Uninstall
and/or under HKLM\...\Installer\UserData\S-1-5-18\Products
. In addition, they may have a key that looks like HKLM\...\Uninstall\NotAGuid
.
Non-MSI applications do not have a product code, and therefore have keys like HKLM\...\Uninstall\NotAGuid
or HKCU\...\Uninstall\NotAGuid
.
create a database schema in SQL Server 2008
1. Navigate to Security > Schemas
2. Right click on Schemas and select New Schema
3. Complete the details in the General tab for the new schema. Like, the schema name is "MySchema" and the schema owner is "Admin".
4. Add users to the schema as required and set their permissions:
5. Add any extended properties (via the Extended Properties tab)
6. Click OK.
Add a Table to the New Schema "MySchema"
1. In Object Explorer, right click on the table name and select "Design":
2. Changing database schema for a table in SQL Server Management Studio
3. From Design view, press F4 to display the Properties window.
4. From the Properties window, change the schema to the desired schema:
5. Close Design View by right clicking the tab and selecting "Close":
6. Closing Design View
7. Click "OK" when prompted to save
8. Your table has now been transferred to the "MySchema" schema.
Refresh the Object Browser view To confirm the changes
Done
The current "pipable" variant of this operator is called finalize()
(since RxJS 6). The older and now deprecated "patch" operator was called finally()
(until RxJS 5.5).
I think finalize()
operator is actually correct. You say:
do that logic only when I subscribe, and after the stream has ended
which is not a problem I think. You can have a single source
and use finalize()
before subscribing to it if you want. This way you're not required to always use finalize()
:
let source = new Observable(observer => {
observer.next(1);
observer.error('error message');
observer.next(3);
observer.complete();
}).pipe(
publish(),
);
source.pipe(
finalize(() => console.log('Finally callback')),
).subscribe(
value => console.log('#1 Next:', value),
error => console.log('#1 Error:', error),
() => console.log('#1 Complete')
);
source.subscribe(
value => console.log('#2 Next:', value),
error => console.log('#2 Error:', error),
() => console.log('#2 Complete')
);
source.connect();
This prints to console:
#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message
Jan 2019: Updated for RxJS 6
I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)
I was also using Fastlane. My fix was to set generate_apple_certs
to false
when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3
Match documentation - https://docs.fastlane.tools/actions/match/
This is the relevant section of my Fastfile:
platform :ios do
lane :certs do
force = false
match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
match(type: "adhoc", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
match(type: "appstore", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
end
...
Another approach is to use android.intent.action.USER_PRESENT
instead of android.intent.action.BOOT_COMPLETED
to avoid slow downs during the boot process. But this is only true
if the user has enabled the lock Screen - otherwise this intent is never broadcasted.
Reference blog - The Problem With Android’s ACTION_USER_PRESENT Intent
You can use np.c_
np.c_[[1,2,3], [4,5,6]]
It will give you:
np.array([[1,4], [2,5], [3,6]])
Since you seem to only have scalar values an PHP’s array is rather a hash map, you could use the value as key to avoid duplicates and associate the $k
keys to them to be able to get the original values:
$keys = array();
foreach ($array as $k => $v){
if (isset($v['key'])) {
$keys[$value] = $k;
}
}
Then you just need to iterate it to get the original values:
$unique = array();
foreach ($keys as $key) {
$unique[] = $array[$key]['key'];
}
This is probably not the most obvious and most comprehensive approach but it is very efficient as it is in O(n).
Using in_array
instead like others suggested is probably more intuitive. But you would end up with an algorithm in O(n2) (in_array
is in O(n)) that is not applicable. Even pushing all values in the array and using array_unique
on it would be better than in_array
(array_unique
sorts the values in O(n·log n) and then removes successive duplicates).
For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 4.0 / Alamofire >= 5.0
response.response?.statusCode
More verbose example:
Alamofire.request(urlString)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
var statusCode = response.response?.statusCode
if let error = response.result.error as? AFError {
statusCode = error._code // statusCode private
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
case .parameterEncodingFailed(let reason):
print("Parameter encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .multipartEncodingFailed(let reason):
print("Multipart encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .responseValidationFailed(let reason):
print("Response validation failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
switch reason {
case .dataFileNil, .dataFileReadFailed:
print("Downloaded file could not be read")
case .missingContentType(let acceptableContentTypes):
print("Content Type Missing: \(acceptableContentTypes)")
case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
case .unacceptableStatusCode(let code):
print("Response status code was unacceptable: \(code)")
statusCode = code
}
case .responseSerializationFailed(let reason):
print("Response serialization failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
// statusCode = 3840 ???? maybe..
default:break
}
print("Underlying error: \(error.underlyingError)")
} else if let error = response.result.error as? URLError {
print("URLError occurred: \(error)")
} else {
print("Unknown error: \(response.result.error)")
}
print(statusCode) // the status code
}
(Alamofire 4 contains a completely new error system, look here for details)
For Swift 2.x users with Alamofire >= 3.0
Alamofire.request(.GET, urlString)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
if let alamoError = response.result.error {
let alamoCode = alamoError.code
let statusCode = (response.response?.statusCode)!
} else { //no errors
let statusCode = (response.response?.statusCode)! //example : 200
}
}
With
def person = new Person("Kumar", 12)
you are defining a function/lazy variable which always returns a new Person instance with name "Kumar" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.
When writing
person.age = 45
you assign a new value to the age property in class Person, which is valid since age is declared as var
. The compiler will complain if you try to reassign person
with a new Person object like
person = new Person("Steve", 13) // Error
Yes. add a linked server entry, and use select into using the four part db object naming convention.
Example:
SELECT * INTO targetTable
FROM [sourceserver].[sourcedatabase].[dbo].[sourceTable]
Adding to slebetman's answer for more clarity on what happens while executing the code.
The internal thread pool in nodeJs just has 4 threads by default. and its not like the whole request is attached to a new thread from the thread pool the whole execution of request happens just like any normal request (without any blocking task) , just that whenever a request has any long running or a heavy operation like db call ,a file operation or a http request the task is queued to the internal thread pool which is provided by libuv. And as nodeJs provides 4 threads in internal thread pool by default every 5th or next concurrent request waits until a thread is free and once these operations are over the callback is pushed to the callback queue. and is picked up by event loop and sends back the response.
Now here comes another information that its not once single callback queue, there are many queues.
Whenever a request comes the code gets executing in this order of callbacks queued.
It is not like when there is a blocking request it is attached to a new thread. There are only 4 threads by default. So there is another queueing happening there.
Whenever in a code a blocking process like file read occurs , then calls a function which utilises thread from thread pool and then once the operation is done , the callback is passed to the respective queue and then executed in the order.
Everything gets queued based on the the type of callback and processed in the order mentioned above.
With the upcoming Xcode 7 it's now possible to install apps on your devices without an apple developer license, so now it is possible to skip the app store and you don't have to jailbreak your device.
Now everyone can get their app on their Apple device.
Xcode 7 and Swift now make it easier for everyone to build apps and run them directly on their Apple devices. Simply sign in with your Apple ID, and turn your idea into an app that you can touch on your iPad, iPhone, or Apple Watch. Download Xcode 7 beta and try it yourself today. Program membership is not required.
Quoted from: https://developer.apple.com/xcode/
Update:
XCode 7 is now released:
Free On-Device Development Now everyone can run and test their own app on a device—for free. You can run and debug your own creations on a Mac, iPhone, iPad, iPod touch, or Apple Watch without any fees, and no programs to join. All you need to do is enter your free Apple ID into Xcode. You can even use the same Apple ID you already use for the App Store or iTunes. Once you’ve perfected your app the Apple Developer Program can help you get it on the App Store.
See Launching Your App on Devices for detailed information about installing and running on devices.
If you are familiar with git you'll be happy to use histedit that works like git rebase -i
.
https://github.com/wongatech/angular-http-loader is a good project for this.
Example here http://wongatech.github.io/angular-http-loader/
The code below shows a template example/loader.tpl.html when a request is happening.
<div ng-http-loader template="example/loader.tpl.html"></div>
Well you just need to use document.getElementById('hello').setAttribute('class', 'someclass');
.
Also innerHTML
can lead to unexpected results! Consider the following;
var myParag = document.createElement('p');
if(under certain age)
{
myParag.text="Good Bye";
createCookie('age', 'not13', 0);
return false;
{
else
{
myParag.text="Hello";
return true;
}
document.getElementById('hello').appendChild(myParag);
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
Just Do like this
view.animate()
.translationY(-((root.height - (view.height)) / 2).toFloat())
.setInterpolator(AccelerateInterpolator()).duration = 1500
Here, view
is your View which is animating from its origin position. root
is root View of your XML file.
Calculation inside translationY
is made for moving your view to the top but keeping it inside the screen, otherwise, it will go partially outside of the screen if you keep its value 0.
The Splatting Operator
To create an array, we create a variable and assign the array. Arrays are noted by the "@" symbol. Let's take the discussion above and use an array to connect to multiple remote computers:
$strComputers = @("Server1", "Server2", "Server3")<enter>
They are used for arrays and hashes.
One way is to use a Boolean series to index the column df['one']
. This gives you a new column where the True
entries have the same value as the same row as df['one']
and the False
values are NaN
.
The Boolean series is just given by your if
statement (although it is necessary to use &
instead of and
):
>>> df['que'] = df['one'][(df['one'] >= df['two']) & (df['one'] <= df['three'])]
>>> df
one two three que
0 10 1.2 4.2 10
1 15 70 0.03 NaN
2 8 5 0 NaN
If you want the NaN
values to be replaced by other values, you can use the fillna
method on the new column que
. I've used 0
instead of the empty string here:
>>> df['que'] = df['que'].fillna(0)
>>> df
one two three que
0 10 1.2 4.2 10
1 15 70 0.03 0
2 8 5 0 0
var array = string.split(',')
and good morning, too, since I have to type 30 chars ...
Starting
start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)
Stopping
stop-dfs.sh
stop-mapred.sh
For Python 3
Remove the rb
argument and use either r
or don't pass argument (default read mode
).
with open( <path-to-file>, 'r' ) as theFile:
reader = csv.DictReader(theFile)
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
print(line)
For Python 2
import csv
with open( <path-to-file>, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
# e.g. print( line[ 'workers' ] ) yields 'w0'
Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.
No. Its not possible to add link through css. But you can use jquery
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});
Here the demo: http://jsfiddle.net/r5uWX/1/
IF they Give Path Directory Error!
In MAC Then Go to Folder Get Info and Open Storage and Permission change to privileges Read To Write
let's assume this hierarchy:
class Creature{}// X
class Animal extends Creature{}// Y
class Fish extends Animal{}// Z
class Shark extends Fish{}// A
class HammerSkark extends Shark{}// B
class DeadHammerShark extends HammerSkark{}// C
Let's clarify PE - Producer Extends:
List<? extends Shark> sharks = new ArrayList<>();
Why you cannot add objects that extend "Shark" in this list? like:
sharks.add(new HammerShark());//will result in compilation error
Since you have a list that can be of type A, B or C at runtime, you cannot add any object of type A, B or C in it because you can end up with a combination that is not allowed in java.
In practice, the compiler can indeed see at compiletime that you add a B:
sharks.add(new HammerShark());
...but it has no way to tell if at runtime, your B will be a subtype or supertype of the list type. At runtime the list type can be any of the types A, B, C. So you cannot end up adding HammerSkark (super type) in a list of DeadHammerShark for example.
*You will say: "OK, but why can't I add HammerSkark in it since it is the smallest type?". Answer: It is the smallest you know. But HammerSkark can be extended too by somebody else and you end up in the same scenario.
Let's clarify CS - Consumer Super:
In the same hierarchy we can try this:
List<? super Shark> sharks = new ArrayList<>();
What and why you can add to this list?
sharks.add(new Shark());
sharks.add(new DeadHammerShark());
sharks.add(new HammerSkark());
You can add the above types of objects because anything below shark(A,B,C) will always be subtypes of anything above shark (X,Y,Z). Easy to understand.
You cannot add types above Shark, because at runtime the type of added object can be higher in hierarchy than the declared type of the list(X,Y,Z). This is not allowed.
But why you cannot read from this list? (I mean you can get an element out of it, but you cannot assign it to anything other than Object o):
Object o;
o = sharks.get(2);// only assignment that works
Animal s;
s = sharks.get(2);//doen't work
At runtime, the type of list can be any type above A: X, Y, Z, ... The compiler can compile your assignment statement (which seems correct) but, at runtime the type of s (Animal) can be lower in hierarchy than the declared type of the list(which could be Creature, or higher). This is not allowed.
To sum up
We use <? super T>
to add objects of types equal or below T
to the List
. We cannot read from
it.
We use <? extends T>
to read objects of types equal or below T
from list. We cannot add element to it.
With the introduction of Flexbox, this has become quite easy without much hacking. align-self: flex-end
on the child element will align it along the cross-axis.
.container {
display: flex;
}
.bottom {
align-self: flex-end;
}
<div class="container">
<div class="bottom">Bottom of the container</div>
</div>
Output:
.container {_x000D_
display: flex;_x000D_
/* Material design shadow */_x000D_
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);_x000D_
height: 100px;_x000D_
width: 175px;_x000D_
padding: 10px;_x000D_
background: #fff;_x000D_
font-family: Roboto;_x000D_
}_x000D_
.bottom {_x000D_
align-self: flex-end;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="bottom">Bottom of the container</div>_x000D_
</div>
_x000D_
When you use
this.getClass().getResource("myFile.ext")
getResource
will try to find the resource relative to the package.
If you use:
this.getClass().getResource("/myFile.ext")
getResource
will treat it as an absolute path and simply call the classloader like you would have if you'd done.
this.getClass().getClassLoader().getResource("myFile.ext")
The reason you can't use a leading /
in the ClassLoader
path is because all ClassLoader
paths are absolute and so /
is not a valid first character in the path.
There is another option that just entails using scikit-learn. As scikit's wiki describes, you can just use the following instructions:
from sklearn.model_selection import train_test_split
data, labels = np.arange(10).reshape((5, 2)), range(5)
data_train, data_test, labels_train, labels_test = train_test_split(data, labels, test_size=0.20, random_state=42)
This way you can keep in sync the labels for the data you're trying to split into training and test.
It happens when you are not setting the adapter during the creation phase:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
....
}
public void onResume() {
super.onResume();
mRecyclerView.setAdapter(mAdapter);
....
}
Just move setting the adapter into onCreate with an empty data and when you have the data call:
mAdapter.notifyDataSetChanged();
As per different sources, I think the minimum length in E-164 format depends on country to country. For eg:
For Sweden : The minimum number length (excluding the country code) is 7 digits. - Official Source? (country code 46)
For Solomon Islands its 5 for fixed line phones. - Source (country code 677)
... and so on. So including country code, the minimum length is 9 digits for Sweden and 11 for Israel and 8 for Solomon Islands.
Edit (Clean Solution): Actually, Instead of validating an international phone number by having different checks like length etc, you can use the Google's libphonenumber library. It can validate a phone number in E164 format directly. It will take into account everything and you don't even need to give the country if the number is in valid E164 format. Its pretty good! Taking an example:
String phoneNumberE164Format = "+14167129018"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
boolean isValid = phoneUtil.isValidNumber(phoneNumberProto); // returns true if valid
if (isValid) {
// Actions to perform if the number is valid
} else {
// Do necessary actions if its not valid
}
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
If you know the country for which you are validating the numbers, you don;t even need the E164 format and can specify the country in .parse
function instead of passing null
.
sys
has some useful stuff:
$ python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'c:\\Python26\\python.exe'
>>> sys.exec_prefix
'c:\\Python26'
>>>
>>> print '\n'.join(sys.path)
c:\Python26\lib\site-packages\setuptools-0.6c11-py2.6.egg
c:\Python26\lib\site-packages\nose-1.0.0-py2.6.egg
C:\Windows\system32\python26.zip
c:\Python26\DLLs
c:\Python26\lib
c:\Python26\lib\plat-win
c:\Python26\lib\lib-tk
c:\Python26
c:\Python26\lib\site-packages
c:\Python26\lib\site-packages\win32
c:\Python26\lib\site-packages\win32\lib
c:\Python26\lib\site-packages\Pythonwin
c:\Python26\lib\site-packages\wx-2.8-msw-unicode
I wrote up the answer for another question, though this is a more accurate question for it.
How do constructors and destructors work?
Here is a slightly opinionated answer.
Don't use __del__
. This is not C++ or a language built for destructors. The __del__
method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del__
, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:
__del__
is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execute del object
.__del__
is responsible for calling any __del__
in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.__del__
means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html.__del__
function can cheat, saving a reference to an object, and stopping the garbage collection.__del__
are ignored.__del__
complements __new__
far more than __init__
. This gets confusing. See http://www.algorithm.co.il/blogs/programming/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.__del__
is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the __del__
on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should __del__
called even if the __init__
fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.But, on the other hand:
__del__
means you do not forget to call a close statement. See http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/ for a pro __del__
viewpoint. This is usually about freeing ctypes or some other special resource.And my pesonal reason for not liking the __del__
function.
__del__
it devolves into thirty messages of confusion.So, find a reason not to use __del__
.
For me the solution was besides using "Ntlm" as credential type:
XxxSoapClient xxxClient = new XxxSoapClient();
ApplyCredentials(userName, password, xxxClient.ClientCredentials);
private static void ApplyCredentials(string userName, string password, ClientCredentials clientCredentials)
{
clientCredentials.UserName.UserName = userName;
clientCredentials.UserName.Password = password;
clientCredentials.Windows.ClientCredential.UserName = userName;
clientCredentials.Windows.ClientCredential.Password = password;
clientCredentials.Windows.AllowNtlm = true;
clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
}
Did you call your function properly? Ie. is the thing you pass as as a parameter really a string?
Otherwise, I don't see a problem with your code - the example below works as expected
function trim(str) {
return str.replace(/^\s+|\s+$/g,'');
}
trim(' hello '); // --> 'hello'
However, if you call your functoin with something non-string, you will indeed get the error above:
trim({}); // --> TypeError: str.replace is not a function
I am using git-bash in windows.The simplest way is to change the path address to have the forward slashes:
git clone C:/Dev/proposed
P.S: Start the git-bash on the destination folder.
Path used in clone ---> c:/Dev/proposed
Original path in windows ---> c:\Dev\proposed
I display images in windows forms when I put it in Load event like this:
private void Form1_Load( object sender , EventArgs e )
{
pictureBox1.ImageLocation = "./image.png"; //path to image
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}
If you really want an exe Excelsior JET is a professional level product that compiles to native code:
http://www.excelsior-usa.com/jet.html
You can also look at JSMooth:
http://jsmooth.sourceforge.net/
And if your application is compatible with its compatible with AWT/Apache classpath then GCJ compiles to native exe.
Run this code it will take input as audio(microphone) and convert into the text than audio play.
<!doctype HTML>
<head>
<title>MY Echo</title>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.1/css/font-awesome.min.css" />
<style type="text/css">
body {
font-family: verdana;
}
#result {
height: 100px;
border: 1px solid #ccc;
padding: 10px;
box-shadow: 0 0 10px 0 #bbb;
margin-bottom: 30px;
font-size: 14px;
line-height: 25px;
}
button {
font-size: 20px;
position: relative;
left: 50%;
}
</style>
Speech to text converter in JS var r = document.getElementById('result');
function startConverting() {
if ('webkitSpeechRecognition' in window) {
var speechRecognizer = new webkitSpeechRecognition();
speechRecognizer.continuous = true;
speechRecognizer.interimResults = true;
speechRecognizer.lang = 'en-IN';
speechRecognizer.start();
var finalTranscripts = '';
speechRecognizer.onresult = function(event) {
var interimTranscripts = '';
for (var i = event.resultIndex; i < event.results.length; i++) {
var transcript = event.results[i][0].transcript;
transcript.replace("\n", "<br>");
if (event.results[i].isFinal) {
finalTranscripts += transcript;
var speechresult = finalTranscripts;
console.log(speechresult);
if (speechresult) {
responsiveVoice.speak(speechresult, "UK English Female", {
pitch: 1
}, {
rate: 1
});
}
} else {
interimTranscripts += transcript;
}
}
r.innerHTML = finalTranscripts + '<span style="color:#999">' + interimTranscripts + '</span>';
};
speechRecognizer.onerror = function(event) {};
} else {
r.innerHTML = 'Your browser is not supported. If google chrome, please upgrade!';
}
}
</script>
</body>
</html>
A variation on the here-doc trick in the accepted answer by sunny256 is to use the Perl keywords for comments. If your comments are actually some sort of documentation, you can then start using the Perl syntax inside the commented block, which allows you to print it out nicely formatted, convert it to a man-page, etc.
As far as the shell is concerned, you only need to replace 'END'
with '=cut'
.
echo "before comment"
: <<'=cut'
=pod
=head1 NAME
podtest.sh - Example shell script with embedded POD documentation
etc.
=cut
echo "after comment"
(Found on "Embedding documentation in shell script")
If you want to log errors from web-page, you should use WebChromeClient
and override its onConsoleMessage
:
webView.settings.apply {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true
domStorageEnabled = true
}
webView.webViewClient = WebViewClient()
webView.webChromeClient = MyWebChromeClient()
private class MyWebChromeClient : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
Timber.d("${consoleMessage.message()}")
Timber.d("${consoleMessage.lineNumber()} ${consoleMessage.sourceId()}")
return super.onConsoleMessage(consoleMessage)
}
}
All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:
public int Position {get; set}
In your view model builder you set the position 1 through 4.
BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:
<div class="@Model.GridCSS">
Move the switch statement to your view model builder and populate the CSS class there.
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
The way to do this is via the bracket notation.
var test = {_x000D_
"id": "109",_x000D_
"No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
For more info read out here:
If you are talking about an actual database (an mdf file) you would Attach
it
.sql
files are typically run using SQL Server Management Studio. They are basically saved SQL statements, so could be anything. You don't "import" them. More precisely, you "execute" them. Even though the script may indeed insert data.
Also, to expand on Jamie F's answer, don't run a SQL file against your database unless you know what it is doing. SQL scripts can be as dangerous as unchecked exe's
Use file this code
function move_file($path,$to){
if(copy($path, $to)){
unlink($path);
return true;
} else {
return false;
}
}
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
It means that you can't use lambda expressions with a "statement body" (i.e. lambda expressions which use curly braces) in places where the lambda expression needs to be converted to an expression tree (which is for example the case when using linq2sql).
For reading the external Local JSON file (data.json) using javascript, first create your data.json file:
data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
Mention the path of the json file in the script source along with the javascript file.
<script type="text/javascript" src="data.json"></script>
<script type="text/javascript" src="javascrip.js"></script>
Get the Object from the json file
var mydata = JSON.parse(data);
alert(mydata[0].name);
alert(mydata[0].age);
alert(mydata[1].name);
alert(mydata[1].age);
For more information, see this reference.
AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.
timer.scheduleAtFixedRate( new Task(), 1000,3000);
Yes: call the toPandas
method on your dataframe and you'll get an actual pandas dataframe !
You can accomplish it with INSERT as below:
INSERT INTO mytable (id, a, b, c)
VALUES (1, 'a1', 'b1', 'c1'),
(2, 'a2', 'b2', 'c2'),
(3, 'a3', 'b3', 'c3'),
(4, 'a4', 'b4', 'c4'),
(5, 'a5', 'b5', 'c5'),
(6, 'a6', 'b6', 'c6')
ON DUPLICATE KEY UPDATE id=VALUES(id),
a=VALUES(a),
b=VALUES(b),
c=VALUES(c);
This insert new values into table, but if primary key is duplicated (already inserted into table) that values you specify would be updated and same record would not be inserted second time.
If your files have inconsistent use of spaces and tabs, you may find it helpful to include the -t
argument to expand the tabs:
diff -ty file1 file2
I had a similar animation problem on mobile screens but not on laptops, when trying to animate a div using jquery's animate command. So I decided to use a timer that restored the window's scroll position so frequently that to a naked eye the document would appear static. This solution worked perfectly on a small screen mobile device like Samsung Galaxy-2 or iphone-5.
Main Logic of this approach: The timer to set window's scroll position to original scroll position should be started before the jquery animate command, and then when animation is completed we need to clear this timer (original scroll position
is the position just before animation starts).
I found to my pleasant surprise that the document actually appeared static during the animation duration if the timer interval was 1 millisecond
, which is what I was aiming for.
//get window scroll position prior to animation
//so we can keep this position during animation
var xPosition = window.scrollX || window.pageXOffset || document.body.scrollLeft;
var yPosition = window.scrollY || window.pageYOffset || document.body.scrollTop;
//NOTE:restoreTimer needs to be global variable
//start the restore timer
restoreTimer = setInterval(function() {
window.scrollTo(xPosition, yPosition);
}, 1);
//animate the element emt
emt.animate({
left: "toggle",
top: "toggle",
width: "toggle",
height: "toggle"
}, 500, function() {
//when animation completes, we stop the timer
clearInterval(restoreTimer);
});
ANOTHER SOLUTION that worked: Based on the answer by Mohammad Anini under this post to enable/disable scrolling, I also found that a modified version of code as below worked.
//get current scroll position
var xPosition = window.scrollX || window.pageXOffset || document.body.scrollLeft;
var yPosition = window.scrollY || window.pageYOffset || document.body.scrollTop;
//disable scrolling
window.onscroll = function() {
window.scrollTo(xPosition, yPosition);
};
//animate and enable scrolling when animation is completed
emt.animate({
left: "toggle",
top: "toggle",
width: "toggle",
height: "toggle"
}, 500, function() {
//enable scrolling when animation is done
window.onscroll = function() {};
});
I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.
#horizontal-style {
padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line
justify-content: space-around;
display: flex;
}
#horizontal-style a {
text-align: center;
color: white;
text-decoration: none;
}
Create a repository folder under your project. Let's take
${project.basedir}/src/main/resources/repo
Then, install your custom jar to this repo:
mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]
Lastly, add the following repo and dependency definitions to the projects pom.xml:
<repositories>
<repository>
<id>project-repo</id>
<url>file://${project.basedir}/src/main/resources/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>[GROUP]</groupId>
<artifactId>[ARTIFACT]</artifactId>
<version>[VERS]</version>
</dependency>
</dependencies>
Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.
Column pruning
Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).
Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.
import pandas as pd
pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])
Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.
If the data is stored in a CSV file, you can read it like this:
import pandas as pd
pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])
usecols
can't skip over entire columns because of the row nature of the CSV file format.
Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.
Popularity
Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.
Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.
Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.
Schema
Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.
Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.
Column metadata
Parquet stores metadata statistics for each column and lets users add their own column metadata as well.
The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.
Here's how to fetch the column statistics with PyArrow.
import pyarrow.parquet as pq
parquet_file = pq.ParquetFile('some_file.parquet')
print(parquet_file.metadata.row_group(0).column(1).statistics)
<pyarrow._parquet.Statistics object at 0x11ac17eb0>
has_min_max: True
min: 1
max: 9
null_count: 0
distinct_count: 0
num_values: 3
physical_type: INT64
logical_type: None
converted_type (legacy): NONE
Complex column types
Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.
Compression
Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.
first_name,age
ken,30
felicia,36
mia,2
This data is easier to compress when the related types are stored in the same row:
ken,felicia,mia
30,36,2
Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.
Mutable nature of file
Parquet files are immutable, as described here. CSV files are mutable.
Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.
Data lakes
In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.
The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.
Python maps operators like +
, -
, *
and /
to special functions, such that e.g. a + b
is equivalent to
a.__add__(b)
Regarding division in Python 2, there is by default only /
which maps to __div__
and the result is dependent on the input types (e.g. int
, float
).
Python 2.2 introduced the __future__
feature division
, which changed the division semantics the following way (TL;DR of PEP 238):
/
maps to __truediv__
which must "return a reasonable approximation of
the mathematical result of the division" (quote from PEP 238)//
maps to __floordiv__
, which should return the floored result of /
With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__
in Python's object model.
If you want to use the same code in Python 2 and Python 3 use
from __future__ import division
and stick to the PEP 238 semantics of /
and //
.
I know this is an old question, but I think the responders may have misinterpreted it. I think what was intended was to convert a 16-digit bit sequence received as an unsigned integer (technically, an unsigned short
) into a signed integer. This might happen (it recently did to me) when you need to convert something received from a network from network byte order to host byte order. In that case, use a union:
unsigned short value_from_network;
unsigned short host_val = ntohs(value_from_network);
// Now suppose host_val is 65529.
union SignedUnsigned {
short s_int;
unsigned short us_int;
};
SignedUnsigned su;
su.us_int = host_val;
short minus_seven = su.s_int;
And now minus_seven
has the value -7.
An alternative to using keytool
, you can use the command
openssl x509 -in certificate.pem -text
This should work for any x509 .pem file provided you have openssl
installed.
The following worked for me (tested on react native 0.38
and 0.40
):
npm install -g ios-deploy
# Run on a connected device, e.g. Max's iPhone:
react-native run-ios --device "Max's iPhone"
If you try to run run-ios
, you will see that the script recommends to do npm install -g ios-deploy
when it reach install step after building.
While the documentation on the various commands that react-native offers is a little sketchy, it is worth going to react-native/local-cli. There, you can see all the commands available and the code that they run - you can thus work out what switches are available for undocumented commands.
Be careful, because none of these methods work with a large number of files. Personally, I used this line:
for i in $(ls | grep ".txt");do cat $i >> output.txt;done
EDIT: As someone said in the comments, you can replace $(ls | grep ".txt")
with $(ls *.txt)
EDIT: thanks to @gnourf_gnourf expertise, the use of glob is the correct way to iterate over files in a directory. Consequently, blasphemous expressions like $(ls | grep ".txt")
must be replaced by *.txt
(see the article here).
Good Solution
for i in *.txt;do cat $i >> output.txt;done
Ctrl + F2 works for me in Windows 10.
Ctrl + Shift + L starts performance logging
^M
gives unwanted line breaks. To handle this we can use the sed
command as follows:
sed 's/\r//g'
It's perfectly safe as long as you always access the values through the struct via the .
(dot) or ->
notation.
What's not safe is taking the pointer of unaligned data and then accessing it without taking that into account.
Also, even though each item in the struct is known to be unaligned, it's known to be unaligned in a particular way, so the struct as a whole must be aligned as the compiler expects or there'll be trouble (on some platforms, or in future if a new way is invented to optimise unaligned accesses).
Well, speaking from quarantine, the complete()
in $.ajax is like finally
in try catch block.
If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.
Same goes for complete()
in $.ajax, whether you get success()
response or error()
the complete()
function always will be called once the execution has been done.
Here is a helper that I wrote to solve this issue for my projects. It makes it super simple and easy to be able to clear everything out quickly and with a single command.
Note that -Dmaven.test.skip prevents Maven building the test-jar artifact.
If you'd like to skip tests but create artifacts as per a normal build use:
-Dmaven.test.skip.exec
You may use clang as well. It used to be faster than GCC, and now it is quite a stable thing. It is much easier to build clang from sources (you can really drink cup of coffee during build process).
In short:
Compile your code:
path/to/clang --target=arm-linux-gnueabihf --sysroot=/some/path/arm-linux-gnueabihf/sysroot my-happy-program.c -fuse-ld=lld
Optionally you may use legacy arm-linux-gnueabihf binutils. Then you may remove "-fuse-ld=lld" flag at the end.
Below is my cmake toolchain file.
toolchain.cmake
set(CMAKE_SYSTEM_VERSION 1)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
# Custom toolchain-specific definitions for your project
set(PLATFORM_ARM "1")
set(PLATFORM_COMPILE_DEFS "COMPILE_GLES")
# There we go!
# Below, we specify toolchain itself!
set(TARGET_TRIPLE arm-linux-gnueabihf)
# Specify your target rootfs mount point on your compiler host machine
set(TARGET_ROOTFS /Volumes/rootfs-${TARGET_TRIPLE})
# Specify clang paths
set(LLVM_DIR /Users/stepan/projects/shared/toolchains/llvm-7.0.darwin-release-x86_64/install)
set(CLANG ${LLVM_DIR}/bin/clang)
set(CLANGXX ${LLVM_DIR}/bin/clang++)
# Specify compiler (which is clang)
set(CMAKE_C_COMPILER ${CLANG})
set(CMAKE_CXX_COMPILER ${CLANGXX})
# Specify binutils
set (CMAKE_AR "${LLVM_DIR}/bin/llvm-ar" CACHE FILEPATH "Archiver")
set (CMAKE_LINKER "${LLVM_DIR}/bin/llvm-ld" CACHE FILEPATH "Linker")
set (CMAKE_NM "${LLVM_DIR}/bin/llvm-nm" CACHE FILEPATH "NM")
set (CMAKE_OBJDUMP "${LLVM_DIR}/bin/llvm-objdump" CACHE FILEPATH "Objdump")
set (CMAKE_RANLIB "${LLVM_DIR}/bin/llvm-ranlib" CACHE FILEPATH "ranlib")
# You may use legacy binutils though.
#set(BINUTILS /usr/local/Cellar/arm-linux-gnueabihf-binutils/2.31.1)
#set (CMAKE_AR "${BINUTILS}/bin/${TARGET_TRIPLE}-ar" CACHE FILEPATH "Archiver")
#set (CMAKE_LINKER "${BINUTILS}/bin/${TARGET_TRIPLE}-ld" CACHE FILEPATH "Linker")
#set (CMAKE_NM "${BINUTILS}/bin/${TARGET_TRIPLE}-nm" CACHE FILEPATH "NM")
#set (CMAKE_OBJDUMP "${BINUTILS}/bin/${TARGET_TRIPLE}-objdump" CACHE FILEPATH "Objdump")
#set (CMAKE_RANLIB "${BINUTILS}/bin/${TARGET_TRIPLE}-ranlib" CACHE FILEPATH "ranlib")
# Specify sysroot (almost same as rootfs)
set(CMAKE_SYSROOT ${TARGET_ROOTFS})
set(CMAKE_FIND_ROOT_PATH ${TARGET_ROOTFS})
# Specify lookup methods for cmake
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# Sometimes you also need this:
# set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
# Specify raspberry triple
set(CROSS_FLAGS "--target=${TARGET_TRIPLE}")
# Specify other raspberry related flags
set(RASP_FLAGS "-D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS")
# Gather and distribute flags specified at prev steps.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CROSS_FLAGS} ${RASP_FLAGS}")
# Use clang linker. Why?
# Well, you may install custom arm-linux-gnueabihf binutils,
# but then, you also need to recompile clang, with customized triple;
# otherwise clang will try to use host 'ld' for linking,
# so... use clang linker.
set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld)
private static final int SELECT_PHOTO = 100;
Start intent
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
Process result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
}
}
}
Alternatively, you can also downsample your image to avoid OutOfMemory errors.
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 140;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
If you have directory listing disabled in your webserver, then the only way somebody will find it is by guessing or by finding a link to it.
That said, I've seen hacking scripts attempt to "guess" a whole bunch of these common names. "secret.html" would probably be in such a guess list.
The more reasonable solution is to restrict access using a username/password via a htaccess file (for apache) or the equivalent setting for whatever webserver you're using.
Another way to do this is with union:
INSERT INTO Data ( Col1 )
select 'hello'
union
select 'world'
This is how you can add .jar
file in Android Studio 2.1.3.
AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle
android {
signingConfigs {
release {
storeFile file('android.keystore')
storePassword "pwd"
keyAlias "alias"
keyPassword "pwd"
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
To actually run your application at emulator or device run gradle installDebug
or gradle installRelease
.
You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872
Polo I wouldn't use Bundles in MVC for multiple reasons. It doesn't work in your case because you have to set up a custom BundleConfig class in your Apps_Start folder. This makes no sense when you can simple add a style in the head of your html like so:
<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/bootstrap.theme.css" />
You can also add these to a Layout.cshtml or partial class that's called from all your views and dropped into each page. If your styles change, you can easily change the name and path without having to recompile.
Adding hard-coded links to CSS in a class breaks with the whole purpose of separation of the UI and design from the application model, as well. You also don't want hard coded style sheet paths managed in c# because you can no longer build "skins" or separate style models for say different devices, themes, etc. like so:
<link rel="stylesheet" href="~/UI/Skins/skin1/base.css" />
<link rel="stylesheet" href="~/UI/Skins/skin2/base.css" />
Using this system and Razor you can now switch out the Skin Path from a database or user setting and change the whole design of your website by just changing the path dynamically.
The whole purpose of CSS 15 years ago was to develop both user-controlled and application-controlled style sheet "skins" for sites so you could switch out the UI look and feel separate from the application and repurpose the content independent of the data structure.....for example a printable version, mobile, audio version, raw xml, etc.
By moving back now to this "old-fashioned", hard-coded path system using C# classes, rigid styles like Bootstrap, and merging the themes of sites with application code, we have gone backwards again to how websites were built in 1998.
You can try this
set @duration= 112000
SELECT
"Time" = cast (@duration/3600 as varchar(3)) +'H'
+ Case
when ((@duration%3600 )/60)<10 then
'0'+ cast ((@duration%3600 )/60)as varchar(3))
else
cast ((@duration/60) as varchar(3))
End
I get the same error when I run Oracle XE instance on the same machine. As my database is Oracle, I preferred changing Glassfish's default port:
<network-listener port="9090" protocol="http-listener-1" transport="tcp" name="http-listener-1" thread-pool="http-thread-pool"></network-listener>_x000D_
_x000D_
My solution:
Option Explicit
Public datHora As Date
Function Cronometro(action As Integer) As Integer
'This return the seconds between two >calls
Cronometro = 0
If action = 1 Then 'Start
datHora = Now
End If
If action = 2 Then 'Time until that moment
Cronometro = DateDiff("s", datHora, Now)
End If
End Function
How to use? Easy...
dummy= Cronometro(1) ' This starts the timer
seconds= Cronometro(2) ' This returns the seconds between the first call and this one
If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.
Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/
EDIT
Your code should look like this:
.img_thumb {
float: left;
height: 120px;
margin-bottom: 5px;
margin-left: 9px;
position: relative;
width: 147px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 3px;
line-height:120px;
text-align:center;
}
.img_thumb img {
vertical-align: middle;
}
The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:
http://jsfiddle.net/Cthulhu/QHEnL/6/
http://jsfiddle.net/Cthulhu/QHEnL/7/
UPDATE
It's now 2016 (the future!) and looks like a few things are changing (finally!!).
Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).
Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.
With that being said, here's an updated way of aligning elements, both horizontally and vertically:
.container {
position: relative;
}
.container .element {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Using this transform: translate();
method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.
If you only need to center in one dimension, you can use translateY
or translateX
. Just try it for a while and you'll see how it works. Also, try to change the values of the translate
, you will find it useful for a bunch of different situations.
Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/
For more information on transform
, here's a good resource.
Happy coding.
wtluo, great ! May I propose a slight modification of your code 2. ? Here it is:
for i, detected_box in enumerate(detect_boxes):
box = detected_box["box"]
face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)
This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset
or a null coalescing operator which is introduced in PHP7:
$param = $_GET['param'] ?? 'default';
Use position: fixed
instead of position: absolute
.
See here.
Set specific tab index as active:
$(this).tabs({ active: # }); /* Where # is the tab index. The index count starts at 0 */
Set last tab as active
$(this).tabs({ active: -1 });
Set specific tab by ID:
$(this).tabs({ active: $('a[href="#tab-101"]').parent().index() });
1) you are calling it wrong way try:
$(input[name="searchBar"]).val('hi')
2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event
$(document).ready(function() {
$(input[name="searchBar"]).val('hi');
});
Spring documentation to disable csrf: https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-configure
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
yes on your aspx page include a script tag with runat=server
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
// some load code
}
</script>
You can also use classic ASP Syntax
<% if (this.MyTextBox.Visible) { %>
<span>Only show when myTextBox is visible</span>
<% } %>
To add a header just add the following code to the location block where you want to add the header:
location some-location {
add_header X-my-header my-header-content;
}
Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.
Instead of Str(RequestID)
, try convert(varchar(38), RequestID)
try this code
data.php
<table border="1">
<tr>
<th>NO.</th>
<th>NAME</th>
<th>Major</th>
</tr>
<?php
//connection to mysql
mysql_connect("localhost", "root", ""); //server , username , password
mysql_select_db("codelution");
//query get data
$sql = mysql_query("SELECT * FROM student ORDER BY id ASC");
$no = 1;
while($data = mysql_fetch_assoc($sql)){
echo '
<tr>
<td>'.$no.'</td>
<td>'.$data['name'].'</td>
<td>'.$data['major'].'</td>
</tr>
';
$no++;
}
?>
code for excel file
export.php
<?php
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=codelution-export.xls");
// Add data table
include 'data.php';
?>
if mysqli version
$sql="SELECT * FROM user_details";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
$no = 1;
while($data = mysqli_fetch_assoc($result))
{echo '
<tr>
<<td>'.$no.'</td>
<td>'.$data['name'].'</td>
<td>'.$data['major'].'</td>
</tr>
';
$no++;
http://codelution.com/development/web/easy-ways-to-export-data-from-mysql-to-excel-with-php/
It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.
In general, I suggest calling a function on ng-click like so:
<a ng-click="navigateToPath()">click me</a>
obj.val1
& obj.val2
should be available on your controller's $scope, you dont need to pass those into a function from the markup.
then, in your controller:
$scope.navigateToPath = function(){
var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
$location.path(path)
}
To change the Modal position in the viewport you can target the Modal div id, in this example this id is myModal3
<div id="modal3" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#myModal3 {
top:5%;
right:50%;
outline: none;
overflow:hidden;
}
This one worked for me.
public void RestrictNumbersOnly(TextField tf){
tf.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
if (!newValue.matches("|[-\\+]?|[-\\+]?\\d+\\.?|[-\\+]?\\d+\\.?\\d+")){
tf.setText(oldValue);
}
}
});
}
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
I have found that the error is sometimes caused by a missing library.
so If you install RDOC first by running
gem install rdoc
then install rails with:
gem install rails
then go back and install the devtools as mentioned before with:
1) Extract DevKit to path C:\Ruby193\DevKit
2) cd C:\Ruby192\DevKit
3) ruby dk.rb init
4) ruby dk.rb review
5) ruby dk.rb install
then try installing json
which culminate with you finally being able to run
rails new project_name
- without errors.
good luck
HttpClient webClient = new HttpClient();
Uri uri = new Uri("your url");
HttpResponseMessage response = await webClient.GetAsync(uri)
var jsonString = await response.Content.ReadAsStringAsync();
var objData = JsonConvert.DeserializeObject<List<CategoryModel>>(jsonString);
FileReader reads from files on the file system.
Perhaps you intended to use something like this to load a file from the class path
// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
.getResourceAsStream("config.txt");
Or you could extract the file from the jar before reading it.
You can also use "smart-ip" service:
$.getJSON("http://smart-ip.net/geoip-json?callback=?",
function (data) {
alert(data.countryName);
alert(data.city);
}
);
The simplest that helped me:
rm -rf _dir_in_question_
svn up
If you have changes in the problematic dir, then this is not a good solution for you.
It's in the python docs.
import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1),
datetime.time(10, 23))
returns
datetime.datetime(2011, 1, 1, 10, 23)
Loop through the dictionary to find the index and then remove it.
I am using numbers to resize by mapping the following in .vimrc
nmap 7 :res +2<CR> " increase pane by 2
nmap 8 :res -2<CR> " decrease pane by 2
nmap 9 :vertical res +2<CR> " vertical increase pane by 2
nmap 0 :vertical res -2<CR> " vertical decrease pane by 2
UITextView *textview= [[UITextView alloc]initWithFrame:CGRectMake(10, 130, 250, 170)];
NSString *str = @"This is <font color='red'>simple</font>";
[textview setValue:str forKey:@"contentToHTMLString"];
textview.textAlignment = NSTextAlignmentLeft;
textview.editable = NO;
textview.font = [UIFont fontWithName:@"vardana" size:20.0];
[UIView addSubview:textview];
work fine for me
I know this is an old post but I came across it when faced with a similar issue using core 3.0, hope it helps someone.
@{
Layout = null;
ViewData["SampleString"] = "some string need in the partial";
}
<partial name="_Partial" for="PartialViewModel" view-data="ViewData" />
Assuming that rand(n) here means "random integer in a uniform distribution from 0 to n-1", here's a code sample using Python's randint, which has that effect. It uses only randint(5), and constants, to produce the effect of randint(7). A little silly, actually
from random import randint
sum = 7
while sum >= 7:
first = randint(0,5)
toadd = 9999
while toadd>1:
toadd = randint(0,5)
if toadd:
sum = first+5
else:
sum = first
assert 7>sum>=0
print sum
An incredibly powerful alternative to other answers here:
ng-class="[ { key: resulting-class-expression }[ key-matching-expression ], .. ]"
Some examples:
1. Simply adds 'class1 class2 class3' to the div:
<div ng-class="[{true: 'class1'}[true], {true: 'class2 class3'}[true]]"></div>
2. Adds 'odd' or 'even' classes to div, depending on the $index:
<div ng-class="[{0:'even', 1:'odd'}[ $index % 2]]"></div>
3. Dynamically creates a class for each div based on $index
<div ng-class="[{true:'index'+$index}[true]]"></div>
If $index=5
this will result in:
<div class="index5"></div>
Here's a code sample you can run:
var app = angular.module('app', []); _x000D_
app.controller('MyCtrl', function($scope){_x000D_
$scope.items = 'abcdefg'.split('');_x000D_
});
_x000D_
.odd { background-color: #eee; }_x000D_
.even { background-color: #fff; }_x000D_
.index5 {background-color: #0095ff; color: white; font-weight: bold; }_x000D_
* { font-family: "Courier New", Courier, monospace; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="app" ng-controller="MyCtrl">_x000D_
<div ng-repeat="item in items"_x000D_
ng-class="[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]]">_x000D_
index {{$index}} = "{{item}}" ng-class="{{[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]].join(' ')}}"_x000D_
</div>_x000D_
</div>
_x000D_
Other way is using of built-in method start timer & event TimerEvent.
Header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
int timerId;
protected:
void timerEvent(QTimerEvent *event);
};
#endif // MAINWINDOW_H
Source:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timerId = startTimer(1000);
}
MainWindow::~MainWindow()
{
killTimer(timerId);
delete ui;
}
void MainWindow::timerEvent(QTimerEvent *event)
{
qDebug() << "Update...";
}
path of pg_config in my case (MacOS)
/Library/PostgreSQL/13/bin
Execute the following in the terminal:
PATH="/Library/PostgreSQL/13/bin:$PATH"
Then
pip install psycopg2
try this
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
$_SESSION['myid'] = $row['id'];
}
@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank",@class="edit"})
script below will open the action view url in a new window
<script type="text/javascript">
$(function (){
$('a.edit').click(function () {
var url = $(this).attr('href');
window.open(url, "popupWindow", "width=600,height=800,scrollbars=yes");
});
return false;
});
</script>
SQL Server / MS Access Syntax:
SELECT TOP 1 * FROM table_name ORDER BY RAND()
MySQL Syntax:
SELECT * FROM table_name ORDER BY RAND() LIMIT 1
Another solution: go through a filter with your inverted conditions : Example :
if(subscribtion.isOnce() && subscribtion.isCalled()){
continue;
}
can be replaced with
.filter(s -> !(s.isOnce() && s.isCalled()))
The most straightforward approach seem to be using "return;" though.
many ways to change date format
private final String dateTimeFormatPattern = "yyyy/MM/dd";
private final Date now = new Date();
final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);
final String nowString = format.format(now);
final Instant instant = now.toInstant();
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(
dateTimeFormatPattern).withZone(ZoneId.systemDefault());
final String formattedInstance = formatter.format(instant);
/* Java 8 needed*/
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
Infact, 2 dimensional array is the list of list of X
, where X
is one of your data structures from typical ones to user-defined ones. As the following snapshot code, I added row by row into an array triangle
. To create each row, I used the method add
to add elements manually or the method asList
to create a list from a band of data.
package algorithms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RunDemo {
/**
* @param args
*/
public static void main(String[] args) {
// Get n
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row1 = new ArrayList<Integer>(1);
row1.add(2);
triangle.add(row1);
List<Integer> row2 = new ArrayList<Integer>(2);
row2.add(3);row2.add(4);
triangle.add(row2);
triangle.add(Arrays.asList(6,5,7));
triangle.add(Arrays.asList(4,1,8,3));
System.out.println("Size = "+ triangle.size());
for (int i=0; i<triangle.size();i++)
System.out.println(triangle.get(i));
}
}
Running the sample, it generates the output:
Size = 4
[2]
[3, 4]
[6, 5, 7]
[4, 1, 8, 3]
In DialogFragment, custom animation is called onCreateDialog. 'DialogAnimation' is custom animation style in previous answer.
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
return dialog;
}
$('#root').append(child);
// do your work here
Append doesn't have callbacks, and this is code that executes synchronously - there is no risk of it NOT being done
The following constructor, JLabel(String, int)
, allow you to specify the horizontal alignment of the label.
JLabel label = new JLabel("The Label", SwingConstants.CENTER);
SELECT date1 - date2
FROM some_table
returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So
SELECT (date1 - date2) * 24 * 60 difference_in_minutes
FROM some_table
should be what you're looking for
Like hughdbrown, I like Fabric. Please notice that while it implement its own declarative scripting (for making deploys and the such) it can also be imported as a Python module and used on your programs without having to write a Fabric script.
Fabric has a new maintainer and is in the process of being rewriten; that means that most tutorials you'll (currently) find on the web will not work with the current version. Also, Google still shows the old Fabric page as the first result.
For up to date documentation you can check: http://docs.fabfile.org
if you are looking for something speedy, here's a method I've been using that's worked for years:
from array import array
with open( path, 'rb' ) as file:
data = array( 'B', file.read() ) # buffer the file
# evaluate it's data
for byte in data:
v = byte # int value
c = chr(byte)
if you want to iterate chars instead of ints, you can simply use data = file.read()
, which should be a bytes() object in py3.
Try "difftool" (assuming you have diff tools setup) - see https://www.kernel.org/pub/software/scm/git/docs/git-difftool.html
I find name status good for the summary but difftool will iterate the changes (and the -d
option gives you the directory view), e.g.
$ git difftool their-branch my-branch
Viewing: 'file1.txt'
Launch 'bc3' [Y/n]:
...
Or as @rsilva4 mentioned with -d
and default to your current branch it is just - e.g. compare to master:
$ git difftool -d master..
...and yes - there are many variations - https://www.kernel.org/pub/software/scm/git/docs/git-reset.html
I liked the way @OscarRyz presents. Although here i am continuing the story of serialization which was originally written by @amitgupta.
Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.
Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:
Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything became fine.
queryParams
queryParams
is another input of routerLink
where they can be passed like
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>
fragment
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>
routerLinkActiveOptions
To also get routes active class set on parent routes:
[routerLinkActiveOptions]="{ exact: false }"
To pass query parameters to this.router.navigate(...)
use
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
See also https://angular.io/guide/router#query-parameters-and-fragments
FWIW, here's the dictionary thing. After setting a reference to MS Scripting. You can jack around with the array size of avInput to match your needs.
Sub somemacro()
Dim avInput As Variant
Dim uvals As Dictionary
Dim i As Integer
Dim rop As Range
avInput = Sheets("data").UsedRange
Set uvals = New Dictionary
For i = 1 To UBound(avInput, 1)
If uvals.Exists(avInput(i, 1)) = False Then
uvals.Add avInput(i, 1), 1
Else
uvals.Item(avInput(i, 1)) = uvals.Item(avInput(i, 1)) + 1
End If
Next i
ReDim avInput(1 To uvals.Count)
i = 1
For Each kv In uvals.Keys
avInput(i) = kv
i = i + 1
Next kv
Set rop = Sheets("sheet2").Range("a1")
rop.Resize(UBound(avInput, 1), 1) = Application.Transpose(avInput)
End Sub
You can also overcome this problem with
git mergetool
which causes git
to create local copies of the conflicted binary and spawn your default editor on them:
{conflicted}.HEAD
{conflicted}
{conflicted}.REMOTE
Obviously you can't usefully edit binaries files in a text editor. Instead you copy the new {conflicted}.REMOTE
file over {conflicted}
without closing the editor. Then when you do close the editor git
will see that the undecorated working-copy has been changed and your merge conflict is resolved in the usual way.
Converting svn submodule/folder 'MyModule' into git with history without tags nor branches.
To retain svn ignore list use the above comments after step 1