I found UriBuilder
worked really well for this sort of thing:
UriBuilder urlb = new UriBuilder("http", _serverAddress, _webPort, _filePath);
Uri url = urlb.Uri;
return url.AbsoluteUri;
See UriBuilder Class - MSDN for more constructors and documentation.
Try this
$str = '<option value="123">abc</option>
<option value="123">aabbcc</option>';
preg_match_all("#<option.*?>([^<]+)</option>#", $str, $foo);
print_r($foo[1]);
The simplest way to check the existence of the column in mongo compass is :
{ 'column_name': { $exists: true } }
I don't think you can do it with one rsync command, but you can 'pre-create' the extra directory first like this:
rsync --recursive emptydir/ destination/newdir
where 'emptydir' is a local empty directory (which you might have to create as a temporary directory first).
It's a bit of a hack, but it works for me.
cheers
Chris
1) I had to do the following with my configuration: (Add BackConnectionHostNames or Disable Loopback Check) http://support.microsoft.com/kb/896861
2) I was working off a dev system on an isolated dev network. I had gotten it working using the dev system's computer name in the URL to the web service, but when I modified the URL to the URL that would be used in production (rather than the computer name), I started getting the NTLM error.
3) I noticed the security log showed that the service account failing to login with an error similar to the one in the MSDN article.
4) Adding the BackConnectionHostNames made it so I could log into the server via a browser running on the server, but the service account still had NTLM errors when trying to authenticate for the web services. I wound up disabling the loop back check and that fixed it for me.
An alternative to the above commands that is a little more bulletproof.
It can list all files irrespective of permissions or path length.
robocopy "C:\YourFolderPath" "C:\NULL" /E /L /NJH /NJS /FP /NS /NC /B /XJ
I have a slight issue with the use of C:\NULL which I have written about in my blog
https://theitronin.com/bulletproofdirectorylisting/
But nevertheless it's the most robust command I know.
I have 2 computers with VMWare Workstation and Mac OS Sierra installed as the guest OS. First machine could recognize my iOS device whereas my second machine could not recognize it. The second machine was exhibiting the same behavior as others reported where it would reconnect and disconnect with the iPhone endlessly.
Thankfully, my second machine had network connectivity problems with my VM. So I stumbled upon the solution when I reset my network settings for the VM.
You can try the following steps and see if it works for you. It worked for me.
If you really need it inline, for example because you are loading some user-defined colors dynamically, you can always add a <style>
element right before your content.
<style>#project-slide-1:before { color: #ff0000; }</style>
<div id="project-slide-1" class="project-slide"> ... </div>
Example use case with PHP and some (wordpress inspired) dummy functions:
<style>#project-slide-<?php the_ID() ?>:before { color: <?php the_field('color') ?>; }</style>
<div id="project-slide-<?php the_ID() ?>" class="project-slide"> ... </div>
Since HTML 5.2 it is valid to place style elements inside the body, although it is still recommend to place style elements in the head.
Reference: https://www.w3.org/TR/html52/document-metadata.html#the-style-element
I'm a little late to the party but for future readers.
From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the !
operator?
jxPanel6.setVisible(!jxPanel6.isVisible);
It's not an if statement but I prefer this method for code related to your example.
CSS3 can solve this problem. Unfortunately it's only supported on 60% of used browsers nowadays.
For IE and iOS you can't turn off resizing but you can limit the textarea
dimension by setting its width
and height
.
/* One can also turn on/off specific axis. Defaults to both on. */
textarea { resize:vertical; } /* none|horizontal|vertical|both */
You should add the g
modifier so that sed performs a global substitution of the contents of the pattern buffer:
echo dog dog dos | sed -e 's:dog:log:g'
For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6
The official documentation for GNU sed
is available at http://www.gnu.org/software/sed/manual/
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Undoing a merge with git is so easy you shouldn't even worry about the dry run:
$ git pull $REMOTE $BRANCH
# uh oh, that wasn't right
$ git reset --hard ORIG_HEAD
# all is right with the world
EDIT: As noted in the comments below, if you have changes in your working directory or staging area you'll probably want to stash them before doing the above (otherwise they will disappear following the git reset
above)
You can even try this.
String date="09/08/1980"; // take a string date
Timestamp ts=null; //declare timestamp
Date d=new Date(date); // Intialize date with the string date
if(d!=null){ // simple null check
ts=new java.sql.Timestamp(d.getTime()); // convert gettime from date and assign it to your timestamp.
}
Let's say you have a tar file and you want to uncompress it after placing it in your container, remove it, you can use the COPY command to do this. Butt he various commands would be 1) Copy the tar file to the destination, 2). Uncompress it, 3) Remove the tar file. If you did this in 3 steps then there will be a new image created after each step. You can do this in one step using & but it becomes a hassle.
But you used ADD, then Docker will take care of everything for you and only one intermediate image will be created.
As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.
However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.
Recursion is more costly in memory, as each recursive call generally requires a memory address to be pushed to the stack - so that later the program could return to that point.
Still, there are many cases in which recursion is a lot more natural and readable than loops - like when working with trees. In these cases I would recommend sticking to recursion.
On my clean macOS 10.15.7, I needed to brew link gnupg && brew unlink gnupg
first and then used Ashish's answer to use gpg
instead of gpg2
. I also had to chown
a few directories. before the un/link.
By far the most easiest one I've found and used is sync-request and it supports both node and the browser!
var request = require('sync-request');
var res = request('GET', 'http://google.com');
console.log(res.body.toString('utf-8'));
That's it, no crazy configuration, no complex lib installs, although it does have a lib fallback. Just works. I've tried other examples here and was stumped when there was much extra setup to do or installs didn't work!
The example that sync-request uses doesn't play nice when you use res.getBody()
, all get body does is accept an encoding and convert the response data. Just do res.body.toString(encoding)
instead.
Use android:background property for that edittext. Pass your drawable folder image to it. For example,
android:background="@drawable/abc.png"
Just set the selectIndex
of the associated <select>
tag to -1
as the last step of your processing event.
mySelect = document.getElementById("idlist");
mySelect.selectedIndex = -1;
It works every time, removing the highlight and allowing you to select the same (or different) element again .
You should not create a new Random
instance in a loop. Try something like:
var rnd = new Random();
for(int i = 0; i < 100; ++i)
Console.WriteLine(rnd.Next(1, 100));
The sequence of random numbers generated by a single Random
instance is supposed to be uniformly distributed. By creating a new Random
instance for every random number in quick successions, you are likely to seed them with identical values and have them generate identical random numbers. Of course, in this case, the generated sequence will be far from uniform distribution.
For the sake of completeness, if you really need to reseed a Random
, you'll create a new instance of Random
with the new seed:
rnd = new Random(newSeed);
Consider that the files you need to delete have an extension txt
and is located in the location D:\My Folder
, then you could use the below code inside the bat file.
cd "D:\My Folder"
DEL *.txt
It really depends on the IE versions ... I found this excellent resource that is up to date from IE6-10:
CSS hack for Internet Explorer 6
It is called the Star HTML Hack and looks as follows:
- html .color {color: #F00;} This hack uses fully valid CSS.
CSS hack for Internet Explorer 7
It is called the Star Plus Hack.
*:first-child+html .color {color: #F00;} Or a shorter version:
*+html .color {color: #F00;} Like the star HTML hack, this uses valid CSS.
CSS hack for Internet Explorer 8
@media \0screen { .color {color: #F00;} } This hacks does not use valid CSS.
CSS hack for Internet Explorer 9
:root .color {color: #F00\9;} This hacks also does not use valid CSS.
Added 2013.02.04: Unfortunately IE10 understands this hack.
CSS hack for Internet Explorer 10
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { .color {color: #F00;} } This hacks also does not use valid CSS.
Since a jQuery object inherits from an array, and this array contains the selected DOM elements. Saying you're using an id and so the element should be unique within the DOM, you could perform a direct call to submit by doing :
$(".nextbutton").click(function() {
$("#formID")[0].submit();
});
this is an out of topic answer, but, for those who are interested, it maybe valuable.
As in @John Kugelman's answer, % is related to job specification. how to efficiently find that? use less's &pattern command, seems man use less pager (not that sure), in man bash type &% then type Enter will only show lines that containing '%', to reshow all, type &. then Enter.
one liner, without opening ~/.zshrc
file
echo -n 'export PATH=~/bin:$PATH' >> ~/.zshrc
or
echo -n 'export PATH=$HOME/bin:$PATH' >> ~/.zshrc
To see the effect, do source ~/.zshrc
in the same tab or open a new tab
Here's an example using Angular 2+
For example, if you wanted to close a Modal Component if the user clicks outside of it:
// Close the modal if the document is clicked.
@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
this.closeModal();
}
// Don't close the modal if the modal itself is clicked.
@HostListener('click', ['$event'])
public onClick(event: MouseEvent): void {
event.stopPropagation();
}
Please try this
SELECT *
FROM [Village]
WHERE CONVERT(VARCHAR, CastleType) = 'foo'
Following command worked for me, all the local committed changes are dropped & local is reset to the same as remote origin/master branch.
git reset --hard origin
I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.
I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))
The following should prefix 'www' to any request that doesn't have one, and redirect the edited request to the new URI.
RewriteCond "%{HTTP_HOST}" "!^www\." [NC]
RewriteCond "%{HTTP_HOST}" "(.*)"
RewriteRule "(.*)" "http://www.%1$1" [R=301,L]
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!"
}).then(
function () { /*Your Code Here*/ },
function () { return false; });
I changed the package name while coding an update so that I could debug it on my device via Eclipse, without deleting the old version that was installed. Without reverting the package name I was using when trying to reinstall, I got this same error. Using the same package name the reinstall was successful.
if((int)letter != 0) { }
This is my original post, which sparked some debate... because it is wrong:
The switch statement is not the same thing as a big if-else statement. Each case must be unique and evaluated statically. The switch statement does a constant time branch regardless of how many cases you have. The if-else statement evaluates each condition until it finds one that is true.
In fact, the C# switch statement is not always a constant time branch.
In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely.
This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.
How large are the values? Java 6 has Scanner class that can read anything from int (32 bit), long (64-bit) to BigInteger (arbitrary big integer).
For Java 5 or 4, Scanner is there, but no support for BigInteger. You have to read line by line (with readLine of Scanner class) and create BigInteger object from the String.
If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch()
. Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.
MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.
It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.
The feature doesn't prevent any other type of data forgery or tampering based attacks.
To use it, decorate the action method or controller with the ValidateAntiForgeryToken
attribute and place a call to @Html.AntiForgeryToken()
in the forms posting to the method.
I tried the following @janny loco's answer first and then reset anaconda to get it to work.
Step 1:
activate root
conda update -n root conda
conda update --all
Step 2:
anaconda-navigator --reset
After running the update commands in step 1 and not seeing any success, I reset anaconda by running the command above based on what I found here.
I am not sure if it was the combination of updating conda and reseting the navigator or just one of the two. So, please try accordingly.
Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?
Something like request.Credentials = new NetworkCredential("UserName", "PassWord");
Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;
Check out my post on this subject.
This seems to be a little buggy in Pandas 0.23.4?
If there are np.nan values then this will throw an error as expected:
df['col'] = df['col'].astype(np.int64)
But doesn't change any values from float to int as I would expect if "ignore" is used:
df['col'] = df['col'].astype(np.int64,errors='ignore')
It worked if I first converted np.nan:
df['col'] = df['col'].fillna(0).astype(np.int64)
df['col'] = df['col'].astype(np.int64)
Now I can't figure out how to get null values back in place of the zeroes since this will convert everything back to float again:
df['col'] = df['col'].replace(0,np.nan)
I think you could write it that way too. I am also a student so I understand your struggle. A bit late response but ok .
#include<stdio.h>
#define n 3
struct {
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}bodies[n];
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
Just make option#1 Select Language:


is the HTML representation in hex of a line feed
character. It represents a new line on Unix and Unix-like (for example) operating systems.
You can find a list of such characters at (for example) http://la.remifa.so/unicode/latin1.html
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Email, model.UserName),
new Claim(JwtRegisteredClaimNames.NameId, model.Id.ToString()),
};
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
Then extract content
var handler = new JwtSecurityTokenHandler();
string authHeader = Request.Headers["Authorization"];
authHeader = authHeader.Replace("Bearer ", "");
var jsonToken = handler.ReadToken(authHeader);
var tokenS = handler.ReadToken(authHeader) as JwtSecurityToken;
var id = tokenS.Claims.First(claim => claim.Type == "nameid").Value;
Going off the accepted answer, an alternative solution that doesn't require a custom hook:
const Component = ({ receiveAmount, sendAmount }) => {
const prevAmount = useRef({ receiveAmount, sendAmount }).current;
useEffect(() => {
if (prevAmount.receiveAmount !== receiveAmount) {
// process here
}
if (prevAmount.sendAmount !== sendAmount) {
// process here
}
return () => {
prevAmount.receiveAmount = receiveAmount;
prevAmount.sendAmount = sendAmount;
};
}, [receiveAmount, sendAmount]);
};
This assumes you actually need reference to the previous values for anything in the "process here" bits. Otherwise unless your conditionals are beyond a straight !==
comparison, the simplest solution here would just be:
const Component = ({ receiveAmount, sendAmount }) => {
useEffect(() => {
// process here
}, [receiveAmount]);
useEffect(() => {
// process here
}, [sendAmount]);
};
Try the worksheet activate command before you need data from the sheet:
objWorkbook.WorkSheets(1).Activate
objWorkbook.WorkSheets(2).Activate
key
is a function that will be called to transform the collection's items before they are compared. The parameter passed to key
must be something that is callable.
The use of lambda
creates an anonymous function (which is callable). In the case of sorted
the callable only takes one parameters. Python's lambda
is pretty simple. It can only do and return one thing really.
The syntax of lambda
is the word lambda
followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while
, for
, if
and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.
We can compare the use of lambda with that of def to create a function.
adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2
lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.
variable
is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.
All three are not the conventions.
Use com.stackoverflow.mypackage
.
The package names do not follow camel casing or underscores or hyphens package naming convention.
Also, Google Java Style Guide specifies exactly the same (i.e. com.stackoverflow.mypackage
) convention:
5.2.1 Package names
Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example,
com.example.deepspace
, notcom.example.deepSpace
orcom.example.deep_space
.— Google Java Style Guide: 5.2 Rules by identifier type: 5.2.1 Package names.
I was quite inspired by the last answer by mklement0 - I have few scripts/small programs I run at every reboot via /etc/crontab
. I built on his answer and built a login script, which shows if my programs are still running.
I execute this scripts.sh
via .profile
-file on every login, to get instant notification on each login.
cat scripts.sh
#!/bin/bash
getscript() {
pgrep -lf ".[ /]$1( |\$)"
}
script1=keepalive.sh
script2=logger_v3.py
# test if script 1 is running
if getscript "$script1" >/dev/null; then
echo "$script1" is RUNNING
else
echo "$script1" is NOT running
fi
# test if script 2 is running:
if getscript "$script2" >/dev/null; then
echo "$script2" is RUNNING
else
echo "$script2" is NOT running
fi
Below the function for taking snapshot a specific element in Selenium. Here the driver is a type of WebDriver.
private static void getScreenshot(final WebElement e, String fileName) throws IOException {
final BufferedImage img;
final Point topleft;
final Point bottomright;
final byte[] screengrab;
screengrab = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
img = ImageIO.read(new ByteArrayInputStream(screengrab));
topleft = e.getLocation();
bottomright = new Point(e.getSize().getWidth(), e.getSize().getHeight());
BufferedImage imgScreenshot=
(BufferedImage)img.getSubimage(topleft.getX(), topleft.getY(), bottomright.getX(), bottomright.getY());
File screenshotLocation = new File("Images/"+fileName +".png");
ImageIO.write(imgScreenshot, "png", screenshotLocation);
}
You can set imageview in XML file like this :
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/imagep1" />
and you can define image view in android java file like :
ImageView imageView = (ImageView) findViewById(R.id.imageViewId);
and set Image with drawable like :
imageView.setImageResource(R.drawable.imageFileId);
and set image with your memory folder like :
File file = new File(SupportedClass.getString("pbg"));
if (file.exists()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap selectDrawable = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imageView.setImageBitmap(selectDrawable);
}
else
{
Toast.makeText(getApplicationContext(), "File not Exist", Toast.LENGTH_SHORT).show();
}
add JAVA_HOME to the file:
/etc/environment
for it to be available to the entire system (you would need to restart Ubuntu though)
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table @Lines:
declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);
declare @Lines table (
line varchar(8000)
);
declare @sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+@filename+'''
with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
select * from #tmp';
insert into @Lines
exec(@sql);
select * from @lines
Incase of lookup_food_array is array.
match_stage["favoriteFoods"] = {'$elemMatch': {'$in': lookup_food_array}}
Incase of lookup_food_array is string.
match_stage["favoriteFoods"] = {'$elemMatch': lookup_food_string}
Very useful post! I've implemented this in JavaScript, hereby my code. I've used this successfully.
function rad2degr(rad) { return rad * 180 / Math.PI; }
function degr2rad(degr) { return degr * Math.PI / 180; }
/**
* @param latLngInDeg array of arrays with latitude and longtitude
* pairs in degrees. e.g. [[latitude1, longtitude1], [latitude2
* [longtitude2] ...]
*
* @return array with the center latitude longtitude pairs in
* degrees.
*/
function getLatLngCenter(latLngInDegr) {
var LATIDX = 0;
var LNGIDX = 1;
var sumX = 0;
var sumY = 0;
var sumZ = 0;
for (var i=0; i<latLngInDegr.length; i++) {
var lat = degr2rad(latLngInDegr[i][LATIDX]);
var lng = degr2rad(latLngInDegr[i][LNGIDX]);
// sum of cartesian coordinates
sumX += Math.cos(lat) * Math.cos(lng);
sumY += Math.cos(lat) * Math.sin(lng);
sumZ += Math.sin(lat);
}
var avgX = sumX / latLngInDegr.length;
var avgY = sumY / latLngInDegr.length;
var avgZ = sumZ / latLngInDegr.length;
// convert average x, y, z coordinate to latitude and longtitude
var lng = Math.atan2(avgY, avgX);
var hyp = Math.sqrt(avgX * avgX + avgY * avgY);
var lat = Math.atan2(avgZ, hyp);
return ([rad2degr(lat), rad2degr(lng)]);
}
Below solution is perfect for this purpose:
select mod('299123456789',1000000000) from dual;
I think you can also use BufferedWriter :
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("note.txt")));
String stuffToWrite = info;
writer.write(stuffToWrite);
writer.close();
and before that remember too add
import java.io.BufferedWriter;
Please use Spring Tool Suite (Eclipse-based development environment that is customized for developing Spring applications).
Create a Spring Starter Project, it will create the directory structure for you with the spring boot maven dependencies.
I had a similar problem. To solve this (instead of calculate the iframe's height using the body, document or window) I created a div that wraps the whole page content (a div with an id="page" for example) and then I used its height.
[root@host]# mysqladmin -u root -p drop [DB]
Enter password:******
Well, you just fire the desired click event:
$(".first").click(function(){
$(".second").click();
return false;
});
If you'd like a simple method to resolve this problem. (Can be used as an extension)
See below:
public static string RemoveFirstInstanceOfString(this string value, string removeString)
{
int index = value.IndexOf(removeString, StringComparison.Ordinal);
return index < 0 ? value : value.Remove(index, removeString.Length);
}
Usage:
string valueWithPipes = "| 1 | 2 | 3";
string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
//Output, valueWithoutFirstpipe = " 1 | 2 | 3";
Inspired by and modified @LukeH's and @Mike's answer.
Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html
I suggest you when working with listview or recyclerview to use SwipeRefreshLayout. Like this
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/card_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
Only wrap your view and this will create an animation of refresh when loading data or by swipping down the screen as we can do in many apps.
Here's the documentation of how to use it:
https://developer.android.com/training/swipe/add-swipe-interface.html
https://developer.android.com/training/swipe/respond-refresh-request.html
Happy coding !
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.
the directive
angular.module('myCoolApp')
.directive('fileButton', function () {
return {
templateUrl: 'components/directives/fileButton/fileButton.html',
restrict: 'E',
link: function (scope, element, attributes) {
var container = angular.element('.file-upload-container');
var button = angular.element('.file-upload-button');
container.css({
position: 'relative',
overflow: 'hidden',
width: button.offsetWidth,
height: button.offsetHeight
})
}
};
});
a jade template if you are using jade
div(class="file-upload-container")
button(class="file-upload-button") +
input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")
the same template in html if you are using html
<div class="file-upload-container">
<button class="file-upload-button"></button>
<input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" />
</div>
the css
.file-upload-button {
margin-top: 40px;
padding: 30px;
border: 1px solid black;
height: 100px;
width: 100px;
background: transparent;
font-size: 66px;
padding-top: 0px;
border-radius: 5px;
border: 2px solid rgb(255, 228, 0);
color: rgb(255, 228, 0);
}
.file-upload-input {
position: absolute;
top: 0;
left: 0;
z-index: 2;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
Make sure that the -L
option appears ahead of the -l
option; the order of options in linker command lines does matter, especially with static libraries. The -L
option specifies a directory to be searched for libraries (static or shared). The -lname
option specifies a library which is with libmine.a
(static) or libmine.so
(shared on most variants of Unix, but Mac OS X uses .dylib
and HP-UX used to use .sl
). Conventionally, a static library will be in a file libmine.a
. This is convention, not mandatory, but if the name is not in the libmine.a
format, you cannot use the -lmine
notation to find it; you must list it explicitly on the compiler (linker) command line.
The -L./libmine
option says "there is a sub-directory called libmine
which can be searched to find libraries". I can see three possibilities:
libmine.a
, in which case you also need to add -lmine
to the linker line (after the object files that reference the library).libmine
that is a static archive, in which case you simply list it as a file ./libmine
with no -L
in front. libmine.a
in the current directory that you want to pick up. You can either write ./libmine.a
or -L . -lmine
and both should find the library.There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.
Though PuTTY supports connection-sharing.
While you still need to run a compatible file transfer client (pscp
or psftp
), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.
To enable the sharing see:
Sharing an SSH connection between PuTTY tools.
Even without connection-sharing, you can still use the psftp
or pscp
from Windows command line.
See How to use PSCP to copy file from Unix machine to Windows machine ...?
Note that the scp
is OpenSSH program. It's primarily *nix program, but you can run it via Windows Subsystem for Linux or get a Windows build from Win32-OpenSSH (it is already built-in in the latest versions of Windows 10).
If you really want to download the files to a local desktop, you have to specify a target path as %USERPROFILE%\Desktop
(what typically resolves to a path like C:\Users\username\Desktop
).
Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY command.
See Opening Session in PuTTY.
With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.
See Opening PuTTY in the same directory.
(I'm the author of WinSCP)
You should apply close before than quit
driver.close()
driver.quit()
Quick answer
On src, you can always specify files to ignore using "!".
Example (you want to exclude all *.min.js files on your js folder and subfolder:
gulp.src(['js/**/*.js', '!js/**/*.min.js'])
You can do it as well for individual files.
Expanded answer:
Extracted from gulp documentation:
gulp.src(globs[, options])
Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
glob refers to node-glob syntax or it can be a direct file path.
So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.
On minimatch documentation, they point out the following:
if the pattern starts with a ! character, then it is negated.
And that is why using ! symbol will exclude files / directories from a gulp task
For C# the solution is to cast the values to a double (as Math.Ceiling takes a double):
int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);
In java you should do the same with Math.ceil().
psutil provides a portable way that doesn't use environment variables like the getpass
solution. It is less prone to security issues, and should probably be the accepted answer as of today.
import psutil
def get_username():
return psutil.Process().username()
Under the hood, this combines the getpwuid
based method for unix and the GetTokenInformation
method for Windows.
Even this piece of code does the same job.
<tbody>
{array.map(i =>
<ObjectRow key={i.id} name={i.name} />
)}
</tbody>
As there is currently no CSS solution to style a parent, I use a simple jQuery one here to add a class to a label with checked input inside it.
$(document).on("change","input", function(){
$("label").removeClass("checkedlabel");
if($(this).is(":checked")) $(this).closest("label").addClass("checkedlabel");
});
Don't forget to give the pre-checked input's label the class checkedlabel
too
When I upgraded to Spring 4 I needed to update the jackson dependencies as follows:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.1</version>
</dependency>
How to access screen size or pixel density or aspect ratio in flutter ?
We can access screen size and other like pixel density, aspect ration etc. with helps of MediaQuery.
syntex : MediaQuery.of(context).size.height
Personal preference.
Usually. Sometimes it matters but, not to seem like a jerk here, but if you have to ask, it probably doesn't.
I tried every possible solution on this web site and nothing worked for me. I ended up doing in the design mode. Right click on the table name and then click design. Then I changed the name and saved here. Worked simply.
Something like this (not tested)
with match_groups as (
select product_id,
matching_product_id,
product_id as group_id
from matches
where product_id not in (select matching_product_id from matches)
union all
select m.product_id, m.matching_product_id, p.group_id
from matches m
join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;
Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial
The MDN Documentation is very eloquent and features examples.
My situation has two Submit
buttons within the form element: Update
and Delete
. The Delete
button deletes an image and the Update
button updates the database with the text fields in the form.
Because the Delete
button was first in the form, it was the default button on Enter
key. Not what I wanted. The user would expect to be able to hit Enter
after changing some text fields.
I found my answer to setting the default button here:
<form action="/action_page.php" method="get" id="form1">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
</form>
<button type="submit" form="form1" value="Submit">Submit</button>
Without using any script, I defined the form that each button belongs to using the <button> form="bla"
attribute. I set the Delete
button to a form that doesn't exist and set the Update
button I wanted to trigger on the Enter
key to the form that the user would be in when entering text.
This is the only thing that has worked for me so far.
Private Sub Main()
Dim value = getValue()
'do something with value
End Sub
Private Function getValue() As Integer
Return 3
End Function
Nowadays with HTML5, it's pretty simple:
<input type="search" placeholder="Search..."/>
Most modern browsers will automatically render a usable clear button in the field by default.
(If you use Bootstrap, you'll have to add an override to your css file to make it show)
input[type=search]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
Safari/WebKit browsers can also provide extra features when using type="search"
, like results=5
and autosave="..."
, but they also override many of your styles (e.g. height, borders) . To prevent those overrides, while still retaining functionality like the X button, you can add this to your css:
input[type=search] {
-webkit-appearance: none;
}
See css-tricks.com for more info about the features provided by type="search"
.
554 is commonly used by dns blacklists when shooing away blacklisted servers. I'm assuming
Mon 2008-10-20 16:11:36: * relays.ordb.org - failed
in the log you included is to blame.
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.
For more detail you can refer the link.
To add to Timo's answer LINQ can be used like this as well:
items = items.Select(i => {
...
//perform some logic adding / updating.
return i / return new Item();
...
//To remove an item simply have logic to return null.
//Then attach the Where to filter out nulls
return null;
...
}).Where(i => i != null);
I've written an Angular directive that does slideToggle()
without jQuery.
one liner remote remove all collections from mongo database
note must use --host, (-h is help for mongo command), and -d is not an option, select the db and command after password.
mongo --host <mongo_host>:<mongo_port> -u <db_user> -p <db_pass> <your_db> --eval "db.dropDatabase()"
The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.
See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
In this example, the user selects an HTML file. It uploaded into the <textarea>
.
<form enctype="multipart/form-data">
<input id="upload" type=file accept="text/html" name="files[]" size=30>
</form>
<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// use the 1st file from the list
f = files[0];
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
jQuery( '#ms_word_filtered_html' ).val( e.target.result );
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
Okay, here are the explanations.
e.keyCode - used to get the number that represents the key on the keyboard
e.charCode - a number that represents the unicode character of the key on keyboard
e.which - (jQuery specific) is a property introduced in jQuery (DO Not use in plain javascript)
Below is the code snippet to get the keyCode and charCode
<script>
// get key code
function getKey(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
alert(keyCode);
}
// get char code
function getChar(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
var typedChar = String.fromCharCode(keyCode);
alert(typedChar);
}
</script>
Live example of Getting keyCode and charCode in JavaScript.
Use jquery-dateFormat. It will solve your problem.
You need to include the jquery.dateFormat in your html file.
<script>
var date = $('#scheduleDate').val();
document.write($.format.date(date, "dd,MM,yyyy"));
var dateTypeVar = $('#scheduleDate').datepicker('getDate');
document.write($.format.date(dateTypeVar, "dd-MM-yy"));
</script>
Based on the EnumToBooleanConverter from Scott. I noticed that the ConvertBack method doesn't work on the Enum with flags code.
I've tried the following code:
public class EnumHasFlagToBooleanConverter : IValueConverter
{
private object _obj;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
_obj = value;
return ((Enum)value).HasFlag((Enum)parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.Equals(true))
{
if (((Enum)_obj).HasFlag((Enum)parameter))
{
// Do nothing
return Binding.DoNothing;
}
else
{
int i = (int)_obj;
int ii = (int)parameter;
int newInt = i+ii;
return (NavigationProjectDates)newInt;
}
}
else
{
if (((Enum)_obj).HasFlag((Enum)parameter))
{
int i = (int)_obj;
int ii = (int)parameter;
int newInt = i-ii;
return (NavigationProjectDates)newInt;
}
else
{
// do nothing
return Binding.DoNothing;
}
}
}
}
The only thing that I can't get to work is to do a cast from int
to targetType
so I made it hardcoded to NavigationProjectDates
, the enum that I use. And, targetType == NavigationProjectDates
...
Edit for more generic Flags Enum converter:
public class FlagsEnumToBooleanConverter : IValueConverter { private int _flags=0; public object Convert(object value, Type targetType, object parameter, string language) { if (value == null) return false; _flags = (int) value; Type t = value.GetType(); object o = Enum.ToObject(t, parameter); return ((Enum)value).HasFlag((Enum)o); } public object ConvertBack(object value, Type targetType, object parameter, string language) { if (value?.Equals(true) ?? false) { _flags = _flags | (int) parameter; } else { _flags = _flags & ~(int) parameter; } return _flags; } }
You can do this by executing the following command:
ld --verbose | grep SEARCH_DIR | tr -s ' ;' \\012
gcc passes a few extra -L paths to the linker, which you can list with the following command:
gcc -print-search-dirs | sed '/^lib/b 1;d;:1;s,/[^/.][^/]*/\.\./,/,;t 1;s,:[^=]*=,:;,;s,;,; ,g' | tr \; \\012
The answers suggesting to use ld.so.conf and ldconfig are not correct because they refer to the paths searched by the runtime dynamic linker (i.e. whenever a program is executed), which is not the same as the path searched by ld (i.e. whenever a program is linked).
You can follow this code. Immutable way array clone. This is the perfect way to array cloning
const array = [1, 2, 3, 4]
const newArray = [...array]
newArray.push(6)
console.log(array)
console.log(newArray)
You could also do something as follow
public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
or
EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).
For the validation, I had to use Apache's EnumUtils
library since the type of enum is not known at compile time.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
Set<String> notAllowedNames = enumNames.stream()
.filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
.collect(Collectors.toSet());
if (notAllowedNames.size() > 0) {
String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
.collect(Collectors.joining(", "));
throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
.collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
+ "of the following : " + validEnumNames);
}
}
I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551
After declaring the array
int boardAux[length][length];
the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy
int i, j;
for (i = 0; i<length; i++)
{
for (j = 0; j<length; j++)
boardAux[i][j] = 0;
}
It's very simple,
just run the following commands
sudo a2enmod ssl
sudo service apache2 restart
sudo a2ensite default-ssl.conf
That's it, you are done.
If you want to force SSL (to use https always), edit the file:
sudo nano /etc/apache2/sites-available/000-default.conf
and add this one line
<VirtualHost *:80>
. . .
Redirect "/" "https://your_domain_or_IP/"
. . .
</VirtualHost>
then restart again
sudo service apache2 restart
Make #container
to display:inline-block
#container {
height: auto;
width: 100%;
display: inline-block;
}
#content {
height: auto;
width: 500px;
margin-left: auto;
margin-right: auto;
}
#backgroundContainer {
height: 200px; /*200px is example, change to what you want*/
width: 100%;
}
Also see: W3Schools
I was facing similar issue and found out that this error was due to incorrect rules set for read/write operations for real time database. By default google firebase nowadays loads cloud store not real time database. We need to switch to real time and apply the correct rules.
As we can see it says cloud Firestore not real time database, once switched to correct database apply below rules:
{
"rules": {
".read": true,
".write": true
}
}
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
Just grep:
echo 'abcdef' | grep -Po "^.." # ab
This page explains it pretty well.
As a numeric
the allowable range that can be stored in that field is -10^38 +1
to 10^38 - 1
.
The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.
The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.
So the range that can be stored in this particular field is -(10^18 - 1)
to (10^18 - 1)
Or -999999999999999999
to 999999999999999999
Integers only
You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.
My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries.
Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID
WHERE p.isactive = 1
The better version of this query is :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1
(Assuming isactive is a field in product table which represents the active/inactive products).
I also had this issue and what I did was create an AlertDialog and use the setItems() method along with the DialogInterface listener:
AlertDialog.Builder getImageFrom = new AlertDialog.Builder(Fotos.this);
getImageFrom.setTitle("Select:");
final CharSequence[] opsChars = {getResources().getString(R.string.takepic), getResources().getString(R.string.opengallery)};
getImageFrom.setItems(opsChars, new android.content.DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}else
if(which == 1){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
getResources().getString(R.string.pickgallery)), SELECT_PICTURE);
}
dialog.dismiss();
}
});
You can force it to push, but please do this ONLY when you're quite sure what you are doing.
The command is:
git push -f
Restricting to few lines will work in almost all browsers, but an ellipsis(3 dots) will not be displayed in Firefox & IE. Demo - http://jsfiddle.net/ahzo4b91/1/
div {
width: 300px;
height: 2.8em;
line-height: 1.4em;
display: flex;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
}
Using ReactJS ES6 here's the simplest way
shift + enter New Line at any position
enter Blocked
class App extends React.Component {_x000D_
_x000D_
constructor(){_x000D_
super();_x000D_
this.state = {_x000D_
message: 'Enter is blocked'_x000D_
}_x000D_
}_x000D_
onKeyPress = (e) => {_x000D_
if (e.keyCode === 13 && e.shiftKey) {_x000D_
e.preventDefault();_x000D_
let start = e.target.selectionStart,_x000D_
end = e.target.selectionEnd;_x000D_
this.setState(prevState => ({ message:_x000D_
prevState.message.substring(0, start)_x000D_
+ '\n' +_x000D_
prevState.message.substring(end)_x000D_
}),()=>{_x000D_
this.input.selectionStart = this.input.selectionEnd = start + 1;_x000D_
})_x000D_
}else if (e.keyCode === 13) { // block enter_x000D_
e.preventDefault();_x000D_
}_x000D_
_x000D_
};_x000D_
_x000D_
render(){_x000D_
return(_x000D_
<div>_x000D_
New line with shift enter at any position<br />_x000D_
<textarea _x000D_
value={this.state.message}_x000D_
ref={(input)=> this.input = input}_x000D_
onChange={(e)=>this.setState({ message: e.target.value })}_x000D_
onKeyDown={this.onKeyPress}/>_x000D_
</div>_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='root'></div>
_x000D_
If one is on a Linux distro (e.g. CentOS, Debian) then perhaps the most accessible way to find out about core files and related conditions is in the man page. Just run the following command from a terminal:
man 5 core
A FragmentActivity
is a subclass of Activity
that was built for the Android Support Package.
The FragmentActivity
class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager()
and getFragmentManager()
to getSupportLoaderManager()
and getSupportFragmentManager()
respectively.
I know this post is realy old but now that some time and ant versions passed there is a way to do this with basic ant features and i thought i should share it.
It's done via a recursive macrodef that calls nested tasks (even other macros may be called). The only convention is to use a fixed variable name (element here).
<project name="iteration-test" default="execute" xmlns="antlib:org.apache.tools.ant" xmlns:if="ant:if" xmlns:unless="ant:unless">
<macrodef name="iterate">
<attribute name="list" />
<element name="call" implicit="yes" />
<sequential>
<local name="element" />
<local name="tail" />
<local name="hasMoreElements" />
<!-- unless to not get a error on empty lists -->
<loadresource property="element" unless:blank="@{list}" >
<concat>@{list}</concat>
<filterchain>
<replaceregex pattern="([^;]*).*" replace="\1" />
</filterchain>
</loadresource>
<!-- call the tasks that handle the element -->
<call />
<!-- recursion -->
<condition property="hasMoreElements">
<contains string="@{list}" substring=";" />
</condition>
<loadresource property="tail" if:true="${hasMoreElements}">
<concat>@{list}</concat>
<filterchain>
<replaceregex pattern="[^;]*;(.*)" replace="\1" />
</filterchain>
</loadresource>
<iterate list="${tail}" if:true="${hasMoreElements}">
<call />
</iterate>
</sequential>
</macrodef>
<target name="execute">
<fileset id="artifacts.fs" dir="build/lib">
<include name="*.jar" />
<include name="*.war" />
</fileset>
<pathconvert refid="artifacts.fs" property="artifacts.str" />
<echo message="$${artifacts.str}: ${artifacts.str}" />
<!-- unless is required for empty lists to not call the enclosed tasks -->
<iterate list="${artifacts.str}" unless:blank="${artifacts.str}">
<echo message="I see:" />
<echo message="${element}" />
</iterate>
<!-- local variable is now empty -->
<echo message="${element}" />
</target>
</project>
The key features needed where:
I didnt manage to make the delimiter variabel, but this may not be a major downside.
To get elements of a list you have to use list[i]
instead of list(i)
.
If you actually want a small editor for simple housekeeping in a docker, use this in your Dockerfile:
RUN apt-get install -y busybox && ln -s /bin/busybox /bin/vi
I used it on an Ubuntu 18 based docker.
(Of course you might need an RUN apt-get update
before it but if you are making your own Docker file you probably already have that.)
This also works:
^([1-9]|[0-1][0-2])$
[1-9]
matches single digits between 1 and 9
[0-1][0-2]
matches double digits between 10 and 12
There are some good examples here
I tryed all solutions, this works for me:
<style>
@page {
size: A4;
margin: 1cm;
}
.print {
display: none;
}
@media print {
div.fix-break-print-page {
page-break-inside: avoid;
}
.print {
display: block;
}
}
.print:last-child {
page-break-after: auto;
}
</style>
Following looks very simple to me:
model.layers[idx].output
Above is a tensor object, so you can modify it using operations that can be applied to a tensor object.
For example, to get the shape model.layers[idx].output.get_shape()
idx
is the index of the layer and you can find it from model.summary()
I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).
When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.
It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.
You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
/* create new name file */
$filename = uniqid() . "-" . time(); // 5dab1961e93a7-1571494241
$extension = pathinfo( $_FILES["file"]["name"], PATHINFO_EXTENSION ); // jpg
$basename = $filename . "." . $extension; // 5dab1961e93a7_1571494241.jpg
$source = $_FILES["file"]["tmp_name"];
$destination = "../img/imageDirectory/{$basename}";
/* move the file */
move_uploaded_file( $source, $destination );
echo "Stored in: {$destination}";
.switch
{
width: 50px;
height: 30px;
position: relative;
display:inline-block;
}
.switch input
{
display: none;
}
.slider
{
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
cursor: pointer;
background-color: gray;
border-radius: 30px;
}
.slider:before
{
position: absolute;
background-color: #fff;
height: 20px;
width: 20px;
content: "";
left: 5px;
bottom: 5px;
border-radius: 50%;
transition: ease-in-out .5s;
}
.slider:after
{
content: "Off";
color: white;
display: block;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 70%;
transition: all .5s;
font-size: 10px;
font-family: Verdana,sans-serif;
}
input:checked + .slider:after
{
transition: all .5s;
left: 30%;
content: "On"
}
input:checked + .slider
{
background-color: blue;
}
input:checked + .slider:before
{
transform: translateX(20px);
}
**The HTML CODE**
<label class="switch">
<input type="checkbox"/>
<div class="slider">
</div>
</label>
If You want to add long text like activate or Deactivate
just make few changes
.switch
{
width:90px
}
.slider:after
{
left: 60%; //as you want in percenatge
}
input:checked + .slider:after
{
left:40%; //exactly opposite of .slider:after
}
and last
input:checked + .slider:before
{
transform: translateX(60px); //as per your choice but 60px is perfect
}
content as per your choice where you have witten "On" and "Off"
You can write the php code in another file and include it in the proper place where you want it.
AJAX is also used to display HTML content that is formed by PHP into a specified HTML tag.
Using jQuery:
$.ajax({url: "test.php"}).done(function( html ) {
$("#results").append(html);
});
Above code will execute test.php and result will be displayed in the element with id results.
I recommend you to read more about the this keyword.
You cannot expect "this" to select the "select" tag in this case.
What you want to do in this case is use obj.id
to get the id of select tag.
You can do:
git log -S <whatever> --source --all
To find all commits that added or removed the fixed string whatever
. The --all
parameter means to start from every branch and --source
means to show which of those branches led to finding that commit. It's often useful to add -p
to show the patches that each of those commits would introduce as well.
Versions of git since 1.7.4 also have a similar -G
option, which takes a regular expression. This actually has different (and rather more obvious) semantics, explained in this blog post from Junio Hamano.
As thameera points out in the comments, you need to put quotes around the search term if it contains spaces or other special characters, for example:
git log -S 'hello world' --source --all
git log -S "dude, where's my car?" --source --all
Here's an example using -G
to find occurrences of function foo() {
:
git log -G "^(\s)*function foo[(][)](\s)*{$" --source --all
finishAffinity();
System.exit(0);
If you will use only finishAffinity();
without System.exit(0);
your application will quit but the allocated memory will still be in use by your phone, so... if you want a clean and really quit of an app, use both of them.
This is the simplest method and works anywhere, quit the app for real, you can have a lot of activity opened will still quitting all with no problem.
example on a button click
public void exitAppCLICK (View view) {
finishAffinity();
System.exit(0);
}
or if you want something nice, example with an alert dialog with 3 buttons YES NO and CANCEL
// alertdialog for exit the app
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set the title of the Alert Dialog
alertDialogBuilder.setTitle("your title");
// set dialog message
alertDialogBuilder
.setMessage("your message")
.setCancelable(false)
.setPositiveButton("YES"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// what to do if YES is tapped
finishAffinity();
System.exit(0);
}
})
.setNeutralButton("CANCEL"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// code to do on CANCEL tapped
dialog.cancel();
}
})
.setNegativeButton("NO"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// code to do on NO tapped
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
You have an error in you script tag construction, this:
<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
Should look like this:
<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.
UPDATE
But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
I used the command
ansible -i inventory example -m ping -u <your_user_name> --ask-pass
And it will ask for your password.
For anyone who gets the error:
to use the 'ssh' connection type with passwords, you must install the sshpass program
On MacOS, you can follow below instructions to install sshpass:
I just had the same problem and solved it as follows:
alias gitk='/usr/local/git/bin/gitk'
)I'm not sure precisely what you're looking for, but this program:
public class Building
{
public enum StatusType
{
open,
closed,
weird,
};
public string Name { get; set; }
public StatusType Status { get; set; }
}
public static List <Building> buildingList = new List<Building> ()
{
new Building () { Name = "one", Status = Building.StatusType.open },
new Building () { Name = "two", Status = Building.StatusType.closed },
new Building () { Name = "three", Status = Building.StatusType.weird },
new Building () { Name = "four", Status = Building.StatusType.open },
new Building () { Name = "five", Status = Building.StatusType.closed },
new Building () { Name = "six", Status = Building.StatusType.weird },
};
static void Main (string [] args)
{
var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
var q = from building in buildingList
where statusList.Contains (building.Status)
select building;
foreach ( var b in q )
Console.WriteLine ("{0}: {1}", b.Name, b.Status);
}
produces the expected output:
one: open
two: closed
four: open
five: closed
This program compares a string representation of the enum and produces the same output:
public class Building
{
public enum StatusType
{
open,
closed,
weird,
};
public string Name { get; set; }
public string Status { get; set; }
}
public static List <Building> buildingList = new List<Building> ()
{
new Building () { Name = "one", Status = "open" },
new Building () { Name = "two", Status = "closed" },
new Building () { Name = "three", Status = "weird" },
new Building () { Name = "four", Status = "open" },
new Building () { Name = "five", Status = "closed" },
new Building () { Name = "six", Status = "weird" },
};
static void Main (string [] args)
{
var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
var statusStringList = statusList.ConvertAll <string> (st => st.ToString ());
var q = from building in buildingList
where statusStringList.Contains (building.Status)
select building;
foreach ( var b in q )
Console.WriteLine ("{0}: {1}", b.Name, b.Status);
Console.ReadKey ();
}
I created this extension method to convert one IEnumerable to another, but I'm not sure how efficient it is; it may just create a list behind the scenes.
public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
{
foreach ( TSource source in sources )
yield return convert (source);
}
Then you can change the where clause to:
where statusList.ConvertEach <string> (status => status.GetCharValue()).
Contains (v.Status)
and skip creating the List<string>
with ConvertAll ()
at the beginning.
I have ended up using ABCPdf from webSupergoo. It works really well and for about $350 it has saved me hours and hours based on your comments above. Thanks again Daniel and Bratch for your comments.
So simple you can use case statement here.
CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN
CASE WHEN ISSUE_DIVISION is null then "Null Value found" //give your option
Else 1 End
ELSE 0 END As Issue_Division_Result
Something that has helped me: if you have ranges of variables to convert (or just more then one), you can use sapply
.
A bit nonsensical but just for example:
data(cars)
cars[, 1:2] <- sapply(cars[, 1:2], as.factor)
Say columns 3, 6-15 and 37 of you dataframe need to be converted to numeric one could:
dat[, c(3,6:15,37)] <- sapply(dat[, c(3,6:15,37)], as.numeric)
Joke? :)
How about echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
This is my output:
p2> echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
112312
so I guess it's working after all..
There's another important point in constructor chaining: order. Why? Let's say that you have an object being constructed at runtime by a framework that expects it's default constructor. If you want to be able to pass in values while still having the ability to pass in constructor argments when you want, this is extremely useful.
I could for instance have a backing variable that gets set to a default value by my default constructor but has the ability to be overwritten.
public class MyClass
{
private IDependency _myDependency;
MyClass(){ _myDependency = new DefaultDependency(); }
MYClass(IMyDependency dependency) : this() {
_myDependency = dependency; //now our dependency object replaces the defaultDependency
}
}
The deduplication (to select the max T1) and the aggregation need to be done as distinct steps. I've used a CTE since I think this makes it clearer:
;WITH sumCTE
AS
(
SELECT Rel.t2ID, SUM(Price) price
FROM @t1 AS T1
JOIN @relation AS Rel
ON Rel.t1ID=T1.ID
GROUP
BY Rel.t2ID
)
,maxCTE
AS
(
SELECT Rel.t2ID, Rel.t1ID,
ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
FROM @t1 AS T1
JOIN @relation AS Rel
ON Rel.t1ID=T1.ID
)
SELECT T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,sumT1.Price
FROM @t2 AS T2
JOIN sumCTE AS sumT1
ON sumT1.t2ID = t2.ID
JOIN maxCTE AS maxT1
ON maxT1.t2ID = t2.ID
JOIN @t1 AS T1
ON T1.ID = maxT1.t1ID
WHERE maxT1.PriceList = 1
In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:
sc.exe config Service obj= user password= pass
Specyfying the .exe extension, PowerShell bypasses the alias lookup.
HTH
Steps for upgrading to PHP7 on CentOS 6 system. Taken from install-php-7-in-centos-6
To install latest PHP 7, you need to add EPEL and Remi repository to your CentOS 6 system
yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
yum install http://rpms.remirepo.net/enterprise/remi-release-6.rpm
Now install yum-utils, a group of useful tools that enhance yum’s default package management features
yum install yum-utils
In this step, you need to enable Remi repository using yum-config-manager utility, as the default repository for installing PHP.
yum-config-manager --enable remi-php70
If you want to install PHP 7.1 or PHP 7.2 on CentOS 6, just enable it as shown.
yum-config-manager --enable remi-php71
yum-config-manager --enable remi-php72
Then finally install PHP 7 on CentOS 6 with all necessary PHP modules using the following command.
yum install php php-mcrypt php-cli php-gd php-curl php-mysql php-ldap php-zip php-fileinfo
Double check the installed version of PHP on your system as follows.
php -V
If you are having issues when using "type": "module"
in package.json
(described in https://github.com/TypeStrong/ts-node/issues/1007) use the following config:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --loader ts-node/esm --experimental-specifier-resolution ./src/index.ts"
}
or in the command line
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "node --loader ts-node/esm --experimental-specifier-resolution src/index.ts"
$result = mysql_query("select if(exists (SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName'),'Assigned', 'Available')");
I would recommend everyone look into CSS grids. It has been supported by most browsers now since about 2017. Here is a link to some documentation: https://css-tricks.com/snippets/css/complete-guide-grid/ . It is so much easier to keep your page elements where you want them, especially when it comes to responsiveness. It took me all of 20 minutes to learn how to do it, and I'm a newbie!
<div class="grid-div">
<p class="hello">Hello</p>
<p class="world">World</p>
</div>
//begin css//
.grid-div {
display: grid;
grid-template-columns: 50% 50%;
grid-template-rows: 50% 50%;
}
.hello {
grid-column-start: 2;
grid-row-start: 2;
}
.world {
grid-column-start: 1;
grid-row-start: 2;
}
This code will split the page into 4 equal quadrants, placing the "Hello" in the bottom right, and the "World" in the bottom left without having to change their positioning or playing with margins.
This can be extrapolated into very complex grid layouts with overlapping, infinite grids of all sizes, and even grids nested inside grids, without losing control of your elements every time something changes (MS Word I'm looking at you).
Hope this helps whoever still needs it!
$this->validate($request,[
'input_field_name'=>'digits_between:2,5',
]);
Try this it will be work
This might help some who come across this error. If you are working across a VPN and it becomes disconnected, you can also get this error. The simple fix is to reconnect your VPN.
Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#
[Test]
public void ArraysAreRowMajor()
{
var myArray = new int[2,3]
{
{1, 2, 3},
{4, 5, 6}
};
int rows = myArray.GetLength(0);
int columns = myArray.GetLength(1);
Assert.AreEqual(2,rows);
Assert.AreEqual(3,columns);
Assert.AreEqual(1,myArray[0,0]);
Assert.AreEqual(2,myArray[0,1]);
Assert.AreEqual(3,myArray[0,2]);
Assert.AreEqual(4,myArray[1,0]);
Assert.AreEqual(5,myArray[1,1]);
Assert.AreEqual(6,myArray[1,2]);
}
Expanding on this answer How about the following:
<?php
$json = '[{"user_id":13,"username":"stack"},{"user_id":14,"username":"over"}]';
//$json = '12';
function isJson($string) {
json_decode($string);
if(json_last_error() == JSON_ERROR_NONE) {
if(substr($string,0,1) == '[' && substr($string,-1) == ']') { return TRUE; }
else if(substr($string,0,1) == '{' && substr($string,-1) == '}') { return TRUE; }
else { return FALSE; }
}
}
echo isJson($json);
?>
That's probably a requireJS module definition
Check here for more details
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
The <select>
tag creates a dropdown list. You can't put html links inside a dropdown.
However, there are JavaScript libraries that provide similar functionality. Here is one example: http://www.dynamicdrive.com/dynamicindex1/dropmenuindex.htm
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes.Add("style", "cursor:help;");
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Alternate)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#E56E94'");
e.Row.BackColor = Color.FromName("#E56E94");
}
}
else
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='gray'");
e.Row.BackColor = Color.FromName("gray");
}
}
}
Check if password you are using is correct one by running below command
keytool -keypasswd -new temp123 -keystore awsdemo-keystore.jks -storepass temp123 -alias movie-service -keypass changeit
If you are getting below error then your password is wrong
keytool error: java.security.UnrecoverableKeyException: Cannot recover key
This will work for IPv4 and IPv6:
^(([0-9a-f]{0,4}:){1,7}[0-9a-f]{1,4}|([0-9]{1,3}\.){3}[0-9]{1,3})$
In my case I had to start a list of exclude extensions from the second line because xcopy ignored the first line.
If NEW_TABLE already exists then ...
insert into new_table
select * from old_table
/
If you want to create NEW_TABLE based on the records in OLD_TABLE ...
create table new_table as
select * from old_table
/
If the purpose is to create a new but empty table then use a WHERE clause with a condition which can never be true:
create table new_table as
select * from old_table
where 1 = 2
/
Remember that CREATE TABLE ... AS SELECT creates only a table with the same projection as the source table. The new table does not have any constraints, triggers or indexes which the original table might have. Those still have to be added manually (if they are required).
I realize I'm quite late to the party, and since language wasn't actually specified, here's a VB.NET solution based on Bimmerbound's answer, in case anyone happens to stumble across this and needs a solution. Note: you need to have a reference to the stringbuilder class in your project, if you don't already.
Shared Function returnSerializedXML(ByVal obj As Object) As String
Dim xmlSerializer As New System.Xml.Serialization.XmlSerializer(obj.GetType())
Dim xmlSb As New StringBuilder
Using textWriter As New IO.StringWriter(xmlSb)
xmlSerializer.Serialize(textWriter, obj)
End Using
returnSerializedXML = xmlSb.ToString().Replace(vbCrLf, "")
End Function
Simply call the function and it will return a string with the serialized xml of the object you're attempting to pass to the web service (realistically, this should work for any object you care to throw at it too).
As a side note, the replace call in the function before returning the xml is to strip out vbCrLf characters from the output. Mine had a bunch of them within the generated xml however this will obviously vary depending on what you're trying to serialize, and i think they might be stripped out during the object being sent to the web service.
Using bash regular expressions:
re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi
Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.
re="http://([^/]+)/"
This is the regular expression stored in a bash variable, re
- i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:
http://
is just a string - the input string must contain this substring for the regular expression to match[]
Normally square brackets are used say "match any character within the brackets". So c[ao]t
would match both "cat" and "cot". The ^
character within the []
modifies this to say "match any character except those within the square brackets. So in this case [^/]
will match any character apart from "/".+
to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+
matches 1 or more of the set of all characters, excluding "/".()
parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:
if [[ $name =~ $re ]]; then
echo ${BASH_REMATCH[1]}
fi
In bash, the [[ ]]
specify an extended conditional test, and may contain the =~
bash regular expression operator. In this case we test whether the input string $name
matches the regular expression $re
. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()
), and we can access it using the BASH_REMATCH array:
${BASH_REMATCH[0]}
will be the entire string matched by the regular expression, i.e. "http://www.google.com/".()
within a regular expression - The BASH_REMATCH
elements will correspond to these in order. So in this case ${BASH_REMATCH[1]}
will contain "www.google.com", which I think is the string you want.Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~
operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.
This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.
Note that instead of setting the $re
variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~
match operator.
Simplest Way (no additional library required)
Kotlin:
var handler = Handler()
var isAppInBackground = true
override fun onStop() {
super.onStop()
handler.postDelayed({ isAppInBackground = true },2000)
}
override fun onDestroy() {
super.onDestroy()
handler.removeCallbacksAndMessages(null)
isAppInBackground = false
}
Java:
Handler handler = new Handler();
boolean isAppInBackground = true;
@Override
public void onStop() {
super.onStop();
handler.postDelayed(() -> { isAppInBackground = true; },2000);
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
isAppInBackground = false;
}
val = val < MIN ? MIN : ( val > MAX ? MAX : val);
By iterating I learned that the Token field and the token in an endpoint can be the same. So I set them to be the same as the user token and it works! Also check that the user has privileges to make a job.
Anyway, you can check access.log and see if Bitbucket makes a try or not.
P.S. Also a link to Bitbucket Documentation. May some day it will become more useful.
Add a parameter of type UriComponentsBuilder
to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo
to point at a different controller using the same prefix).
Going Relative:
Going Absolute:
From the SQL Server Management Studio you can right click on your database and select:
Tasks -> Generate Scripts
Then simply proceed through the wizard. Make sure to set 'Script Data' to TRUE when prompted to choose the script options.
Further reading:
I'm running python 3.5 and subprocess.call(['./test.sh']) doesn't work for me.
I give you three solutions depends on what you wanna do with the output.
1 - call script. You will see output in your terminal. output is a number.
import subprocess
output = subprocess.call(['test.sh'])
2 - call and dump execution and error into string. You don't see execution in your terminal unless you print(stdout). Shell=True as argument in Popen doesn't work for me.
import subprocess
from subprocess import Popen, PIPE
session = subprocess.Popen(['test.sh'], stdout=PIPE, stderr=PIPE)
stdout, stderr = session.communicate()
if stderr:
raise Exception("Error "+str(stderr))
3 - call script and dump the echo commands of temp.txt in temp_file
import subprocess
temp_file = open("temp.txt",'w')
subprocess.call([executable], stdout=temp_file)
with open("temp.txt",'r') as file:
output = file.read()
print(output)
Don't forget to take a look at the doc subprocess
Search for the "datalist" tag.
<input list="texto_pronto" name="input_normal">
<datalist id="texto_pronto">
<option value="texto A">
<option value="texto B">
</datalist>
You can always use an attribute selector. The selector itself would look something like:
a[data-item-id=stand-out]
Usage:
Define field in class
let getLocation = GetLocation()
Use in function of class by simple code:
getLocation.run {
if let location = $0 {
print("location = \(location.coordinate.latitude) \(location.coordinate.longitude)")
} else {
print("Get Location failed \(getLocation.didFailWithError)")
}
}
Class:
import CoreLocation
public class GetLocation: NSObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
var locationCallback: ((CLLocation?) -> Void)!
var locationServicesEnabled = false
var didFailWithError: Error?
public func run(callback: @escaping (CLLocation?) -> Void) {
locationCallback = callback
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
manager.requestWhenInUseAuthorization()
locationServicesEnabled = CLLocationManager.locationServicesEnabled()
if locationServicesEnabled { manager.startUpdatingLocation() }
else { locationCallback(nil) }
}
public func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
locationCallback(locations.last!)
manager.stopUpdatingLocation()
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
didFailWithError = error
locationCallback(nil)
manager.stopUpdatingLocation()
}
deinit {
manager.stopUpdatingLocation()
}
}
Don't forget to add the "NSLocationWhenInUseUsageDescription" in the info.plist.
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime
and strftime
behavior to better understand how python processes dates and time field
If you have a table called memos that has two columns id
and text
you should be able to do like this:
INSERT INTO memos(id,text)
SELECT 5, 'text to insert'
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');
If a record already contains a row where text
is equal to 'text to insert' and id
is equal to 5, then the insert operation will be ignored.
I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.
I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer
below.
Don't know exactly what kind of dataset you have, so I provide general answer.
x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
x y
1 1 1
2 2 2
3 NA 3
4 3 NA
5 4 6
6 5 8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
x y
1 1 1
2 2 2
5 4 6
6 5 8
I noticed one answer that was similar, but in my case I used the IIS Configured Editor to find the section I wanted to "unlock".
Then I copied the path and used it in my automation to unlock it prior to changing the sections I wanted to edit.
. "$($env:windir)\system32\inetsrv\appcmd" unlock config -section:system.webServer/security/authentication/windowsAuthentication
. "$($env:windir)\system32\inetsrv\appcmd" unlock config -section:system.webServer/security/authentication/anonymousAuthentication
You can use a constructor with no parameters in your Parent class :
public parent() { }
Value to val
variable can be assigned only once.
val address = Address("Bangalore","India")
address = Address("Delhi","India") // Error, Reassigning is not possible with val
Though you can't reassign the value but you can certainly modify the properties of the object.
//Given that city and country are not val
address.setCity("Delhi")
address.setCountry("India")
That means you can't change the object reference to which the variable is pointing but the underlying properties of that variable can be changed.
Value to var variable can be reassigned as many times as you want.
var address = Address("Bangalore","India")
address = Address("Delhi","India") // No Error , Reassigning possible.
Obviously, It's underlying properties can be changed as long as they are not declared val.
//Given that city and country are not val
address.setCity("Delhi")
address.setCountry("India")
JavaScript doesn't have a native StringBuffer object, so I'm assuming this is from a library you are using, or a feature of an unusual host environment (i.e. not a browser).
I doubt a library (written in JS) would produce anything faster, although a native StringBuffer object might. The definitive answer can be found with a profiler (if you are running in a browser then Firebug will provide you with a profiler for the JS engine found in Firefox).
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
If you need to hit the database, you need to hit the web server again (for the most part).
What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.
AJAX calls can be made in jquery with the $.ajax() function call, so this will happen
User's browser enters input that fires a trigger that makes an AJAX call
$('input .callAjax').bind('change', function() {
$.ajax({ url: 'script/ajax',
type: json
data: $foo,
success: function(data) {
$('input .targetAjax').val(data.newValue);
});
);
Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.
You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.
The php function json_encode($phpobj); will be useful.
I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.
The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception
, you might call Logger.error
. If you want to print the value of a variable at any given point, you might call Logger.debug
. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.
In the case of log4j at least, the ordering of log levels is:
DEBUG < INFO < WARN < ERROR < FATAL
Here is a short example from that article demonstrating how log levels work.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
// Now set its level. Normally you do not need to set the
// level of a logger programmatically. This is usually done
// in configuration files.
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.foo.Bar");
// This request is enabled, because WARN >= INFO.
logger.warn("Low fuel level.");
// This request is disabled, because DEBUG < INFO.
logger.debug("Starting search for nearest gas station.");
// The logger instance barlogger, named "com.foo.Bar",
// will inherit its level from the logger named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO.
barlogger.info("Located nearest gas station.");
// This request is disabled, because DEBUG < INFO.
barlogger.debug("Exiting gas station search");
Well System.Reflection.MethodBase.GetCurrentMethod().Name
is not a very good choice 'cause it will just display the method name without additional information.
Like for string MyMethod(string str)
the above property will return just MyMethod
which is hardly adequate.
It is better to use System.Reflection.MethodBase.GetCurrentMethod().ToString()
which will return the entire method signature...
For turning off line numbers, any of these commands will work:
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
try
{
String datestr="06/27/2007";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/dd/yyyy");
date = (Date)formatter.parse(datestr);
}
catch (Exception e)
{}
month is MM, minutes is mm..
You could use strcpy()
, like so:
strcpy(tab2, tmp.c_str());
Watch out for buffer overflow.
I had a similar problem when I needed to make multiple sql queries. The problem was that some queries did not return the result and I wanted to print that result. And there was a mistake. As already written, there are several solutions.
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT
As well as:
exist = cursor.fetchone()
if exist is None:
... # does not exist
else:
... # exists
One of the solutions is:
The try
and except
block lets you handle the error
/exceptions
. The finally
block lets you execute code, regardless of the result of the try
and except
blocks.
So the presented problem can be solved by using it.
s = """ set current query acceleration = enable;
set current GET_ACCEL_ARCHIVE = yes;
SELECT * FROM TABLE_NAME;"""
query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
print(f"Executing SQL statements ====> {sql} <=====")
cursor.execute(sql)
print(f"SQL ====> {sql} <===== was executed successfully")
try:
print("\n****************** RESULT ***********************")
for result in cursor.fetchall():
print(result)
print("****************** END RESULT ***********************\n")
except Exception as e:
print(f"SQL: ====> {sql} <==== doesn't have output!\n")
# print(str(e))
output:
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!
Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!
Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====
****************** RESULT ***********************
---------- DATA ----------
****************** END RESULT ***********************
The example above only presents a simple use as an idea that could help with your solution. Of course, you should also pay attention to other errors, such as the correctness of the query, etc.
You need to turn on "Allow less secure apps" from here https://myaccount.google.com/lesssecureapps
Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/
That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.
$('.bwWrapper').BlackAndWhite({
hoverEffect : true, // default true
// set the path to BnWWorker.js for a superfast implementation
webworkerPath : false,
// to invert the hover effect
invertHoverEffect: false,
// this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
intensity:1,
speed: { //this property could also be just speed: value for both fadeIn and fadeOut
fadeIn: 200, // 200ms for fadeIn animations
fadeOut: 800 // 800ms for fadeOut animations
},
onImageReady:function(img) {
// this callback gets executed anytime an image is converted
}
});
There's no need for a regular expression but you do want to use string formatting rather than the string concatenation in the accepted answer.
This is probably the most canonical, Pythonic way to truncate the string data
at 75 characters.
>>> data = "saddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
>>> info = "{}..".format(data[:75]) if len(data) > 75 else data
>>> info
'111111111122222222223333333333444444444455555555556666666666777777777788888...'
Just in case you are not sure the string starts with a word...
$input = ' Test me more ';
echo preg_replace('/(\s*)([^\s]*)(.*)/', '$2', $input); //Test
I have seen people use Throwable to catch some errors that might happen due to infra failure/ non availability.
That's called SQL INJECTION. The '
tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.
for example,
instead of this:
"VALUES ('$sender_id') "
do this:
"VALUES ('". mysql_real_escape_string($sender_id) ."') "
(or equivalent, of course)
However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).
Hope it helps. Cheers
I have had some problems in Swift 5 with this. When using this function I had a wrong alignment with the header cell:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
return headerCell
}
The cell view was shown with a bad alignment and the top part of the tableview was shown. So I had to make some tweak like this:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 90))
let headerCell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER")
headerCell?.frame = headerView.bounds
headerView.addSubview(headerCell!)
return headerView
}
I am having this problem in Swift 5 and Xcode 12.0.1, I don't know if it is just a problem for me or it is a bug. Hope it helps ! I have lost a morning...
Somehow even Webstorm made it like this import {of} from 'rxjs/observable/of';
and everything started to work
You can use the method from Bouncy Castle Provider library:
org.bouncycastle.util.encoders.Hex.toHexString(byteArray);
The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms. This jar contains JCE provider and lightweight API for the Bouncy Castle Cryptography APIs for JDK 1.5 to JDK 1.8.
Maven dependency:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.60</version>
</dependency>
or from Apache Commons Codec:
org.apache.commons.codec.binary.Hex.encodeHexString(byteArray);
The Apache Commons Codec package contains simple encoder and decoders for various formats such as Base64 and Hexadecimal. In addition to these widely used encoders and decoders, the codec package also maintains a collection of phonetic encoding utilities.
Maven dependency:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
var query = list.Where(r => listofIds.Any(id => id == r.Id));
Another approach, useful if the listOfIds array is large:
HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));
Take a look at bash(1)
, you need a login shell to pickup the ~/.profile
, i.e. the -l
option.
If you search Google for the version you want, you should be able to find a download link. For example, Android NDK r5b is available at http://androgeek.info/?p=296
On another note, it might be a good idea to look at why your code doesn't compile against the latest version and fix it.
How are you doing the compiling and linking? You'll need to specify both files, something like:
gcc testpoint.c point.c
...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main
. You'll need/want to eliminate one (undoubtedly the one in point.c).
In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make
to do the work. In this case you'd have something like this:
OBJS=testpoint.o point.o
testpoint.exe: $(OBJS)
gcc $(OJBS)
The first is just a macro for the names of the object files. You get it expanded with $(OBJS)
. The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.
Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:
.c.o:
$(CC) -c $(CFLAGS) $<
This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc
) and allows you to specify any flags you care about in a macro named CFLAGS
(e.g., CFLAGS=-O3
to turn on optimization) and $<
is a special macro that expands to the name of the source file.
You typically store this in a file named Makefile
, and to build your program, you just type make
at the command line. It implicitly looks for a file named Makefile
, and runs whatever rules it contains.
The good point of this is that make
automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).
Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.
This works really well:
<td><div style = "width:80px; word-wrap: break-word"> your text </div></td>
You can use the same width for all your <div
's, or adjust the width in each case to break your text wherever you like.
This way you do not have to fool around with fixed table widths, or complex css.
You may use pattern
defined in the additional-methods.js
file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use
$("#frm").validate({_x000D_
rules: {_x000D_
Textbox: {_x000D_
pattern: /^[a-zA-Z'.\s]{1,40}$/_x000D_
},_x000D_
},_x000D_
messages: {_x000D_
Textbox: {_x000D_
pattern: 'The Textbox string format is invalid'_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>_x000D_
<form id="frm" method="get" action="">_x000D_
<fieldset>_x000D_
<p>_x000D_
<label for="fullname">Textbox</label>_x000D_
<input id="Textbox" name="Textbox" type="text">_x000D_
</p>_x000D_
</fieldset>_x000D_
</form>
_x000D_
Set the path of adb into System Variables. You can find adb in "ADT Bundle/sdk/platform-tools" Set the path and restart the cmd n then try again.
Or
You can also goto the dir where adb.exe is located and do the same thing if you don't wanna set the PATH.
If you wanna see all the paths, just do
echo %PATH%