I suggest you run:
$ brew update && brew upgrade
Until couple of minutes ago I had this problem, too. Because I have an up to date PHP version, I solved it with:
$ brew reinstall php55
Hope that helps.
This issue can also occur when you pull code from git and not yet installed node modules "npm install".
$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);
you can change LIMIT 1 to LIMIT any number you want
This will show you the last INSERTED row first.
try this
ArrayList<ArrayList<String>> PriceModelList = new ArrayList<>();
ArrayList<ArrayList<String>> PriceQtyList = new ArrayList<>();
ArrayList<ArrayList<String>> PriceTotalList = new ArrayList<>();
for (int i = 0; i < CustomerNames.length; i++) {
PriceModelList.add(new ArrayList<String>());
String[] PriceModel = {"s6", "s7", "note4", "note5", "j5", "j6"};
for (int j = 0; j < PriceModel.length; j++) {
PriceModelList.get(i).add(PriceModel[j]);
}
PriceQtyList.add(new ArrayList<String>());
String[] PriceQut = {"12", "13", "21", "15", "43", "21"};
for (int k = 0; k < PriceQut.length; k++) {
PriceQtyList.get(i).add(PriceQut[k]);
}
PriceTotalList.add(new ArrayList<String>());
String[] PriceTotal = {"1323", "1312321", "43123212", "43434", "12312", "43322"};
for (int m = 0; m < PriceTotal.length; m++) {
PriceTotalList.get(i).add(PriceTotal[m]);
}
}
ArrayList<ArrayList<ArrayList<String>>> CustomersShoppingLists = new ArrayList<>();
CustomersShoppingLists.add(PriceModelList);
CustomersShoppingLists.add(PriceQtyList);
CustomersShoppingLists.add(PriceTotalList);
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
Here is another open source library to create CSV file easily, Cinchoo ETL
List<dynamic> objs = new List<dynamic>();
dynamic rec1 = new ExpandoObject();
rec1.Id = 10;
rec1.Name = @"Mark";
rec1.JoinedDate = new DateTime(2001, 2, 2);
rec1.IsActive = true;
rec1.Salary = new ChoCurrency(100000);
objs.Add(rec1);
dynamic rec2 = new ExpandoObject();
rec2.Id = 200;
rec2.Name = "Tom";
rec2.JoinedDate = new DateTime(1990, 10, 23);
rec2.IsActive = false;
rec2.Salary = new ChoCurrency(150000);
objs.Add(rec2);
using (var parser = new ChoCSVWriter("emp.csv").WithFirstLineHeader())
{
parser.Write(objs);
}
For more information, please read the CodeProject article on usage.
One thing to double-check is that you have applied your theme correctly in your AndroidManifest.xml file. In my case, I had omitted the android:theme attribute. E.g:
<application ... android:theme="@style/Your.Theme.Here" ... >
Another simpler/lighter alternative to gnuplot is ervy, a NodeJS based terminal charts tool.
Supported types: scatter (XY points), bar, pie, bullet, donut and gauge.
Usage examples with various options can be found on the projects GitHub repo
how to convert JTextField to string and string to JTextField in java
If you mean how to get and set String from jTextField then you can use following methods:
String str = jTextField.getText() // get string from jtextfield
and
jTextField.setText(str) // set string to jtextfield
//or
new JTextField(str) // set string to jtextfield
You should check JavaDoc for JTextField
It can also be done using a single line with while
loops and if
like this:
if (blah)
doThis();
It also works with while
loops.
You have a scope problem indeed, because statement
is a local method variable defined here:
protected void createContents() {
...
Statement statement = null; // local variable
...
btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
@Override
public void mouseDown(MouseEvent e) {
...
try {
statement.executeUpdate(query); // local variable out of scope here
} catch (SQLException e1) {
e1.printStackTrace();
}
...
});
}
When you try to access this variable inside mouseDown()
method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final
(which given your code is not possible) or declared as a class member so the inner class can access this statement
variable.
Sources:
Make statement
a class member instead of a local variable:
public class A1 { // Note Java Code Convention, also class name should be meaningful
private Statement statement;
...
}
Define another final variable and use this one instead, as suggested by @HotLicks:
protected void createContents() {
...
Statement statement = null;
try {
statement = connect.createStatement();
final Statement innerStatement = statement;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
...
}
Reconsider your approach. If statement
variable won't be used until btnInsert
button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:
btnInsert.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
try (Connection connect = DriverManager.getConnection(...);
Statement statement = connect.createStatement()) {
// execute the statement here
} catch (SQLException ex) {
ex.printStackTrace();
}
} catch (ClassNotFoundException ex) {
e.printStackTrace();
}
});
Edit filename: core/Common.php, line number: 257
Before
return $_config[0] =& $config;
After
$_config[0] =& $config;
return $_config[0];
Added by NikiC
In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).
This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.
localhost
will always redirect to 127.0.0.1
. You can trick this by naming your other VirtualHost to other local loop-back address, such as 127.0.0.2
. Make sure you also change the corresponding hosts
file to implement this.
For example, my httpd-vhosts.conf
looks like this:
<VirtualHost 127.0.0.2:80>
DocumentRoot "D:/6. App Data/XAMPP Shared/htdocs/intranet"
ServerName intranet.dev
ServerAlias www.intranet.dev
ErrorLog "logs/intranet.dev-error.log"
CustomLog "logs/intranet.dec-access.log" combined
<Directory "D:/6. App Data/XAMPP Shared/htdocs/intranet">
Options Indexes FollowSymLinks ExecCGI Includes
Order allow,deny
Allow from all
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
(Notice that in <VirtualHost>
section I typed 127.0.0.2:80
. It means that this block of VirtualHost will only affects requests to IP address 127.0.0.2
port 80
, which is the default port for HTTP.
To route the name intranet.dev
properly, my hosts
entry line is like this:
127.0.0.2 intranet.dev
This way, it will prevent you from creating another VirtualHost block for localhost
, which is unnecessary.
Go to the starting line and type ma (mark "a"). Then go to the last line and enter d'a (delete to mark "a").
That will delete all lines from the current to the marked one (inclusive). It's also compatible with vi
as well as vim
, on the off chance that your environment is not blessed with the latter.
This solution work on my case i am using ubuntu 16.04, VirtualBox 2.7.2 and genymotion 2.7.2 Same error come in my system i have followed simple step and my problem was solve
1. $ LD_LIBRARY_PATH=/usr/local/lib64/:$LD_LIBRARY_PATH
2. $ export LD_LIBRARY_PATH
3. $ sudo apt-add-repository ppa:ubuntu-toolchain-r/test
4. $ sudo apt-get update
5. $ sudo apt-get install gcc-4.9 g++-4.9
I hope this will work for you
I used to ponder and desire the same feature. But over time, I noticed it really isn't needed. When you stash, it's OK to leave the new files. Nothing "bad" can happen to them (when you check out something else, git will error and not overwrite the existing untracked file)
And since usually the time frame between the git stash
and the git stash pop
is rather small, you'll be needing the untracked file quickly again.
So I would say the inconvenience of the file showing up in git status
while you're working on something else (between the git stash
and the git stash pop
) is smaller then the inconvenience caused by the work and needed attention it would otherwise cost to try to add the untracked file to your stash.
Wrap text in a span and use jquery width()
You can use an RDLC file provided in visual studio to define your report layout. You can view the rdlc using the ReportViewer control.
Both are provided out of the box with visual studio.
This is what worked for my, and its pure css
css
html {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
#bg {
width: 100%;
height: 100%;
background: url('/image.jpg/') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
-webkit-animation: myfirst 5s ; /* Chrome, Safari, Opera */
animation: myfirst 5s ;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
from {opacity: 0.2;}
to {opacity: 1;}
}
/* Standard syntax */
@keyframes myfirst {
from {opacity: 0.2;}
to {opacity: 1;}
}
html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="bg">
<!-- content here -->
</div> <!-- end bg -->
</body>
</html>
This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.
Here are the steps I found to work.
Use pdfimages
from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.
Use Tesseract to detect rotation and ImageMagick mogrify
to fix it.
Use OpenCV to find and extract tables.
Use OpenCV to find and extract each cell from the table.
Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.
Use Tesseract to OCR each cell.
Combine the extracted text of each cell into the format you need.
I wrote a python package with modules that can help with those steps.
Repo: https://github.com/eihli/image-table-ocr
Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html
Some of the steps don't require code, they take advantage of external tools like pdfimages
and tesseract
. I'll provide some brief examples for a couple of the steps that do require code.
This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/
import cv2
def find_tables(image):
BLUR_KERNEL_SIZE = (17, 17)
STD_DEV_X_DIRECTION = 0
STD_DEV_Y_DIRECTION = 0
blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
MAX_COLOR_VAL = 255
BLOCK_SIZE = 15
SUBTRACT_FROM_MEAN = -2
img_bin = cv2.adaptiveThreshold(
~blurred,
MAX_COLOR_VAL,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
BLOCK_SIZE,
SUBTRACT_FROM_MEAN,
)
vertical = horizontal = img_bin.copy()
SCALE = 5
image_width, image_height = horizontal.shape
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)
horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))
mask = horizontally_dilated + vertically_dilated
contours, hierarchy = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
)
MIN_TABLE_AREA = 1e5
contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
epsilons = [0.1 * p for p in perimeter_lengths]
approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
bounding_rects = [cv2.boundingRect(a) for a in approx_polys]
# The link where a lot of this code was borrowed from recommends an
# additional step to check the number of "joints" inside this bounding rectangle.
# A table should have a lot of intersections. We might have a rectangular image
# here though which would only have 4 intersections, 1 at each corner.
# Leaving that step as a future TODO if it is ever necessary.
images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
return images
This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.
We want to identify the cells from left-to-right, top-to-bottom.
We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.
def cell_in_same_row(c1, c2):
c1_center = c1[1] + c1[3] - c1[3] / 2
c2_bottom = c2[1] + c2[3]
c2_top = c2[1]
return c2_top < c1_center < c2_bottom
orig_cells = [c for c in cells]
rows = []
while cells:
first = cells[0]
rest = cells[1:]
cells_in_same_row = sorted(
[
c for c in rest
if cell_in_same_row(c, first)
],
key=lambda c: c[0]
)
row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
rows.append(row_cells)
cells = [
c for c in rest
if not cell_in_same_row(c, first)
]
# Sort rows by average height of their center.
def avg_height_of_center(row):
centers = [y + h - h / 2 for x, y, w, h in row]
return sum(centers) / len(centers)
rows.sort(key=avg_height_of_center)
You should execute the next query:
GRANT ALL ON TABLE mytable TO myuser;
Or if your error is in a view then maybe the table does not have permission, so you should execute the next query:
GRANT ALL ON TABLE tbm_grupo TO myuser;
You can request a path in this format:
/package/path/to/the/resource.ext
Even the bytes for creating the classes in memory are found this way:
my.Class -> /my/Class.class
and getResource
will give you a URL which can be used to retrieve an InputStream
.
But... I'd recommend using directly getClass().getResourceAsStream(...)
with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.
In short: try using getResourceAsStream
and some constructor of ImageIcon
that uses an InputStream
as an argument.
Classloaders
Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon
was capable of finding it.
Edit: classpath
getResource
is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.
If you are using windows, then take a look at this link. Otherwise, you may look for your OS specific version api. I don't think C++ comes with a cross-platform way to do it. At the end, it's NOT C++'s work, it's the OS's work.
The quick and dirty way to check what string you need it to look at the generated .resources files.
Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)
Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.
For example in my obj/Bin directory I have the file:
MyLocalisation.Properties.Resources.resources
If the resource files are in the same Class library/Application I would use the following C#
ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());
However, as it sounds like you are using the resources file from a separate Class library/Application you probably want
Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);
From Microsoft:
Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop.
I'm assuming the exception is happening within an internal .NET method, and not in your code.
You can do a couple things.
You can use the Process class to load the assembly that will apply the transform into a separate process, and alert the user of the failure if it dies, without killing your main app.
EDIT: I just tested, here is how to do it:
MainProcess:
// This is just an example, obviously you'll want to pass args to this.
Process p1 = new Process();
p1.StartInfo.FileName = "ApplyTransform.exe";
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.Start();
p1.WaitForExit();
if (p1.ExitCode == 1)
Console.WriteLine("StackOverflow was thrown");
ApplyTransform Process:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
throw new StackOverflowException();
}
// We trap this, we can't save the process,
// but we can prevent the "ILLEGAL OPERATION" window
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.IsTerminating)
{
Environment.Exit(1);
}
}
}
It's already an array of C-style strings:
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char *argv[]) // Don't forget first integral argument 'argc'
{
std::string current_exec_name = argv[0]; // Name of the current exec program
std::vector<std::string> all_args;
if (argc > 1) {
all_args.assign(argv + 1, argv + argc);
}
}
Argument argc
is count of arguments plus the current exec file.
I'd say this is an indicator of a flawed table structure. Perhaps the different location types should be separated in different tables, enabling you to do much richer querying and also avoid having superfluous columns around.
If you're unable to change the structure, something like the below might work:
SELECT
*
FROM
Test
WHERE
Account_Location = (
CASE LocationType
WHEN 'location' THEN @locationID
ELSE Account_Location
END
)
AND
Account_Location_Area = (
CASE LocationType
WHEN 'area' THEN @locationID
ELSE Account_Location_Area
END
)
And so forth... We can't change the structure of the query on the fly, but we can override it by making the predicates equal themselves out.
EDIT: The above suggestions are of course much better, just ignore mine.
This would do the trick, returning the values at indeces 0, 2 and 3.
Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
You need to set Opacity first for standards-compliant browsers, then the various versions of IE. See Example:
but this opacity code not work in ie8
.slidedownTrigger
{
cursor: pointer;
opacity: .75; /* Standards Compliant Browsers */
filter: alpha(opacity=75); /* IE 7 and Earlier */
/* Next 2 lines IE8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=75);
}
Note that I eliminated -moz as Firefox is a Standards Compliant browser and that line is no longer necessary. Also, -khtml is depreciated, so I eliminated that style as well.
Furthermore, IE's filters will not validate to w3c standards, so if you want your page to validate, separate your standards stylesheet from your IE stylesheet by using an if IE statement like below:
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="http://www.mysite.com/css/ie.css" />
<![endif]-->
If you separate the ie quirks, your site will validate just fine.
<html>
<body>
<h1 align="center">
<video width="1000" controls>
<source src="video.mp4" type="video/mp4">
</video>
</h1>
</body>
</html>
_x000D_
In crystal report formulafield date function aavailable there pass your date-time format in that You Will get the Date only here
Example: Date({MyTable.dte_QDate})
To toggle the input's disabled attribute was surprisingly complex. The issue for me was twofold:
(1) Remember: the input's "disabled" attribute is NOT a Boolean attribute.
The mere presence of the attribute means that the input is disabled.
However, the Vue.js creators have prepared this... https://vuejs.org/v2/guide/syntax.html#Attributes
(Thanks to @connexo for this... How to add disabled attribute in input text in vuejs?)
(2) In addition, there was a DOM timing re-rendering issue that I was having. The DOM was not updating when I tried to toggle back.
Upon certain situations, "the component will not re-render immediately. It will update in the next 'tick.'"
From Vue.js docs: https://vuejs.org/v2/guide/reactivity.html
The solution was to use:
this.$nextTick(()=>{
this.disableInputBool = true
})
Fuller example workflow:
<div @click="allowInputOverwrite">
<input
type="text"
:disabled="disableInputBool">
</div>
<button @click="disallowInputOverwrite">
press me (do stuff in method, then disable input bool again)
</button>
<script>
export default {
data() {
return {
disableInputBool: true
}
},
methods: {
allowInputOverwrite(){
this.disableInputBool = false
},
disallowInputOverwrite(){
// accomplish other stuff here.
this.$nextTick(()=>{
this.disableInputBool = true
})
}
}
}
</script>
int[] arr = {111, 111, 110, 101, 101, 102, 115, 112};
/* for ascending order */
System.out.println(Arrays.toString(getSortedArray(arr)));
/*for descending order */
System.out.println(Arrays.toString(getSortedArray(arr)));
private int[] getSortedArray(int[] k){
int localIndex =0;
for(int l=1;l<k.length;l++){
if(l>1){
localIndex = l;
while(true){
k = swapelement(k,l);
if(l-- == 1)
break;
}
l = localIndex;
}else
k = swapelement(k,l);
}
return k;
}
private int[] swapelement(int[] ar,int in){
int temp =0;
if(ar[in]<ar[in-1]){
temp = ar[in];
ar[in]=ar[in-1];
ar[in-1] = temp;
}
return ar;
}
private int[] getDescOrder(int[] byt){
int s =-1;
for(int i = byt.length-1;i>=0;--i){
int k = i-1;
while(k >= 0){
if(byt[i]>byt[k]){
s = byt[k];
byt[k] = byt[i];
byt[i] = s;
}
k--;
}
}
return byt;
}
output:-
ascending order:-
101, 101, 102, 110, 111, 111, 112, 115
descending order:-
115, 112, 111, 111, 110, 102, 101, 101
I have added the following on my excel sheet
=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)
Still doesn't seem to work. I get an #N/A
BUT
=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)
Works
for opensuse 12.3 (Dartmouth) (i586) sudo zypper install zlib-devel zlib-devel-static
This is for those who bump into the odd case I did, you CANNOT use the keyword test
in the bundle id.
We were needing to test sharing data through the app group feature and the companion app wasn't developed yet so we simply changed the bundle identifier to test.APP_NAME instead of company.APP_NAME. We set up everything in iTunes Connect and nothing worked right. We then swapped the name to beta.APP_NAME and Xcode was able to manage the app id correctly again.
Normally to fix this issue, verify your provisioning profiles and App Id's have the correct settings, and if your still having trouble to to Xcode -> Preferences -> Accounts -> View Details -> Download All and you should be good.
Hope that helps.
Have a look at View.setVisibility(View.GONE / View.VISIBLE / View.INVISIBLE)
.
From the API docs:
public void setVisibility(int visibility)
Since: API Level 1
Set the enabled state of this view.
Related XML Attributes: android:visibilityParameters:
visibility
One of VISIBLE, INVISIBLE, or GONE.
Note that LinearLayout
is a ViewGroup
which in turn is a View
. That is, you may very well call, for instance, myLinearLayout.setVisibility(View.VISIBLE)
.
This makes sense. If you have any experience with AWT/Swing, you'll recognize it from the relation between Container
and Component
. (A Container
is a Component
.)
The snippet from @Chris J had some issues with margins and overflow. The proposed changes by @YanickRochon and @Joana, based on the fiddel from @Chris J can be found in the following jsfiddle.
That's the CSS code that worked for me:
.modal-dialog {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.modal-content {
height: 100%;
min-height: 100%;
height: auto;
border-radius: 0;
}
My solution based on the answer by @Bill the Lizard.
Note that these functions will return the empty string if the input string contains nothing but whitespace.
const std::string StringUtils::WHITESPACE = " \n\r\t";
std::string StringUtils::Trim(const std::string& s)
{
return TrimRight(TrimLeft(s));
}
std::string StringUtils::TrimLeft(const std::string& s)
{
size_t startpos = s.find_first_not_of(StringUtils::WHITESPACE);
return (startpos == std::string::npos) ? "" : s.substr(startpos);
}
std::string StringUtils::TrimRight(const std::string& s)
{
size_t endpos = s.find_last_not_of(StringUtils::WHITESPACE);
return (endpos == std::string::npos) ? "" : s.substr(0, endpos+1);
}
Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose
Go a simple way to do this :-
Created one class to hold following information
Go the list of sites stored on a ArrayList object. And executed following query to sort it in descending order by Level.
var query = from MyClass object in objCollection
orderby object.Level descending
select object
Once I got the collection sorted in descending order, I wrote following code to get the Object that comes as top row
MyClass topObject = query.FirstRow<MyClass>()
This worked like charm.
May be sometimes upgrading to a superuser might not be a good option. So apart from super user there are lot of other options which you can use. Open your terminal and type the following:
$ sudo su - postgres
[sudo] password for user: (type your password here)
$ psql
postgres@user:~$ psql
psql (10.5 (Ubuntu 10.5-1.pgdg18.04+1))
Type "help" for help.
postgres=# ALTER USER my_user WITH option
Also listing the list of options
SUPERUSER | NOSUPERUSER | CREATEDB | NOCREATEDB | CREATEROLE | NOCREATEROLE |
CREATEUSER | NOCREATEUSER | INHERIT | NOINHERIT | LOGIN | NOLOGIN | REPLICATION|
NOREPLICATION | BYPASSRLS | NOBYPASSRLS | CONNECTION LIMIT connlimit |
[ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password' | VALID UNTIL 'timestamp'
So in command line it will look like
postgres=# ALTER USER my_user WITH LOGIN
OR use an encrypted password.
postgres=# ALTER USER my_user WITH ENCRYPTED PASSWORD '5d41402abc4b2a76b9719d911017c592';
OR revoke permissions after a specific time.
postgres=# ALTER USER my_user WITH VALID UNTIL '2019-12-29 19:09:00';
For:
var str = "hello world!";
To get the resulting string without the first 10 characters and an empty string if the string is less or equal in length to 10 you can use:
var result = str.Length <= 10 ? "" : str.Substring(10);
or
var result = str.Length <= 10 ? "" : str.Remove(0, 10);
First variant being preferred since it needs only one method parameter.
In SQL Server 2008:
Listing a public key in .ssh/authorized_keys is necessary, but not sufficient for sshd (server) to accept it. If your private key is passphrase-protected, you'll need to give ssh (client) the passphrase every time. Or you can use ssh-agent, or a GNOME equivalent.
Your updated trace is consistent with a passphrase-protected private key. See ssh-agent, or use ssh-keygen -p
.
Do this.
$(function(){
var myFunction = function()
{
alert("myFunction called");
}
jQuery(':input').change(myFunction).keyup(myFunction);
});
I boiled my head over this issue and it has happened due to a careless mistake on handling the callbacks. non returned callbacks cause the response to be set twice.!
My program had a code which validate request and query the DB. after validating if error is there, I was calling back the index.js with the validation errors . And if validation passes it goes ahead and hit the db with success/failure.
var error = validateRequestDetails("create",queryReq);
if (error)
callback(error, null);
else
some code
callback(null, success);
What was happening is : Incase validation fails the callback get called and response get set. But not returned. So it still continues the method goes to db and hit success/failure . It calls the same callback again causing the response to be set twice now.
So solution is simple, you need to 'return' the callback so that the method don't continue executing, once the error has occurred and hence set the response object once
var error = validateRequestDetails("create",queryReq);
if (error)
callback(error, null);
return;
else
some code
callback(null, success);
It turns out the best solution for me here was to just reformat the drive. Once reformatted all these problems were no longer problems.
If i understand your question right then,
Yes you can set style of individual element if its id or name is available,
e.g.
if id available then u can get control over the element like,
<input type="submit" value="Go" name="goButton">
var v_obj = document.getElementsById('goButton');
v_obj.setAttribute('style','color:red;background:none');
else if name is available then u can get control over the element like,
<input type="submit" value="Go" name="goButton">
var v_obj = document.getElementsByName('goButton');
v_obj.setAttribute('style','color:red;background:none');
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)
print (d2-d1).days * 24 * 60
I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:
Disable USB debugging
Disable Developer mode
Unplug the device from the USB cable
Re-enable Developer mode
Re-enable USB debugging
Reconnect the USB cable to your device
It is important you do it in this order as it didn't work until it was done in this order.
There is simple code:
echo implode("",array_map(create_function('$s','return substr($s,mt_rand(0,strlen($s)),1);'),array_fill(0,16,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")));
There is a simple guide:
16
to another value, only.The common convention would be to put it in a .sh file that looks like this -
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar;... etc
Note that '\' become '/'.
You could execute as
sh myfile.sh
or set the x bit on the file
chmod +x myfile.sh
and then just call
myfile.sh
[Updated to adapt to modern pandas
, which has isnull
as a method of DataFrame
s..]
You can use isnull
and any
to build a boolean Series and use that to index into your frame:
>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
>>> df.isnull().any(axis=1)
0 False
1 True
2 True
3 False
4 False
dtype: bool
>>> df[df.isnull().any(axis=1)]
0 1 2
1 0 NaN 0
2 0 0 NaN
[For older pandas
:]
You could use the function isnull
instead of the method:
In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
In [57]: df
Out[57]:
0 1 2
0 0 1 2
1 0 NaN 0
2 0 0 NaN
3 0 1 2
4 0 1 2
In [58]: pd.isnull(df)
Out[58]:
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
In [59]: pd.isnull(df).any(axis=1)
Out[59]:
0 False
1 True
2 True
3 False
4 False
leading to the rather compact:
In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]:
0 1 2
1 0 NaN 0
2 0 0 NaN
You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?
Following line will give you an application path:
var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
Above solution is working properly in the following situations:
mkbundle
bundles (no other methods work)try the following code
select * from TableA A
inner join TableB B on A.Column=B.Column
inner join TableC C on A.Column=C.Column
You can achieve that with just one line code that simplify that:
$('#divs').get(0).outerHTML;
As simple as that.
It can also be written this way
this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)
You could maybe add
.print:last-child {
page-break-after: auto;
}
so the last print
element will not get the extra page break.
Do note that the :last-child selector is not supported in IE8, if you're targetting that wretch of a browser.
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
==
does a numeric comparison: it converts both arguments to a number and then compares them. As long as $str1
and $str2
both evaluate to 0 as numbers, the condition will be satisfied.
eq
does a string comparison: the two arguments must match lexically (case-sensitive) for the condition to be satisfied.
"foo" == "bar"; # True, both strings evaluate to 0.
"foo" eq "bar"; # False, the strings are not equivalent.
"Foo" eq "foo"; # False, the F characters are different cases.
"foo" eq "foo"; # True, both strings match exactly.
You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.
There's a good howto here:
https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/
Basically:
If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).
Simplest way to truly remove all non-numeric characters:
echo preg_replace('/\D/', '', $string);
\D
represents "any character that is not a decimal digit"
The following is the more generic solution. It essentially does the same thing (in O(N) order) but on any IEnumberable types and can mixed with types whose property selectors could return null.
public static class LinqExtensions
{
public static T MinBy<T>(this IEnumerable<T> source, Func<T, IComparable> selector)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (selector == null)
{
throw new ArgumentNullException(nameof(selector));
}
return source.Aggregate((min, cur) =>
{
if (min == null)
{
return cur;
}
var minComparer = selector(min);
if (minComparer == null)
{
return cur;
}
var curComparer = selector(cur);
if (curComparer == null)
{
return min;
}
return minComparer.CompareTo(curComparer) > 0 ? cur : min;
});
}
}
Tests:
var nullableInts = new int?[] {5, null, 1, 4, 0, 3, null, 1};
Assert.AreEqual(0, nullableInts.MinBy(i => i));//should pass
You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.
label
is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center
but since the label is only as wide as the text you don't notice.
The best thing to do is to apply a specific width to the label
that is greater than the width of the content - this will give you the results you want.
$('input').on('ifChanged', function(event) {
if($(".checkbox").is(":checked")) {
$value = $(this).val();
}
else if($(".checkbox").is(":not(:checked)")) {
$value= $(this).val();
}
});
When I understand this correctly, you replace the default constructor with a parameterized one and therefore have to describe the JSON keys which are used to call the constructor with.
Before you call setContentView()
, call setTheme(android.R.style...)
and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).
Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)
"Are there any arguments I could use to help me convince him the for loop is acceptable to use?"
No, if your boss is micromanaging to the level of telling you what programming language constructs to use, there's really nothing you can say. Sorry.
The character 0x0C is be invalid in XML 1.0 but would be a valid character in XML 1.1. So unless the xml file specifies the version as 1.1 in the prolog it is simply invalid and you should complain to the producer of this file.
jQuery uses a regex to remove script tags in some cases and I'm pretty sure its devs had a damn good reason to do so. Probably some browser does execute scripts when inserting them using innerHTML
.
Here's the regex:
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi
And before people start crying "but regexes for HTML are evil": Yes, they are - but for script tags they are safe because of the special behaviour - a <script>
section may not contain </script>
at all unless it should end at this position. So matching it with a regex is easily possible. However, from a quick look the regex above does not account for trailing whitespace inside the closing tag so you'd have to test if </script
etc. will still work.
The previously linked solution is a horrible piece of code; nearly every line contains a bug. Use fgetcsv instead:
<?php
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
Select Database , select table and click icon as shown in picture.
Convert the message to a character array, then use a for loop to change it to a string
string message = "This Is A Test";
string[] result = new string[message.Length];
char[] temp = new char[message.Length];
temp = message.ToCharArray();
for (int i = 0; i < message.Length - 1; i++)
{
result[i] = Convert.ToString(temp[i]);
}
Open a command prompt as an Administrator.
Enter slmgr /upk
and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.
Enter slmgr /cpky
and wait for this to complete. This will remove the product key from the registry if it's still there.
Enter slmgr /rearm
and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.
This should put the system back to a pre-key state.
Hope this helps you out!
\d{1,2}[,.]\d{1,2}
\d means a digit, the {1,2} part means 1 or 2 of the previous character (\d in this case) and the [,.] part means either a comma or dot.
For those using NetBeans with SVN, there is an option 'Subversion > Export'.
A switch
statement can only be used for integral values, not for values of user-defined type. And even if it could, your input operation doesn't work, either.
You might want this:
#include <string>
#include <iostream>
std::string input;
if (!std::getline(std::cin, input)) { /* error, abort! */ }
if (input == "Option 1")
{
// ...
}
else if (input == "Option 2")
{
// ...
}
// etc.
Os
You can list all files in the current directory using os.listdir
:
import os
for filename in os.listdir(os.getcwd()):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Glob
Or you can list only some files, depending on the file pattern using the glob
module:
import glob
for filename in glob.glob('*.txt'):
with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
It doesn't have to be the current directory you can list them in any path you want:
path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
# do your stuff
Pipe
Or you can even use the pipe as you specified using fileinput
import fileinput
for line in fileinput.input():
# do your stuff
And then use it with piping:
ls -1 | python parse.py
Using num_holes=None
as the default is fine if you are going to have just __init__
.
If you want multiple, independent "constructors", you can provide these as class methods. These are usually called factory methods. In this case you could have the default for num_holes
be 0
.
class Cheese(object):
def __init__(self, num_holes=0):
"defaults to a solid cheese"
self.number_of_holes = num_holes
@classmethod
def random(cls):
return cls(randint(0, 100))
@classmethod
def slightly_holey(cls):
return cls(randint(0, 33))
@classmethod
def very_holey(cls):
return cls(randint(66, 100))
Now create object like this:
gouda = Cheese()
emmentaler = Cheese.random()
leerdammer = Cheese.slightly_holey()
There are several issues here.
DataContext="{Binding Employee}"
because it's a complex object which can't be assigned as string. So you have to use <Window.DataContext></Window.DataContext>
syntax.{Binding Employee}
is invalid here, you just have to specify an object.<Window.DataContext> <local:Employee/> </Window.DataContext>
know that you are creating a new instance of the Employee class and assigning it as the data context object. You may well have nothing in default constructor so nothing will show up. But then how do you manage it in code behind file? You have typecast the DataContext.
private void my_button_Click(object sender, RoutedEventArgs e)
{
Employee e = (Employee) DataContext;
}
A second way is to assign the data context in the code behind file itself. The advantage then is your code behind file already knows it and can work with it.
public partial class MainWindow : Window
{
Employee employee = new Employee();
public MainWindow()
{
InitializeComponent();
DataContext = employee;
}
}
Activation by system properties can be done as follows
<activation>
<property>
<name>foo</name>
<value>bar</value>
</property>
</activation>
And run the mvn build with -D to set system property
mvn clean install -Dfoo=bar
This method also helps select profiles in transitive dependency of project artifacts.
Download Xcode, which is free with an ADC online membership (also free):
Actually I found out that the container of the image tag need to have a height in order to keep the ratio of the image. for example>
.container{display:flex; height:100%;} img{width:100%;height:auto;}
then in your html your container will wrap the tag image
<div class="container"><img src="image.jpg" alt="image" /></div>
this work for IE and other browsers
this can be done very easily with HTML 5, see this link http://www.html5rocks.com/en/tutorials/file/dndfiles/
Its not recommended to overwrite bootstrap file, just in your local style.css use
body{background: your color !important;
here !important declaration overwrite bootstrap value.
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
unbind() doesn't work with hardcoded inline events.
So, for example, if you want to unbind the mouseover event from
<div id="some_div" onmouseover="do_something();">
, I found that $('#some_div').attr('onmouseover','')
is a quick and dirty way to achieve it.
Its generally
'C:\Users\user-name\AppData\Local\Programs\Python\Python-version'
or try using (in cmd )
where python
Straight from the Java Language Specification:
A method that is
native
is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN,or assembly language. The body of anative
method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.
I believe Mica's way deserves the rank of answer, since is not visible enough as a comment:
\begin{tikzpicture}[font=\small]
Try like this
String sql = "SELECT t FROM table t";
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();
It should work
UPDATE*
You can also try like this
query.setMaxResults(1).getResultList();
From Primitives Data Types:
float:
Thefloat
data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations forbyte
andshort
, use afloat
(instead ofdouble
) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings coversBigDecimal
and other useful classes provided by the Java platform.
double
: Thedouble
data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
For the range of values, see the section 4.2.3 Floating-Point Types, Formats, and Values of the JLS.
I've found the very simple answer: isAdded()
:
Return
true
if the fragment is currently added to its activity.
@Override
protected void onPostExecute(Void result){
if(isAdded()){
getResources().getString(R.string.app_name);
}
}
To avoid onPostExecute
from being called when the Fragment
is not attached to the Activity
is to cancel the AsyncTask
when pausing or stopping the Fragment
. Then isAdded()
would not be necessary anymore. However, it is advisable to keep this check in place.
Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.
var closedStatusId = @(Model.ClosedStatusId);
If you aren't allowing the column to be Null you need to provide a default to populate existing rows. e.g.
ALTER TABLE dbo.YourTbl ADD
newcol int NOT NULL CONSTRAINT DF_YourTbl_newcol DEFAULT 0
On Enterprise Edition this is a metadata only change since 2012
How do I invoke a maven task without leaving vi?
Maven is no different than any other shell command:
:!mvn
You can :set makeprg=mvn
if you already have a favourite key mapping for :make
.
Can I get code completion?
Yes, eclim is great, a bridge between vim's editing efficiency and Eclipse's Java language-specific awareness.
<C-n>
and <C-p>
are not-so-great, but amazingly helpful.
How's the syntax highlighting?
More than good enough for a regex-based highligher.
You may want to consider tools for other vim+java purposes, like code templates (snippetEmu—default snippets suck, but customizability shines), searching for usages and going to declarations (eclim, grep, ctags), generating getters and setters (java_getset, or eclim), automatic imports (eclim). You might also need a java shell for quick experiments (the BeanShell, a.k.a. bsh
).
Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)
Try turning on WP Debug. If this is happening due to a PHP error (which I bet that it is), you will be able to see what's going on and fix the error.
Just replace localhost
with 127.0.0.1
.
(The answer is based on answers of other people on this page.)
Set data to this:
data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
this
is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle {
int x;
circle(int x){
this.x =x;
//class variable =local variable
}
}
this
can also be use to call one constructor from another constructor. e.g.:
public class circle {
int x;
circle() {
this(1);
}
circle(int x) {
this.x = x;
}
}
Outside of character classes, it is conventional not to escape hyphens. If I saw an escaped hyphen outside of a character class, that would suggest to me that it was written by someone who was not very comfortable with regexes.
Inside character classes, I don't think one way is conventional over the other; in my experience, it usually seems to be to put either first or last, as in [-._:]
or [._:-]
, to avoid the backslash; but I've also often seen it escaped instead, as in [._\-:]
, and I wouldn't call that unconventional.
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www. I just changed the statement in bin/www.
Fix: Unlock your device before running it.
Hi Guys: Think I may have a fix for this:
Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!
This works at the moment (Oct. 2016), but I can't guarantee how long it will last:
https://www.facebook.com/sharer.php?caption=[caption]&description=[description]&u=[website]&picture=[image-url]
No, these defines are compiler dependent. What you can do, use your own set of defines, and set them on the Makefile. See this thread for more info.
I usually combine CSS and JavaScript approaches, so that it works without JavaScript in all browsers but IE6/7, and in IE6/7 with JavaScript on (but not off), since they does not support the :last-child
pseudo-class.
$("li:last-child").addClass("last-child");
li:last-child,li.last-child{ /* ... */ }
Simple One Liners:
If you want UTF8 text hash:
const hash = require('crypto').createHash('sha256').update('Hash me', 'utf8').digest('hex');
If you want to get the same hash with Python, PHP, Perl, Github:
const hash = require('crypto').createHash('sha256').update('Hash me', 'binary').digest('hex');
You can also replace 'sha256'
with 'sha1'
, 'md5'
, 'sha256'
, 'sha512'
You can simply use MaterialAlertDialogBuilder to create custom dialog with rounded corners.
First create a style for the material dialog like this :
<style name="MyRounded.MaterialComponents.MaterialAlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.App.CustomDialog.Rounded
</item>
<item name="colorSurface">@color/YOUR_COLOR</item>
</style>
<style name="ShapeAppearanceOverlay.App.CustomDialog.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">10dp</item>
</style>
then create a Alert Dialog object in Java class like this :
AlertDialog alertDialog = new MaterialAlertDialogBuilder(this,R.style.MyRounded_MaterialComponents_MaterialAlertDialog) // for fragment you can use getActivity() instead of this
.setView(R.layout.custom_layout) // custom layout is here
.show();
final EditText editText = alertDialog.findViewById(R.id.custom_layout_text); // access to text view of custom layout
Button btn = alertDialog.findViewById(R.id.custom_layout_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: " + editText.getText().toString());
}
});
That's all you need to do.
I just want to build upon Serpens answer and add the line:
logger.setLevel('DEBUG')
This will allow you to chose what level of message gets logged.
For example in Serpens example,
logger.info('Info message')
Will not get recorded as it defaults to only recording Warnings and above.
More about levels used can be read about here
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException
if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db
object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Within AppDelegate, this has globally changed the format of the NavBar:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().barTintColor = UIColor.redColor()
UINavigationBar.appearance().translucent = false
UINavigationBar.appearance().clipsToBounds = false
UINavigationBar.appearance().backgroundColor = UIColor.redColor()
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : (UIFont(name: "FONT NAME", size: 18))!, NSForegroundColorAttributeName: UIColor.whiteColor()] }
Haven't managed to implement anything different on a specific VC, but this will help 90% of people
Try this:
<SCRIPT LANGUAGE="JavaScript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
</SCRIPT>
</head>
<body>
<p>To sign up for the Excel workshop please fill out the form below:
</p>
<form onSubmit="WriteToFile(this)">
Type your first name:
<input type="text" name="FirstName" size="20">
<br>Type your last name:
<input type="text" name="LastName" size="20">
<br>
<input type="submit" value="submit">
</form>
This will work only on IE
In case of gray image, I am using this function and it works fine! however you must take care about the function features ;)
CvMat * src= cvCreateMat(300,300,CV_32FC1);
IplImage *dist= cvCreateImage(cvGetSize(dist),IPL_DEPTH_32F,3);
cvConvertScale(src, dist, 1, 0);
The #define
allows you to establish a value in a header that would otherwise compile to size-greater-than-zero. Your headers should not compile to size-greater-than-zero.
// File: MyFile.h
// This header will compile to size-zero.
#define TAX_RATE 0.625
// NO: static const double TAX_RATE = 0.625;
// NO: extern const double TAX_RATE; // WHAT IS THE VALUE?
EDIT: As Neil points out in the comment to this post, the explicit definition-with-value in the header would work for C++, but not C.
I tried all the above solutions but not working for me. I tried update libraries by goto project structure > app. And it works for me! Hope this answer helpful to someone.
This is, by far, the fastest way I have seen it done. Plus, it does it all without adding, removing, or changing elements on the page.
function escapeHTML(unsafeText) {
let div = document.createElement('div');
div.innerText = unsafeText;
return div.innerHTML;
}
With an angular {{expression}} you can add the old user or user.id value to the ng-change attribute as a literal string:
<select ng-change="updateValue(user, '{{user.id}}')"
ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>
On ngChange, the 1st argument to updateValue will be the new user value, the 2nd argument will be the literal that was formed when the select-tag was last updated by angular, with the old user.id value.
A Quick and dirty way: Just write your query as db.getCollection('collection').find({}).toArray()
and right click Copy JSON
. Paste the data in the editor of your choice.
There is no need for jQuery here, regular JavaScript will do:
var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);
Or, the .split()
and .pop()
version:
var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();
Or, the regex version (several variants of this):
var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
Function expressions in the JSON are completely possible, just do not forget to wrap it in double quotes. Here is an example taken from noSQL database design:
{_x000D_
"_id": "_design/testdb",_x000D_
"views": {_x000D_
"byName": {_x000D_
"map": "function(doc){if(doc.name){emit(doc.name,doc.code)}}"_x000D_
}_x000D_
}_x000D_
}
_x000D_
FYI: I had the same issue with Visual Studio 2015. After many of hours trying, I can now do msbuild myproject.csproj /p:DeployOnBuild=true /p:PublishProfile=myprofile
.
I had to edit my .csproj file to get it working. It contained a line like this:
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets"
Condition="false" />
I changed this line as follows:
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v14.0\WebApplications\Microsoft.WebApplication.targets" />
(I changed 10.0 to 14.0, not sure whether this was necessary. But I definitely had to remove the condition part.)
I have this query snipet for SQLServer but I think It can be used in others DBMS with little changes:
DELETE
FROM Table
WHERE Table.idTable IN (
SELECT MAX(idTable)
FROM idTable
GROUP BY field1, field2, field3
HAVING COUNT(*) > 1)
I forgot to tell you that this query doesn't remove the row with the lowest id of the duplicated rows. If this works for you try this query:
DELETE
FROM jobs
WHERE jobs.id IN (
SELECT MAX(id)
FROM jobs
GROUP BY site_id, company, title, location
HAVING COUNT(*) > 1)
Most of the existing answers here are impractical because they totally ignore the real-world usage of addresses like:
First, a digression into terminology. What are these addresses? Are they valid URLs?
Historically, the answer was "no". According to RFC 3986, from 2005, such addresses are not URIs (and therefore not URLs, since URLs are a type of URIs). Per the terminology of 2005 IETF standards, we should properly call them IRIs (Internationalized Resource Identifiers), as defined in RFC 3987, which are technically not URIs but can be converted to URIs simply by percent-encoding all non-ASCII characters in the IRI.
Per modern spec, the answer is "yes". The WHATWG Living Standard simply classifies everything that would previously be called "URIs" or "IRIs" as "URLs". This aligns the specced terminology with how normal people who haven't read the spec use the word "URL", which was one of the spec's goals.
Per this newer meaning of "URL", what characters are allowed? In many parts of the URL, such as the query string and path, we're allowed to use arbitrary "URL units", which are
What are "URL code points"?
The URL code points are ASCII alphanumeric, U+0021 (!), U+0024 ($), U+0026 (&), U+0027 ('), U+0028 LEFT PARENTHESIS, U+0029 RIGHT PARENTHESIS, U+002A (*), U+002B (+), U+002C (,), U+002D (-), U+002E (.), U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+003F (?), U+0040 (@), U+005F (_), U+007E (~), and code points in the range U+00A0 to U+10FFFD, inclusive, excluding surrogates and noncharacters.
(Note that the list of "URL code points" doesn't include %
, but that %
s are allowed in "URL code units" if they're part of a percent-encoding sequence.)
The only place I can spot where the spec permits the use of any character that's not in this set is in the host, where IPv6 addresses are enclosed in [
and ]
characters. Everywhere else in the URL, either URL units are allowed or some even more restrictive set of characters.
For the sake of history, and since it's not explored fully elsewhere in the answers here, let's examine was allowed under the older pair of specs.
First of all, we have two types of RFC 3986 reserved characters:
:/?#[]@
, which are part of the generic syntax for a URI defined in RFC 3986!$&'()*+,;=
, which aren't part of the RFC's generic syntax, but are reserved for use as syntactic components of particular URI schemes. For instance, semicolons and commas are used as part of the syntax of data URIs, and &
and =
are used as part of the ubiquitous ?foo=bar&qux=baz
format in query strings (which isn't specified by RFC 3986).Any of the reserved characters above can be legally used in a URI without encoding, either to serve their syntactic purpose or just as literal characters in data in some places where such use could not be misinterpreted as the character serving its syntactic purpose. (For example, although /
has syntactic meaning in a URL, you can use it unencoded in a query string, because it doesn't have meaning in a query string.)
RFC 3986 also specifies some unreserved characters, which can always be used simply to represent data without any encoding:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~
Finally, the %
character itself is allowed for percent-encodings.
That leaves only the following ASCII characters that are forbidden from appearing in a URL:
"<>\^`{|}
Every other character from ASCII can legally feature in a URL.
Then RFC 3987 extends that set of unreserved characters with the following unicode character ranges:
%xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
/ %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
/ %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
/ %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
/ %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
/ %xD0000-DFFFD / %xE1000-EFFFD
These block choices from the old spec seem bizarre and arbitrary given the latest Unicode block definitions; this is probably because the blocks have been added to in the decade since RFC 3987 was written.
Finally, it's perhaps worth noting that simply knowing which characters can legally appear in a URL isn't sufficient to recognise whether some given string is a legal URL or not, since some characters are only legal in particular parts of the URL. For example, the reserved characters [
and ]
are legal as part of an IPv6 literal host in a URL like http://[1080::8:800:200C:417A]/foo but aren't legal in any other context, so the OP's example of http://example.com/file[/].html
is illegal.
create table employee
(
empid int,
empname varchar(40),
designation varchar(30),
hiredate datetime,
Bsalary int,
depno constraint emp_m foreign key references department(depno)
)
We should have an primary key to create foreign key or relationship between two or more table .
Here's how you could set a custom cookie value for the request:
var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("foo", "bar"),
new KeyValuePair<string, string>("baz", "bazinga"),
});
cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
var result = await client.PostAsync("/test", content);
result.EnsureSuccessStatusCode();
}
If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning
useEffect(() => {
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
fetchBusinesses();
}, []);
If however you are using fetchBusinesses outside of render, you must note two things
fetchBusinesses
as a method when it's used during mount with its enclosing closure?To sum it up I would say that if you are using fetchBusinesses
outside of useEffect
you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps
otherwise you can move the method inside of useEffect
To disable the rule you would write it like
useEffect(() => {
// other code
...
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
Pattern satisfy, these below criteria
^(?!.*([A-Za-z0-9]))(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$
The ScriptIgnoreAttribute
class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.
You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.
I think it would be easier using this CLR Stored procedure SQL-APIConsumer:
exec [dbo].[APICaller_POST]
@URL = 'http://localhost:5000/api/auth/login'
,@BodyJson = '{"Username":"gdiaz","Password":"password"}'
It has multiple procedures that allows you calling API that required a parameters and even passing multiples headers and tokens authentications.
If you're attempting to start a SERVICE rather than activity, this worked for me:
Intent intent = new Intent();
intent.setClassName("com.example.otherapplication", "com.example.otherapplication.ServiceName");
context.startService(intent);
If you use the intent.setComponent(...) method as mentioned in other answers, you may get an "Implicit intents with startService are not safe" warning.
The event is called beforeunload
, so you can assign a function to window.onbeforeunload
.
? .exe and dll are the compiled version of c# code which are also called as assemblies.
? .exe is a stand alone executable file, which means it can executed directly.
? .dll is a reusable component which cannot be executed directly and it requires other programs to execute it.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
var locations = ["http://webPage1.com", "http://webPage2.com"];
var len = locations.length;
var iframe = $('#frame');
var i = 0;
setInterval(function () {
iframe.attr('src', locations[++i % len]);
}, 30000);
});
</script>
</head>
<body>
<iframe id="frame"></iframe>
</body>
</html>
I tried most of the suggestions, and none of them worked. I didn't get a chance to try /resetuserdata. Finally I reinstalled the plugin and uninstalled it again, and the windows went away.
delete them using git-rm
, and then add .DS_Store to .gitignore
to stop them getting added again. You can also use blueharvest to stop them getting created all together
Little Edit
Try adding
return new JavascriptResult() { Script = "alert('Successfully registered');" };
in place of
return RedirectToAction("Index");
Using the below line
SELECT LEFT(subject , 10) FROM tbl
var expressionWithoutQuotes = '';
for(var i =0; i<length;i++){
if(expressionDiv.charAt(i) != '"'){
expressionWithoutQuotes += expressionDiv.charAt(i);
}
}
This may work for you.
Try to uninstall python3.7.3 using this:-
https://huybien.com/how-to-completely-uninstall-python-on-macos/
var is a statement... so it's a reserved word... So just call it another way. And that's a better way of doing it (=== is better than ==)
if(typeof array[name] !== 'undefined') {
alert("Has var");
} else {
alert("Doesn't have var");
}
Maven Eclipse plugin installation step by step:
Open Eclipse IDE Click Help -> Install New Software Click Add button at top right corner At pop up: fill up Name as you want and Location as http://download.eclipse.org/technology/m2e/milestones/1.0 Now click OK And follow the instruction
In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:
<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>
Where MyActivity
is the one you want to stay in landscape.
The android:configChanges=...
line prevents onResume()
, onPause()
from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.
Note: keyboardHidden
and orientation
are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation
.
Signed variables can be 0, positive or negative.
Unsigned variables can be 0 or positive.
Unsigned variables are used sometimes because more bits can be used to represent the actual value. Giving you a larger range. Also you can ensure that a negative value won't be passed to your function for example.
if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
OR
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
ImageLocation = @"c:\Images\test.jpg",
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
i'm not sure where you put images in your folder structure but you can find the path as bellow
picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");
Yes it is possible.
You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:
Field privateField = Test.class.getDeclaredField("str");
Additionally, you need to set this Field to be accessible, if you want to access a private field:
privateField.setAccessible(true);
Once that's done, you can use the get method on the Field instance, to access the value of the str field.
Try using MAX
with a GROUP BY
.
SELECT u.userName, MAX(c.carPrice)
FROM users u
LEFT JOIN cars c ON u.id = c.belongsToUser
WHERE u.id = 4;
GROUP BY u.userName;
GROUP BY
The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, ...) that will be applied to each group of records in turn. The database will return a single result record for each grouping.
For example, if we have a set of records representing temperatures over time and location in a table like this:
Location Time Temperature
-------- ---- -----------
London 12:00 10.0
Bristol 12:00 12.0
Glasgow 12:00 5.0
London 13:00 14.0
Bristol 13:00 13.0
Glasgow 13:00 7.0
...
Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:
SELECT Location, MAX(Temperature)
FROM Temperatures
GROUP BY Location;
For shared libraries libNAME.so the -D switch was necessary to see symbols in my Linux
nm -D libNAME.so
and for static library as reported by others
nm -g libNAME.a
Don’t Use jquery-latest.js
This file is no longer updated (it'll be on v1.11.1 forever). Furthermore it has a very short cache life, (wiping out the benefits of using a CDN) so you'd be better of selecting a version of jQuery instead.
More details on the jQuery blog: http://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/
this
Consider the following function:
function foo() {
console.log("bar");
console.log(this);
}
foo(); // calling the function
Note that we are running this in the normal mode, i.e. strict mode is not used.
When running in a browser, the value of this
would be logged as window
. This is because window
is the global variable in a web browser's scope.
If you run this same piece of code in an environment like node.js, this
would refer to the global variable in your app.
Now if we run this in strict mode by adding the statement "use strict";
to the beginning of the function declaration, this
would no longer refer to the global variable in either of the environments. This is done to avoid confusions in strict mode. this
would, in this case just log undefined
, because that is what it is, it is not defined.
In the following cases, we would see how to manipulate the value of this
.
There are different ways to do this. If you have called native methods in Javascript like forEach
and slice
, you should already know that the this
variable in that case refers to the Object
on which you called that function (Note that in javascript, just about everything is an Object
, including Array
s and Function
s). Take the following code for example.
var myObj = {key: "Obj"};
myObj.logThis = function () {
// I am a method
console.log(this);
}
myObj.logThis(); // myObj is logged
If an Object
contains a property which holds a Function
, the property is called a method. This method, when called, will always have it's this
variable set to the Object
it is associated with. This is true for both strict and non-strict modes.
Note that if a method is stored (or rather, copied) in another variable, the reference to this
is no longer preserved in the new variable. For example:
// continuing with the previous code snippet
var myVar = myObj.logThis;
myVar();
// logs either of window/global/undefined based on mode of operation
Considering a more commonly practical scenario:
var el = document.getElementById('idOfEl');
el.addEventListener('click', function() { console.log(this) });
// the function called by addEventListener contains this as the reference to the element
// so clicking on our element would log that element itself
new
keywordConsider a constructor function in Javascript:
function Person (name) {
this.name = name;
this.sayHello = function () {
console.log ("Hello", this);
}
}
var awal = new Person("Awal");
awal.sayHello();
// In `awal.sayHello`, `this` contains the reference to the variable `awal`
How does this work? Well, let's see what happens when we use the new
keyword.
new
keyword would immediately initialize an Object
of type Person
.Object
has its constructor set to Person
. Also, note that typeof awal
would return Object
only.Object
would be assigned the prototype of Person.prototype
. This means that any method or property in the Person
prototype would be available to all instances of Person
, including awal
.Person
itself is now invoked; this
being a reference to the newly constructed object awal
.Pretty straightforward, eh?
Note that the official ECMAScript spec nowhere states that such types of functions are actual constructor
functions. They are just normal functions, and new
can be used on any function. It's just that we use them as such, and so we call them as such only.
call
and apply
So yeah, since function
s are also Objects
(and in-fact first class variables in Javascript), even functions have methods which are... well, functions themselves.
All functions inherit from the global Function
, and two of its many methods are call
and apply
, and both can be used to manipulate the value of this
in the function on which they are called.
function foo () { console.log (this, arguments); }
var thisArg = {myObj: "is cool"};
foo.call(thisArg, 1, 2, 3);
This is a typical example of using call
. It basically takes the first parameter and sets this
in the function foo
as a reference to thisArg
. All other parameters passed to call
is passed to the function foo
as arguments.
So the above code will log {myObj: "is cool"}, [1, 2, 3]
in the console. Pretty nice way to change the value of this
in any function.
apply
is almost the same as call
accept that it takes only two parameters: thisArg
and an array which contains the arguments to be passed to the function. So the above call
call can be translated to apply
like this:
foo.apply(thisArg, [1,2,3])
Note that call
and apply
can override the value of this
set by dot method invocation we discussed in the second bullet.
Simple enough :)
bind
!bind
is a brother of call
and apply
. It is also a method inherited by all functions from the global Function
constructor in Javascript. The difference between bind
and call
/apply
is that both call
and apply
will actually invoke the function. bind
, on the other hand, returns a new function with the thisArg
and arguments
pre-set. Let's take an example to better understand this:
function foo (a, b) {
console.log (this, arguments);
}
var thisArg = {myObj: "even more cool now"};
var bound = foo.bind(thisArg, 1, 2);
console.log (typeof bound); // logs `function`
console.log (bound);
/* logs `function () { native code }` */
bound(); // calling the function returned by `.bind`
// logs `{myObj: "even more cool now"}, [1, 2]`
See the difference between the three? It is subtle, but they are used differently. Like call
and apply
, bind
will also over-ride the value of this
set by dot-method invocation.
Also note that neither of these three functions do any change to the original function. call
and apply
would return the value from freshly constructed functions while bind
will return the freshly constructed function itself, ready to be called.
Sometimes, you don't like the fact that this
changes with scope, especially nested scope. Take a look at the following example.
var myObj = {
hello: function () {
return "world"
},
myMethod: function () {
// copy this, variable names are case-sensitive
var that = this;
// callbacks ftw \o/
foo.bar("args", function () {
// I want to call `hello` here
this.hello(); // error
// but `this` references to `foo` damn!
// oh wait we have a backup \o/
that.hello(); // "world"
});
}
};
In the above code, we see that the value of this
changed with the nested scope, but we wanted the value of this
from the original scope. So we 'copied' this
to that
and used the copy instead of this
. Clever, eh?
Index:
this
by default?new
keyword?this
with call
and apply
?bind
.this
to solve nested-scope issues.Just for completeness:
There is another solution, I would recommend: subtree merging.
In contrast to submodules, it's easier to maintain. You would create each repository the normal way. While in your main repository, you want to merge the master (or any other branch) of another repository in a directory of your main directory.
$ git remote add -f OtherRepository /path/to/that/repo
$ git merge -s ours --no-commit OtherRepository/master
$ git read-tree --prefix=AnyDirectoryToPutItIn/ -u OtherRepository/master
$ git commit -m "Merge OtherRepository project as our subdirectory"`
Then, in order to pull the other repository into your directory (to update it), use the subtree merge strategy:
$ git pull -s subtree OtherRepository master
I'm using this method for years now, it works :-)
More about this way including comparing it with sub modules may be found in this git howto doc.
Per this PowerShell blog post, you can create an alias to define a ?:
operator:
set-alias ?: Invoke-Ternary -Option AllScope -Description "PSCX filter alias"
filter Invoke-Ternary ([scriptblock]$decider, [scriptblock]$ifTrue, [scriptblock]$ifFalse)
{
if (&$decider) {
&$ifTrue
} else {
&$ifFalse
}
}
Use it like this:
$total = ($quantity * $price ) * (?: {$quantity -le 10} {.9} {.75})
Escape the backslash:
if message.value[0] == "/" or message.value[0] == "\\":
From the documentation:
The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
Here is the BSD implementation:
int
strcmp(s1, s2)
register const char *s1, *s2;
{
while (*s1 == *s2++)
if (*s1++ == 0)
return (0);
return (*(const unsigned char *)s1 - *(const unsigned char *)(s2 - 1));
}
Once there is a mismatch between two characters, it just returns the difference between those two characters.
Since Fedora 22 yum has been deprecated so the commands given in other answers will actually fire up 'Dandified yum' i.e. dnf
. So the new command to install g++ in recent distributions is
su -c "dnf install gcc-c++"
As of Nov 2015 this installs the 5.1.1 version.
Also note that in Fedora 23 when I gave the command g++ -v
, Fedora automatically asked me if I want to install gcc-c++ package. I think thats nice.(After the install it also ran the command g++ -v
for me)
Only nit pick that I can do about it is that instead of a progress indicator you just get * Downloading packages...
message which you may not like if you are on a slow internet connection.
There is also array_replace
, where an original array is modified by other arrays preserving the key => value association without creating duplicate keys.
I have an optimised implementation you could use in UnconstrainedMelody. Effectively it's just caching the list of names, but it's doing so in a nice, strongly typed, generically constrained way :)
Look into the theme attributes buttonBarStyle
, buttonBarButtonStyle
, and borderlessButtonStyle
.
public void convert(int s)
{
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}
public static void main(String args[])
{
LocalEx n=new LocalEx();
n.convert(10000);
}
Many users suggested that you use
echo json_encode($results, JSON_PRETTY_PRINT);
Which is absolutely right. But it's not enough, the browser needs to understand the type of data, you can specify the header just before echo-ing the data back to the user.
header('Content-Type: application/json');
This will result in a well formatted output.
Or, if you like extensions you can use JSONView for Chrome.
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
Execute these commands in the terminal (excluding the lines with hashtags - they're comments):
# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*
If you would like to delete all projects:
rm -Rf ~/AndroidStudioProjects
To remove gradle related files (caches & wrapper)
rm -Rf ~/.gradle
Use the below command to delete all Android Virtual Devices(AVDs) and keystores.
Note: This folder is used by other Android IDEs as well, so if you still using other IDE you may not want to delete this folder)
rm -Rf ~/.android
To delete Android SDK tools
rm -Rf ~/Library/Android*
Emulator Console Auth Token
rm -Rf ~/.emulator_console_auth_token
Thanks to those who commented/improved on this answer!
rm
are case-sensitive1 (as with most other commands), which means that the f
flag must be in lower case. However, the r
flag can also be capitalised.rm
can be either combined together or separated. They don't have to be combined.r
flag indicates that the rm
command should-
attempt to remove the file hierarchy rooted in each file argument. - DESCRIPTION section on the manpage for
rm
(Seeman rm
for more info)
f
flag indicates that the rm
command should-
attempt to remove the files without prompting for confirmation, regardless of the file's permissions. - DESCRIPTION section on the manpage for
rm
(Seeman rm
for more info)
You can throw your own custom errors by extending the Exception class.
class CustomException : Exception {
[string] $additionalData
CustomException($Message, $additionalData) : base($Message) {
$this.additionalData = $additionalData
}
}
try {
throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
# NOTE: To access your custom exception you must use $_.Exception
Write-Output $_.Exception.additionalData
# This will produce the error message: Didn't catch it the second time
throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}
var depthead = (from s in db.M_Users
join m in db.M_User_Types on s.F_User_Type equals m.UserType_Id
where m.UserType_Name.ToUpper().Trim().Contains("DEPARTMENT HEAD")
select new {s.FullName,s.F_User_Type,s.userId,s.UserCode }
).OrderBy(d => d.userId).ToList();
Model.AvailableDeptHead.Add(new SelectListItem { Text = "Select", Value = "0" });
for (int i = 0; i < depthead.Count; i++)
Model.AvailableDeptHead.Add(new SelectListItem { Text = depthead[i].UserCode + " - " + depthead[i].FullName, Value = Convert.ToString(depthead[i].userId) });
When in trouble what means what:
?%timeit
or ??timeit
To get the details:
Usage, in line mode:
%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
%%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
code
code...
Time execution of a Python statement or expression using the timeit
module. This function can be used both as a line and cell magic:
- In line mode you can time a single-line statement (though multiple
ones can be chained with using semicolons).
- In cell mode, the statement in the first line is used as setup code
(executed but not timed) and the body of the cell is timed. The cell
body has access to any variables created in the setup code.
those are routes you're passing in
<%= Html.ActionLink("Delete", "Delete",
new { id = item.storyId },
new { onclick = "return confirm('Are you sure you wish to delete this article?');" }) %>
The overloaded method you're looking for is this one:
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
Object routeValues,
Object htmlAttributes
)
The C++ syntax is like this:
class Bar : public Foo {
// ...
void printStuff() {
Foo::printStuff(); // calls base class' function
}
};
For those situations where width of the items you do want to flex-end
is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start
with flex:1
This will cause the pseudo flex-start
item to fill the container, just format it to text-align:left
or whatever.
To do this, I would strongly consider wrapping a Text
component in a TouchableOpacity
. When a TouchableOpacity
is touched, it fades (becomes less opaque). This gives the user immediate feedback when touching the text and provides for an improved user experience.
You can use the onPress
property on the TouchableOpacity
to make the link happen:
<TouchableOpacity onPress={() => Linking.openURL('http://google.com')}>
<Text style={{color: 'blue'}}>
Google
</Text>
</TouchableOpacity>
You'll do it the same way you would apply a css selector. For instanse you can do
$("#mydiv > .myclass")
or
$("#mydiv .myclass")
The last one will match every myclass inside myDiv, including myclass inside myclass.
I had the same problem. I found that this is because the Maven script looks at the CurrentJDK link below and finds a 1.6 JDK. Even if you install the latest JDK this is not resolved. While you could just set JAVA_HOME in your $HOME/.bash_profile script I chose to fix the symbolic link instead as follows:
ls -l /System/Library/Frameworks/JavaVM.framework/Versions/
total 64
lrwxr-xr-x 1 root wheel 10 30 Oct 16:18 1.4 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 30 Oct 16:18 1.4.2 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 30 Oct 16:18 1.5 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 30 Oct 16:18 1.5.0 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 30 Oct 16:18 1.6 -> CurrentJDK
lrwxr-xr-x 1 root wheel 10 30 Oct 16:18 1.6.0 -> CurrentJDK
drwxr-xr-x 9 root wheel 306 11 Nov 21:20 A
lrwxr-xr-x 1 root wheel 1 30 Oct 16:18 Current -> A
lrwxr-xr-x 1 root wheel 59 30 Oct 16:18 CurrentJDK -> /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents
Notice that CurrentJDK points at 1.6.0.jdk
To fix it I ran the following commands (you should check your installed version and adapt accordingly).
sudo rm /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/ /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
I have a very similar problem. Actually the problem is deeper as I thought. I am using jquery $.post
which uses Content-Type:application/x-www-form-urlencoded; charset=UTF-8
as default. Unfortunately I based my system on that and when I needed a complex object as a @RequestParam
I couldn't just make it happen.
In my case I am trying to send user preferences with something like;
$.post("/updatePreferences",
{id: 'pr', preferences: p},
function (response) {
...
On client side the actual raw data sent to the server is;
...
id=pr&preferences%5BuserId%5D=1005012365&preferences%5Baudio%5D=false&preferences%5Btooltip%5D=true&preferences%5Blanguage%5D=en
...
parsed as;
id:pr
preferences[userId]:1005012365
preferences[audio]:false
preferences[tooltip]:true
preferences[language]:en
and the server side is;
@RequestMapping(value = "/updatePreferences")
public
@ResponseBody
Object updatePreferences(@RequestParam("id") String id, @RequestParam("preferences") UserPreferences preferences) {
...
return someService.call(preferences);
...
}
I tried @ModelAttribute
, added setter/getters, constructors with all possibilities to UserPreferences
but no chance as it recognized the sent data as 5 parameters but in fact the mapped method has only 2 parameters. I also tried Biju's solution however what happens is that, spring creates an UserPreferences object with default constructor and doesn't fill in the data.
I solved the problem by sending JSon string of the preferences from the client side and handle it as if it is a String on the server side;
client:
$.post("/updatePreferences",
{id: 'pr', preferences: JSON.stringify(p)},
function (response) {
...
server:
@RequestMapping(value = "/updatePreferences")
public
@ResponseBody
Object updatePreferences(@RequestParam("id") String id, @RequestParam("preferences") String preferencesJSon) {
String ret = null;
ObjectMapper mapper = new ObjectMapper();
try {
UserPreferences userPreferences = mapper.readValue(preferencesJSon, UserPreferences.class);
return someService.call(userPreferences);
} catch (IOException e) {
e.printStackTrace();
}
}
to brief, I did the conversion manually inside the REST method. In my opinion the reason why spring doesn't recognize the sent data is the content-type.
Actually it is the issue related to the app store. I have upload many build some time it takes time depend upon the size of the ipa and at which time you are uploading it to the App Store. Please use Application Loader 3.0 or higher to upload the build.
There're lots of characters around the world,like "$,&,h,a,t,?,?,1,=,+...".
Then there comes an organization who's dedicated to these characters,
They made a standard called "Unicode".
The standard is like follows:
PS:Of course there's another organization called ISO maintaining another standard --"ISO 10646",nearly the same.
As above,U+0024 is just a position,so we can't save "U+0024" in computer for the character "$".
There must be an encoding method.
Then there come encoding methods,such as UTF-8,UTF-16,UTF-32,UCS-2....
Under UTF-8,the code point "U+0024" is encoded into 00100100.
00100100 is the value we save in computer for "$".
... I don't know if you're using an activex button or not, but when I insert an activex button into sheet1 in Excel called CommandButton1, the following code works fine:
Sub test()
Sheets(1).CommandButton1.Enabled = False
End Sub
Hope this helps...
You can do it fast, only using one POSIX function. If you have bunch of tasks with dates, see the module DateTime.
use POSIX qw(strftime);
my $date = strftime "%m/%d/%Y", localtime;
print $date;
ObjectPath is a library that provides ability to query JSON and nested structures of dicts and lists. For example, you can search for all attributes called "foo" regardless how deep they are by using $..foo
.
While the documentation focuses on the command line interface, you can perform the queries programmatically by using the package's Python internals. The example below assumes you've already loaded the data into Python data structures (dicts & lists). If you're starting with a JSON file or string you just need to use load
or loads
from the json module first.
import objectpath
data = [
{'foo': 1, 'bar': 'a'},
{'foo': 2, 'bar': 'b'},
{'NoFooHere': 2, 'bar': 'c'},
{'foo': 3, 'bar': 'd'},
]
tree_obj = objectpath.Tree(data)
tuple(tree_obj.execute('$..foo'))
# returns: (1, 2, 3)
Notice that it just skipped elements that lacked a "foo" attribute, such as the third item in the list. You can also do much more complex queries, which makes ObjectPath handy for deeply nested structures (e.g. finding where x has y that has z: $.x.y.z
). I refer you to the documentation and tutorial for more information.
If your computer can't find the IP address associated with SUBDOMAIN1.example.COM
, it will not find the site.
You need to either change your hosts
file (so you can at least test things - this will be a local change, only available to yourself), or update DNS so the name will resolve correctly (so the rest of the world can see it).
I agree with Mark. I set the output to text mode and then sp_HelpText 'sproc'. I have this binded to Crtl-F1 to make it easy.
Thanks to @Yiling. That was a hint.
<bean id="propertyConfigurer"
class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
<property name="locations">
<list>
<value>file:#{systemEnvironment['FILE_PATH']}/first.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/second.properties</value>
<value>file:#{systemEnvironment['FILE_PATH']}/third.properties</value>
</list>
</property>
</bean>
After this, you should have one environment variable named 'FILE_PATH'. Make sure you restart your terminal/IDE after creating that environment variable.
This is kind of a specific case, but in case anyone gets here with my problem:
In MongoHQ, it'll show you a field called "password", but it's actually just the hash of the password. You'll have to add a new user and store the password elsewhere (because MongoHQ won't show it to you).
String
Under System namespace
Immutable (readonly) instance
Performance degrades when continuous change of value occurs
Thread-safe
StringBuilder (mutable string)
For a descriptive article about this topic with a lot of examples using ObjectIDGenerator, follow this link.
Related Stack Overflow question: Mutability of string when string doesn't change in C#
I needed to export our security log and wanted the date and time in Coordinated Universal Time. This proved to be a challenge to figure out, but so simple to execute:
wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ")).evtx
The magic code is just this part:
$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))
The problem with checkboxes is that if they are not checked then they are not posted with your form. If you check a checkbox and post a form you will get the value of the checkbox in the $_POST variable which you can use to process a form, if it's unchecked no value will be added to the $_POST variable.
In PHP you would normally get around this problem by doing an isset() check on your checkbox element. If the element you are expecting isn't set in the $_POST variable then we know that the checkbox is not checked and the value can be false.
if(!isset($_POST['checkbox1']))
{
$checkboxValue = false;
} else {
$checkboxValue = $_POST['checkbox1'];
}
But if you have created a dynamic form then you won't always know the name attribute of your checkboxes, if you don't know the name of the checkbox then you can't use the isset function to check if this has been sent with the $_POST variable.
If you're just after console logging here's what I'd do:
export default class App extends Component {
componentDidMount() {
console.log('I was triggered during componentDidMount')
}
render() {
console.log('I was triggered during render')
return (
<div> I am the App component </div>
)
}
}
Shouldn't be any need for those packages just to do console logging.
I think this has not been highlighted by any answer, but another good example and usage for the new placement is to reduce the memory fragmentation (by using memory pools). This is specially useful in embedded and high availability systems. In this last case it's specially important because for a system that has to run 24/365 days it's very important to have no fragmentation. This problem has nothing to do with memory leakage.
Even when a very good malloc implementation is used (or similar memory management function) it's very difficult to deal with fragmentation for a long time. At some point if you don't manage cleverly the memory reservation/release calls you could end up with a lot of small gaps that are difficult to reuse (assign to new reservations). So, one of the solutions that are used in this case is to use a memory pool to allocate before hand the memory for the application objects. After-wards each time you need memory for some object you just use the new placement to create a new object on the already reserved memory.
This way, once your application starts you already have all the needed memory reserved. All the new memory reservation/release goes to the allocated pools (you may have several pools, one for each different object class). No memory fragmentation happens in this case since there will no gaps and your system can run for very long periods (years) without suffering from fragmentation.
I saw this in practice specially for the VxWorks RTOS since its default memory allocation system suffers a lot from fragmentation. So allocating memory through the standard new/malloc method was basically prohibited in the project. All the memory reservations should go to a dedicated memory pool.
I just found Scandinavian Keyboard as a fine solution to this problem. It do also have English and German keyboard, but neither Dutch nor Spanish - but I guess they could be added. And I guess there is other alternatives out there.
Even I faced this issue and solved it with 2 ways:
1) In your IDE select project and clean all projects then install all the maven dependencies by right clicking on project -> go to maven and Update project dependencies select all projects at once to install the same. Once this is done run the particular project
2) Else What you can do is check in the pom.xml for the dependencies for which you are getting error and "mvn clean install" those dependent project first and the install maven dependencies of the current project in which you facing issue. By this the dependencies of the local project will be build and jars will be created.
In Chrome Browser go to setting , clear browsing history and then reload the page
Here is a useful article by Michael J. Swart on the matter, which covers different patterns and antipatterns for implementing UPSERT
in SQL Server:
https://michaeljswart.com/2017/07/sql-server-upsert-patterns-and-antipatterns/
It addresses associated concurrency issues (primary key violations, deadlocks) - all of the answers provided here yet are considered antipatterns in the article (except for the @Bridge solution using triggers, which is not covered there).
Here is an extract from the article with the solution preferred by the author:
Inside a serializable transaction with lock hints:
CREATE PROCEDURE s_AccountDetails_Upsert ( @Email nvarchar(4000), @Etc nvarchar(max) )
AS
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRAN
IF EXISTS ( SELECT * FROM dbo.AccountDetails WITH (UPDLOCK) WHERE Email = @Email )
UPDATE dbo.AccountDetails
SET Etc = @Etc
WHERE Email = @Email;
ELSE
INSERT dbo.AccountDetails ( Email, Etc )
VALUES ( @Email, @Etc );
COMMIT
There is also related question with answers here on stackoverflow: Insert Update stored proc on SQL Server
Now iOS 7 devices – are always returning a MAC address of 02:00:00:00:00:00.
So better use [UIDevice identifierForVendor].
so better to call this method to get app specific unique key
Category will more suitable
import "UIDevice+Identifier.h"
- (NSString *) identifierForVendor1
{
if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
return @"";
}
Now call above method to get unique address
NSString *like_UDID=[NSString stringWithFormat:@"%@",
[[UIDevice currentDevice] identifierForVendor1]];
NSLog(@"%@",like_UDID);
Alternative - use a function
is_ok(){ :;}
is_ok(){ return 1;}
is_ok && echo "It's OK" || echo "Something's wrong"
Defining the function is less intuitive, but checking its return value is very easy.
<button type="button" onClick="refreshPage()">Close</button>
<script>
function refreshPage(){
window.location.reload();
}
</script>
or
<button type="button" onClick="window.location.reload();">Close</button>
http://api.jqueryui.com/datepicker/#option-maxDate
$( ".selector" ).datepicker( "option", "maxDate", '+0m +0w' );