What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
ItemDecoration
Static headers can easily be added with an ItemDecoration
and without any further changes.
// add the decoration. done.
HeaderDecoration headerDecoration = new HeaderDecoration(/* init */);
recyclerView.addItemDecoration(headerDecoration);
The decoration is also reusable since there is no need to modify the adapter or the RecyclerView
at all.
The sample code provided below will require a view to add to the top which can just be inflated like everything else. It can look like this:
If you just have to display text and images this solution is for you—there is no possibility for user interaction like buttons or view pagers, since it will just be drawn to top of your list.
If there is no view to decorate, the decoration will not be drawn. You will still have to handle an empty list yourself. (One possible workaround would be to add a dummy item to the adapter.)
You can find the full source code here on GitHub including a Builder
to help with the initialization of the decorator, or just use the code below and supply your own values to the constructor.
Please be sure to set a correct layout_height
for your view. e.g. match_parent
might not work properly.
public class HeaderDecoration extends RecyclerView.ItemDecoration {
private final View mView;
private final boolean mHorizontal;
private final float mParallax;
private final float mShadowSize;
private final int mColumns;
private final Paint mShadowPaint;
public HeaderDecoration(View view, boolean scrollsHorizontally, float parallax, float shadowSize, int columns) {
mView = view;
mHorizontal = scrollsHorizontally;
mParallax = parallax;
mShadowSize = shadowSize;
mColumns = columns;
if (mShadowSize > 0) {
mShadowPaint = new Paint();
mShadowPaint.setShader(mHorizontal ?
new LinearGradient(mShadowSize, 0, 0, 0,
new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
new float[]{0f, .5f, 1f},
Shader.TileMode.CLAMP) :
new LinearGradient(0, mShadowSize, 0, 0,
new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
new float[]{0f, .5f, 1f},
Shader.TileMode.CLAMP));
} else {
mShadowPaint = null;
}
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
// layout basically just gets drawn on the reserved space on top of the first view
mView.layout(parent.getLeft(), 0, parent.getRight(), mView.getMeasuredHeight());
for (int i = 0; i < parent.getChildCount(); i++) {
View view = parent.getChildAt(i);
if (parent.getChildAdapterPosition(view) == 0) {
c.save();
if (mHorizontal) {
c.clipRect(parent.getLeft(), parent.getTop(), view.getLeft(), parent.getBottom());
final int width = mView.getMeasuredWidth();
final float left = (view.getLeft() - width) * mParallax;
c.translate(left, 0);
mView.draw(c);
if (mShadowSize > 0) {
c.translate(view.getLeft() - left - mShadowSize, 0);
c.drawRect(parent.getLeft(), parent.getTop(), mShadowSize, parent.getBottom(), mShadowPaint);
}
} else {
c.clipRect(parent.getLeft(), parent.getTop(), parent.getRight(), view.getTop());
final int height = mView.getMeasuredHeight();
final float top = (view.getTop() - height) * mParallax;
c.translate(0, top);
mView.draw(c);
if (mShadowSize > 0) {
c.translate(0, view.getTop() - top - mShadowSize);
c.drawRect(parent.getLeft(), parent.getTop(), parent.getRight(), mShadowSize, mShadowPaint);
}
}
c.restore();
break;
}
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) < mColumns) {
if (mHorizontal) {
if (mView.getMeasuredWidth() <= 0) {
mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
}
outRect.set(mView.getMeasuredWidth(), 0, 0, 0);
} else {
if (mView.getMeasuredHeight() <= 0) {
mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
}
outRect.set(0, mView.getMeasuredHeight(), 0, 0);
}
} else {
outRect.setEmpty();
}
}
}
Please note: The GitHub project is my personal playground. It is not thorougly tested, which is why there is no library yet.
An ItemDecoration
is additional drawing to an item of a list. In this case, a decoration is drawn to the top of the first item.
The view gets measured and laid out, then it is drawn to the top of the first item. If a parallax effect is added it will also be clipped to the correct bounds.
The first code line, Option Explicit
means (in simple terms) that all of your variables have to be explicitly declared by Dim
statements. They can be any type, including object, integer, string, or even a variant.
This line: Dim envFrmwrkPath As Range
is declaring the variable envFrmwrkPath
of type Range
. This means that you can only set it to a range.
This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value
is attempting to set the Range
type variable to a specific Value that is in cell D6
. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.
I'm assuming you want the value stored in a variable. Try something like this:
Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value
This assumes you have a number (like 5) in cell D6. Now your variable will have the value.
For simplicity sake of learning, you can remove or comment out the Option Explicit
line and VBA will try to determine the type of variables at run time.
Try this to get through this part of your code
Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String
import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)
A quick way to decode it without importing anything:
'eW91ciB0ZXh0'.decode('base64')
or more descriptive
>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'
Sounds like you need to grant the execute permission to the user (or a group that they a part of) for the stored procedure in question.
For example, you could grant access thus:
USE zzzzzzz;
GRANT EXEC ON dbo.xxxxxxx TO PUBLIC
called_from
must be null
. Add a test against that condition like
if (called_from != null && called_from.equalsIgnoreCase("add")) {
or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null
behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)
if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null
With the module pygame.draw shapes like rectangles, circles, polygons, liens, ellipses or arcs can be drawn. Some examples:
pygame.draw.rect
draws filled rectangular shapes or outlines. The arguments are the target Surface (i.s. the display), the color, the rectangle and the optional outline width. The rectangle argument is a tuple with the 4 components (x, y, width, height), where (x, y) is the upper left point of the rectangle. Alternatively, the argument can be a pygame.Rect
object:
pygame.draw.rect(window, color, (x, y, width, height))
rectangle = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, rectangle)
pygame.draw.circle
draws filled circles or outlines. The arguments are the target Surface (i.s. the display), the color, the center, the radius and the optional outline width. The center argument is a tuple with the 2 components (x, y):
pygame.draw.circle(window, color, (x, y), radius)
pygame.draw.polygon
draws filled polygons or contours. The arguments are the target Surface (i.s. the display), the color, a list of points and the optional contour width. Each point is a tuple with the 2 components (x, y):
pygame.draw.polygon(window, color, [(x1, y1), (x2, y2), (x3, y3)])
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((255, 255, 255))
pygame.draw.rect(window, (0, 0, 255), (20, 20, 160, 160))
pygame.draw.circle(window, (255, 0, 0), (100, 100), 80)
pygame.draw.polygon(window, (255, 255, 0),
[(100, 20), (100 + 0.8660 * 80, 140), (100 - 0.8660 * 80, 140)])
pygame.display.flip()
pygame.quit()
exit()
To accept both @PathVariable
and @RequestParam
in the same /user
endpoint:
@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
@RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Testing with curl:
When elements are positioned outside the normal flow, they can overlap other elements.
according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp
if column = None
COLUMN_OLD_VALUE
----------------
None
1
None
100
20
------------------
Use create a temptable on data frame:
sqlContext.sql("select * from tempTable where column_old_value='None' ").show()
So use : column_old_value='None'
Neither. You set the isolation level to READ UNCOMMITTED
which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.
Try this runner I wrote. It could be helpful.
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class ProxyAuthHelper {
public static void main(String[] args) throws Exception {
String tmp = System.getProperty("http.proxyUser", System.getProperty("https.proxyUser"));
if (tmp == null) {
System.out.println("Proxy username: ");
tmp = new Scanner(System.in).nextLine();
}
final String userName = tmp;
tmp = System.getProperty("http.proxyPassword", System.getProperty("https.proxyPassword"));
if (tmp == null) {
System.out.println("Proxy password: ");
tmp = new Scanner(System.in).nextLine();
}
final char[] password = tmp.toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("\n--------------\nProxy auth: " + userName);
return new PasswordAuthentication (userName, password);
}
});
Class<?> clazz = Class.forName(args[0]);
Method method = clazz.getMethod("main", String[].class);
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
method.invoke(null, new Object[]{newArgs});
}
}
In phpMyAdmin, navigate to the table in question and click the "Operations" tab. On the left under Table Options you will be allowed to set the current AUTO_INCREMENT value.
While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.
I made an answer for this already, but I think it can help here too..
Regex In C To Search For Credit Card Numbers
// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h
#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>
int main(){
bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;
char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";
pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked.
subject_length = strlen((char *)subject);
re = pcre2_compile(
pattern, /* the pattern */
PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
0, /* default options */
&errornumber, /* for error number */
&erroroffset, /* for error offset */
NULL); /* use default compile context */
/* Compilation failed: print the error message and exit. */
if (re == NULL)
{
PCRE2_UCHAR buffer[256];
pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
return 1;
}
match_data = pcre2_match_data_create_from_pattern(re, NULL);
rc = pcre2_match(
re,
subject, /* the subject string */
subject_length, /* the length of the subject */
0, /* start at offset 0 in the subject */
0, /* default options */
match_data, /* block for storing the result */
NULL);
if (rc < 0)
{
switch(rc)
{
case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
pcre2_match_data_free(match_data);
pcre2_code_free(re);
Found = 0;
return Found;
// break;
/*
Handle other special cases if you like
*/
default: printf("Matching error %d\n", rc); //break;
}
pcre2_match_data_free(match_data); /* Release memory used for the match */
pcre2_code_free(re);
Found = 0; /* data and the compiled pattern. */
return Found;
}
if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);
if (rc == 0)
printf("ovector was not big enough for all the captured substrings\n");
if (ovector[0] > ovector[1])
{
printf("\\K was used in an assertion to set the match start after its end.\n"
"From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
(char *)(subject + ovector[1]));
printf("Run abandoned\n");
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return 0;
}
for (i = 0; i < rc; i++)
{
PCRE2_SPTR substring_start = subject + ovector[2*i];
size_t substring_length = ovector[2*i+1] - ovector[2*i];
printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
}
}
else{
if(rc > 0){
Found = true;
}
}
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;
}
Install PCRE using:
wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make
sudo make install
sudo ldconfig
Compile using :
gcc foo.c -lpcre2-8 -o foo
Check my answer for more details.
2D array:
int sum(int array[][COLS], int rows)
{
}
3D array:
int sum(int array[][B][C], int A)
{
}
4D array:
int sum(int array[][B][C][D], int A)
{
}
and nD array:
int sum(int ar[][B][C][D][E][F].....[N], int A)
{
}
in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)
e.g.
<?php
//plum or data...
$output = array("data","plum");
echo json_encode($output);
?>
in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
success function(json_data){
var data_array = $.parseJSON(json_data);
//access your data like this:
var plum_or_whatever = data_array['output'];.
//continue from here...
}
});
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
Make sure your controller inherits from Controller
class.
It might even be crazier that stuff would work locally even without that.
@OP,
Is glob pettern not only used for file names?
No, "glob" pattern is not only used for file names. you an use it to compare strings as well. In your examples, you can use case/esac to look for strings patterns.
gg=svm-grid-ch
# looking for the word "grid" in the string $gg
case "$gg" in
*grid* ) echo "found";;
esac
# [[ $gg =~ ^....grid* ]]
case "$gg" in ????grid*) echo "found";; esac
# [[ $gg =~ s...grid* ]]
case "$gg" in s???grid*) echo "found";; esac
In bash, when to use glob pattern and when to use regular expression? Thanks!
Regex are more versatile and "convenient" than "glob patterns", however unless you are doing complex tasks that "globbing/extended globbing" cannot provide easily, then there's no need to use regex.
Regex are not supported for version of bash <3.2 (as dennis mentioned), but you can still use extended globbing (by setting extglob
). for extended globbing, see here and some simple examples here.
Update for OP: Example to find files that start with 2 characters (the dots "." means 1 char) followed by "g" using regex
eg output
$ shopt -s dotglob
$ ls -1 *
abg
degree
..g
$ for file in *; do [[ $file =~ "..g" ]] && echo $file ; done
abg
degree
..g
In the above, the files are matched because their names contain 2 characters followed by "g". (ie ..g
).
The equivalent with globbing will be something like this: (look at reference for meaning of ?
and *
)
$ for file in ??g*; do echo $file; done
abg
degree
..g
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
The obligatory LINQ one[1]-liner:
var max = anArray.Select((value, index) => new {value, index})
.OrderByDescending(vi => vi.value)
.First();
(The sorting is probably a performance hit over the other solutions.)
[1]: For given values of "one".
In order to start an activity which should return result to the calling activity, you should do something like below. You should pass the requestcode as shown below in order to identify that you got the result from the activity you started.
startActivityForResult(new Intent(“YourFullyQualifiedClassName”),requestCode);
In the activity you can make use of setData()
to return result.
Intent data = new Intent();
String text = "Result to be returned...."
//---set the data to pass back---
data.setData(Uri.parse(text));
setResult(RESULT_OK, data);
//---close the activity---
finish();
So then again in the first activity you write the below code in onActivityResult()
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
String returnedResult = data.getData().toString();
// OR
// String returnedResult = data.getDataString();
}
}
}
EDIT based on your comment: If you want to return three strings, then follow this by making use of key/value pairs with intent instead of using Uri.
Intent data = new Intent();
data.putExtra("streetkey","streetname");
data.putExtra("citykey","cityname");
data.putExtra("homekey","homename");
setResult(RESULT_OK,data);
finish();
Get them in onActivityResult like below:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
String street = data.getStringExtra("streetkey");
String city = data.getStringExtra("citykey");
String home = data.getStringExtra("homekey");
}
}
}
Objective-C is a more perfect superset of C. In C and Objective-C implicit casting from void*
to a struct pointer is allowed.
Foo* bar = malloc(sizeof(Foo));
C++ will not compile unless the void
pointer is explicitly cast:
Foo* bar = (Foo*)malloc(sizeof(Foo));
The relevance of this to every day programming is zero, just a fun trivia fact.
It's called and
and or
in Python.
If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:
var d = $.datepicker.parseDate("DD, MM dd, yy", "Sunday, February 28, 2010");
and then follow it up with the formatDate method to get it to the string format you want
var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);
If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.
HTH
SqlCommand.ExecuteNonQuery Method
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements. Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data. For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
SqlCommand.ExecuteScalar Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
So to get no. of statements returned by SELECT statement you have to use ExecuteScalar method.
So try below code:
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
command.Parameters.AddWithValue("@zip","india");
// int result = command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader["id"]));
}
}
conn.Close();
The topic is quite old, yet I struggled with the same issue today while compiling cegui 0.7.1 (openVibe prerequisite).
What worked for me was to set: LDFLAGS="-Wl,--no-as-needed"
in the Makefile.
I've also tried -ldl
for LDFLAGS
but to no avail.
\u0000
is the default value for char type in Java
As others mentioned, you can use comparison to check the value of an uninitialized variable.
char ch;
if(ch==0)
System.out.println("Default value is the null character");
For Mac users using Homebrew (Brew) to install and manage services:
List your Brew services:
brew services
Do something with a service:
brew services start elasticsearch-full
brew services restart elasticsearch-full
brew services stop elasticsearch-full
Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab
. Just google it and you will get the download links.
After downloading it, copy that file to C:\dotnet35
and run the following command.
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
Tested and worked in Windows 10 without any issue.
I am posting a way to use _netrc
to download materials from the site www.course.com.
If someone is going to use the coursera-dl to download the open-class materials on www.coursera.com, and on the Windows OS someone wants to use a file like ".netrc" which is in like-Unix OS to add the option -n
instead of -U <username> -P <password>
for convenience. He/she can do it like this:
Check the home path on Windows OS: setx HOME %USERPROFILE%
(refer to VonC's answer). It will save the HOME
environment variable as C:\Users\"username"
.
Locate into the directory C:\Users\"username"
and create a file name _netrc
.NOTE: there is NOT any suffix.
the content is like: machine coursera-dl login <user> password <pass>
Use a command like coursera-dl -n --path PATH <course name>
to download the class materials. More coursera-dl options details for this page.
mydata$sCode
is a vector, it's why nrow output is NULL.mydata[mydata$sCode == 'CA',]
returns data.frame
where sCode == 'CA'
. sCode includes character. That's why sum
gives you the error.subset(mydata, sCode='CA', select=c(sCode))
, you should use sCode=='CA'
instead sCode='CA'
. Then subset returns you vector where sCode equals CA, so you should use
length(subset(na.omit(mydata), sCode='CA', select=c(sCode)))
Or you can try this: sum(na.omit(mydata$sCode) == "CA")
I added this
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
and it still showed the error, then I realized that in another project the templates was showing without adding that code in settings.py file so I checked that project and I realized that I didn't create a virtual environment in this project so I did
virtualenv env
and it worked, don't know why
I recently discovered a project called OniVim, which is an electron-based front-end for NeoVim that comes with very nice autocomplete for several languages out of the box, and since it's basically just a wrapper around NeoVim, you have the full power of vim at your disposal if the GUI doesn't meet your needs. It's still in early development, but it is rapidly improving and there is a really active community around it. I have been using vim for over 10 years and started giving Oni a test drive a few weeks ago, and while it does have some bugs here and there it hasn't gotten in my way. I would strongly recommend it to new vim users who are still getting their vim-fingers!
OniVim: https://www.onivim.io/
When you make the input, set it to be readonly.
<input type="text" name="datepicker" id="datepicker" readonly="readonly" />
Complete and clear example project http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals It displays create, edit and delete entity operation modals with bootstrap and also includes code to handle result returned from those entity operations (c#, JSON, javascript)
I have the same warning (it's make my app cannot build). When I add C function
in Objective-C's .m file
, But forgot to declared it at .h
file.
You can use the parse()
function to convert the characters into an expression. You need to specify that the input is text, because parse expects a file by default:
eval(parse(text="5+5"))
Easiest method: Alt
+Enter
on
private static final long serialVersionUID = ;
IntelliJ will underline the space after the =
. put your cursor on it and hit alt
+Enter
(Option
+Enter
on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.
Other answers provide pretty concise answer to this, without one important fact: You don't need to implement fixed point combinator in any practical language in this convoluted way and doing so serves no practical purpose (except "look, I know what Y-combinator is"). It's important theoretical concept, but of little practical value.
You can create a large array and then copy it to a new array using System.arrayCopy
int contentLength = 100000000;
byte[] byteArray = new byte[contentLength];
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
while ((bytesRead = inputStream.read()) != -1)
{
byteArray[count++] = (byte)bytesRead;
}
byte[] destArray = new byte[count];
System.arraycopy(byteArray, 0, destArray , 0, count);
destArray will contain the information you want
In case the module you want to import is not in a sub-directory, then try the following and run app.py
from the deepest common parent directory:
Directory Structure:
/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json
In app.py
, append path of client to sys.path:
import os, sys, inspect
sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()
Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)
# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")
Run
user@host:/path/to/common_dir$ python3 application/app.py
This solution works for me in cli, as well as PyCharm.
This is a free library and works very easily : OpenHtmlToPdf
string timeStampForPdfName = DateTime.Now.ToString("yyMMddHHmmssff");
string serverPath = System.Web.Hosting.HostingEnvironment.MapPath("~/FolderName");
string pdfSavePath = Path.Combine(@serverPath, "FileName" + timeStampForPdfName + ".FileExtension");
//OpenHtmlToPdf Library used for Performing PDF Conversion
var pdf = Pdf.From(HTML_String).Content();
//FOr writing to file from a ByteArray
File.WriteAllBytes(pdfSavePath, pdf.ToArray()); // Requires System.Linq
You could use the extension method syntax:
var item = Items.Select(x => x.Id == 123).FirstOrDefault();
Other than that, I'm not sure how much more concise you can get, without maybe writing your own specialized "First" and "FirstOrDefault" extension methods.
If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.
Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.
This is the same question as Failed to connect to mailserver at "localhost" port 25
also check this php mail function not working
Create a branch on the local system with that name. e.g. say you want to get the branch named branch-05142011
git branch branch-05142011 origin/branch-05142011
It'll give you a message:
$ git checkout --track origin/branch-05142011
Branch branch-05142011 set up to track remote branch refs/remotes/origin/branch-05142011.
Switched to a new branch "branch-05142011"
Now just checkout the branch like below and you have the code
git checkout branch-05142011
Put this inside your package's __init__.py file:
# For relative imports to work in Python 3.6
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
Assuming your package is like this:
+-- project
¦ +-- package
¦ ¦ +-- __init__.py
¦ ¦ +-- module1.py
¦ ¦ +-- module2.py
¦ +-- setup.py
Now use regular imports in you package, like:
# in module2.py
from module1 import class1
This works in both python 2 and 3.
tooltips can be used as alerts. These can be timed to appear and disappear.
CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.
Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
This can happen for more than one reason. In my case this happened due to a permissions issue. The user that the task was running as didn't have permission to write to the logs directory so it failed with this error.
Following is small snippet i've created in javascript to convert array of objects to hash map, indexed by attribute value of object. You can provide a function to evaluate the key of hash map dynamically (run time).
function isFunction(func){
return Object.prototype.toString.call(func) === '[object Function]';
}
/**
* This function converts an array to hash map
* @param {String | function} key describes the key to be evaluated in each object to use as key for hasmap
* @returns Object
* @Example
* [{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap("id")
Returns :- Object {123: Object, 345: Object}
[{id:123, name:'naveen'}, {id:345, name:"kumar"}].toHashMap(function(obj){return obj.id+1})
Returns :- Object {124: Object, 346: Object}
*/
Array.prototype.toHashMap = function(key){
var _hashMap = {}, getKey = isFunction(key)?key: function(_obj){return _obj[key];};
this.forEach(function (obj){
_hashMap[getKey(obj)] = obj;
});
return _hashMap;
};
You can find the gist here : https://gist.github.com/naveen-ithappu/c7cd5026f6002131c1fa
Place an apostrophe in front of the date and it should export in the correct format. Just found it out for myself, I found this thread searching for an answer.
If you're using jQuery, it's as simple as this:
$('form').attr('action', 'myNewActionTarget.html');
In jstl we can access the current URL path using pageContext.request.contextPath
. If you want to do an Ajax call, use the following URL.
url = "${pageContext.request.contextPath}" + "/controller/path"
Example: For the page http://stackoverflow.com/posts/36577223
this will give http://stackoverflow.com/controller/path
.
#include <stdio.h>
int main(void)
{
int number = 7; /* signed */
int vbool[8 * sizeof(int)];
int i;
for (i = 0; i < 8 * sizeof(int); i++)
{
vbool[i] = number<<i < 0;
printf("%d", vbool[i]);
}
return 0;
}
Well I was able to install it by :
sudo apt-get install php-curl
on my system. This will install a dependency package, which depends on the default php version.
After that restart apache
sudo service apache2 restart
I you have the char '9'
, it will store its ASCII code, so to get the int value, you have 2 ways
char x = '9';
int y = Character.getNumericValue(x); //use a existing function
System.out.println(y + " " + (y + 1)); // 9 10
or
char x = '9';
int y = x - '0'; // substract '0' code to get the difference
System.out.println(y + " " + (y + 1)); // 9 10
And it fact, this works also :
char x = 9;
System.out.println(">" + x + "<"); //> < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10
You store the 9
code, which corresponds to a horizontal tab
(you can see when print as String
, bu you can also use it as int
as you see above
Try:
<table border="1">
<tr>
<td>
<table border="">
...
</table>
</td>
</tr>
</table>
You Can try this way
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());
I've used PDFBox with good success. Here's a sample of what the code looks like (back from version 0.7.2), that likely came from one of the provided examples:
// load the document
System.out.println("Reading document: " + filename);
PDDocument doc = null;
doc = PDDocument.load(filename);
// look at all the document information
PDDocumentInformation info = doc.getDocumentInformation();
COSDictionary dict = info.getDictionary();
List l = dict.keyList();
for (Object o : l) {
//System.out.println(o.toString() + " " + dict.getString(o));
System.out.println(o.toString());
}
// look at the document catalog
PDDocumentCatalog cat = doc.getDocumentCatalog();
System.out.println("Catalog:" + cat);
List<PDPage> lp = cat.getAllPages();
System.out.println("# Pages: " + lp.size());
PDPage page = lp.get(4);
System.out.println("Page: " + page);
System.out.println("\tCropBox: " + page.getCropBox());
System.out.println("\tMediaBox: " + page.getMediaBox());
System.out.println("\tResources: " + page.getResources());
System.out.println("\tRotation: " + page.getRotation());
System.out.println("\tArtBox: " + page.getArtBox());
System.out.println("\tBleedBox: " + page.getBleedBox());
System.out.println("\tContents: " + page.getContents());
System.out.println("\tTrimBox: " + page.getTrimBox());
List<PDAnnotation> la = page.getAnnotations();
System.out.println("\t# Annotations: " + la.size());
Starting with the repo in the original state
To remove the merge commit and squash the branch into a single commit in the mainline
Use these commands (replacing 5 and 1 with the SHAs of the corresponding commits):
git checkout 5
git reset --soft 1
git commit --amend -m '1 2 3 4 5'
git rebase HEAD master
To retain a merge commit but squash the branch commits into one:
Use these commands (replacing 5, 1 and C with the SHAs of the corresponding commits):
git checkout -b tempbranch 5
git reset --soft 1
git commit --amend -m '1 2 3 4 5'
git checkout C
git merge --no-ff tempbranch
git rebase HEAD master
To remove the merge commit and replace it with individual commits from the branch
Just do (replacing 5 with the SHA of the corresponding commit):
git rebase 5 master
And finally, to remove the branch entirely
Use this command (replacing C and D with the SHAs of the corresponding commits):
git rebase --onto C D~ master
start from
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array
member
Iterating
for(int i = 0; i < deletedtrs_array.length(); i++){
JSONObject obj = deletedtrs_array.getJSONObject(i);
Log.d("Item no."+i, obj.toString());
// create object of type DeletedTrsWrapper like this
DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);
// String company_id = obj.getString("companyid");
// String username = obj.getString("username");
// String date = obj.getString("date");
// int report_id = obj.getInt("reportid");
}
Own object type
class DeletedTrsWrapper {
public String company_id;
public String username;
public String date;
public int report_id;
public DeletedTrsWrapper(JSONObject obj){
company_id = obj.getString("companyid");
username = obj.getString("username");
date = obj.getString("date");
report_id = obj.getInt("reportid");
}
}
I think your only option is to wrap java in a script that substitutes the environment variables into the command line
If you're only interested in the keys, you can iterate through the keySet()
of the map:
Map<String, Object> map = ...;
for (String key : map.keySet()) {
// ...
}
If you only need the values, use values()
:
for (Object value : map.values()) {
// ...
}
Finally, if you want both the key and value, use entrySet()
:
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry
).
I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :)
This is what list comprehensions are for:
numbers = [ int(x) for x in numbers ]
If you want to execute all the commands, whether the previous one executes or not, you can use semicolon (;) to separate the commands.
cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install
If you want to execute the next command only if the previous command succeeds, then you can use && to separate the commands.
cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install
In your case, the execution of consecutive commands seems to depend upon the previous commands, so use the second example i.e. use && to join the commands.
SELECT tem.name, COUNT(*)
FROM (
SELECT name FROM results
UNION ALL
SELECT name FROM archive_results
) AS tem
GROUP BY name
ORDER BY name
If you don't want to use a watcher, you can do something like this:
<input type='checkbox' ng-init='checkStatus=false' ng-model='checkStatus' ng-click='doIfChecked(checkStatus)'>
Use :
$(this).parent().css("background-image", "url(/images/r-srchbg_white.png) no-repeat;");
instead of
$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat;");
More examples you cand see here
The length of the array is 7, the NUL character \0
still counts as a character and the string is still terminated with an implicit \0
See this link to see a working example
Note that had you declared str
as char str[6]= "Hello\0";
the length would be 6 because the implicit NUL is only added if it can fit (which it can't in this example.)
§ 6.7.8/p14
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Sucessive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
char str[] = "Hello\0"; /* sizeof == 7, Explicit + Implicit NUL */
char str[5]= "Hello\0"; /* sizeof == 5, str is "Hello" with no NUL (no longer a C-string, just an array of char). This may trigger compiler warning */
char str[6]= "Hello\0"; /* sizeof == 6, Explicit NUL only */
char str[7]= "Hello\0"; /* sizeof == 7, Explicit + Implicit NUL */
char str[8]= "Hello\0"; /* sizeof == 8, Explicit + two Implicit NUL */
You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :
The export runs in the background, a popup will appear when it's done.
In newer versions of DBeaver you can just :
The export runs in the background, a popup will appear when it's done.
Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.
The index is nothing but a data structure that stores the values for a specific column in a table. An index is created on a column of a table.
Example: We have a database table called User
with three columns – Name
, Age
and Address
. Assume that the User
table has thousands of rows.
Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. If we run the following query:
SELECT * FROM User
WHERE Name = 'John'
The database software would literally have to look at every single row in the User
table to see if the Name
for that row is ‘John’. This will take a long time.
This is where index
helps us: index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined.
How to create an index:
CREATE INDEX name_index
ON User (Name)
An index
consists of column values(Eg: John) from one table, and those values are stored in a data structure.
So now the database will use the index to find employees named John because the index will presumably be sorted alphabetically by the Users name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index!
There's another explanation for why .env
doesn't exist, and it happens when you move all the Laravel files.
Take this workflow: in your project directory you do laravel new whatever
, Laravel is installed in whatever
, you do mv * ..
to move all the files to your project folder, and you remove whatever
. The problem is, mv
doesn't move hidden files by default, so the .env
files are left behind, and are removed!
You want $.param()
: http://api.jquery.com/jQuery.param/
Specifically, you want this:
var data = { one: 'first', two: 'second' };
var result = $.param(data);
When given something like this:
{a: 1, b : 23, c : "te!@#st"}
$.param
will return this:
a=1&b=23&c=te!%40%23st
01. Open the page for which you want to get the information.
02. Clear the address bar [where you type the address of the sites]:
and type or copy/paste from below:
javascript:alert(document.lastModified)
03. Press Enter or Go button.
function getNiceFileSize($file, $digits = 2){
if (is_file($file)) {
$filePath = $file;
if (!realpath($filePath)) {
$filePath = $_SERVER["DOCUMENT_ROOT"] . $filePath;
}
$fileSize = filesize($filePath);
$sizes = array("TB", "GB", "MB", "KB", "B");
$total = count($sizes);
while ($total-- && $fileSize > 1024) {
$fileSize /= 1024;
}
return round($fileSize, $digits) . " " . $sizes[$total];
}
return false;
}
Using Collections#addAll()
String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>();
Collections.addAll(arrayList, words);
change parent="android:Theme.Holo.Dark"
to parent="android:Theme.Holo"
The holo dark theme is called Holo
Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E>
with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.
A little mathematical logic theory here:
"NOT a AND NOT b" is the same as "NOT (a OR b)", so:
"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".
So if you want exact opposite result, df1 and df2 should be as below:
df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
From SourceTree, click on Tools->Options. Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.
Then switch to the "Diff" tab. On the lower half, use the drop down to select the external program you want to use to do the diffs and merging. I've installed KDiff3 and like it well enough. When you're done, click OK.
Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.
I had the same issue, as I was using my company LAN. And I just ran cmd.exe npm
and I was able to execute my other commands without any error after that.
C:\Users\586656>cmd.exe npm
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
Just sharing this, as it may help other folks who try to do this in their office LAN. Thank you.
For full-screen frame redirects and similar things I have two methods. Both work fine on mobile and desktop.
Note this are complete cross-browser working, valid HTML files. Just change title
and src
for your needs.
1. this is my favorite:
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-1 </title>
<meta name=viewport content="width=device-width">
<style>
html, body, iframe { height:100%; width:100%; margin:0; border:0; display:block }
</style>
<iframe src=src1></iframe>
<!-- More verbose CSS for better understanding:
html { height:100% }
body { height:100%; margin:0 }
iframe { height:100%; width:100%; border:0; display:block }
-->
or 2. something like that, slightly shorter:
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-2 </title>
<meta name=viewport content="width=device-width">
<iframe src=src2 style="position:absolute; top:0; left:0; width:100%; height:100%; border:0">
</iframe>
Note:
The above examples avoid using height:100vh
because old browsers don't know it (maybe moot these days) and height:100vh
is not always equal to height:100%
on mobile browsers (probably not applicable here). Otherwise, vh
simplifies things a little bit, so
3. this is an example using vh (not my favorite, less compatible with little advantage)
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-3 </title>
<meta name=viewport content="width=device-width">
<style>
body { margin:0 }
iframe { display:block; width:100%; height:100vh; border:0 }
</style>
<iframe src=src3></iframe>
Here is my solution to a modal that can be rendered on any screen and initialized in App.tsx
ModalComponent.tsx
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet, Platform } from 'react-native';
import EventEmitter from 'events';
// I keep localization files for strings and device metrics like height and width which are used for styling
import strings from '../../config/strings';
import metrics from '../../config/metrics';
const emitter = new EventEmitter();
export const _modalEmitter = emitter
export class ModalView extends Component {
state: {
modalVisible: boolean,
text: string,
callbackSubmit: any,
callbackCancel: any,
animation: any
}
constructor(props) {
super(props)
this.state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {}),
animation: new Animated.Value(0)
}
}
componentDidMount() {
_modalEmitter.addListener(strings.modalOpen, (event) => {
var state = {
modalVisible: true,
text: event.text,
callbackSubmit: event.onSubmit,
callbackCancel: event.onClose,
animation: new Animated.Value(0)
}
this.setState(state)
})
_modalEmitter.addListener(strings.modalClose, (event) => {
var state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {}),
animation: new Animated.Value(0)
}
this.setState(state)
})
}
componentWillUnmount() {
var state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {})
}
this.setState(state)
}
closeModal = () => {
_modalEmitter.emit(strings.modalClose)
}
startAnimation=()=>{
Animated.timing(this.state.animation, {
toValue : 0.5,
duration : 500
}).start()
}
body = () => {
const animatedOpacity ={
opacity : this.state.animation
}
this.startAnimation()
return (
<View style={{ height: 0 }}>
<Modal
animationType="fade"
transparent={true}
visible={this.state.modalVisible}>
// render a transparent gray background over the whole screen and animate it to fade in, touchable opacity to close modal on click out
<Animated.View style={[styles.modalBackground, animatedOpacity]} >
<TouchableOpacity onPress={() => this.closeModal()} activeOpacity={1} style={[styles.modalBackground, {opacity: 1} ]} >
</TouchableOpacity>
</Animated.View>
// render an absolutely positioned modal component over that background
<View style={styles.modalContent}>
<View key="text_container">
<Text>{this.state.text}?</Text>
</View>
<View key="options_container">
// keep in mind the content styling is very minimal for this example, you can put in your own component here or style and make it behave as you wish
<TouchableOpacity
onPress={() => {
this.state.callbackSubmit();
}}>
<Text>Confirm</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.state.callbackCancel();
}}>
<Text>Cancel</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
}
render() {
return this.body()
}
}
// to center the modal on your screen
// top: metrics.DEVICE_HEIGHT/2 positions the top of the modal at the center of your screen
// however you wanna consider your modal's height and subtract half of that so that the
// center of the modal is centered not the top, additionally for 'ios' taking into consideration
// the 20px top bunny ears offset hence - (Platform.OS == 'ios'? 120 : 100)
// where 100 is half of the modal's height of 200
const styles = StyleSheet.create({
modalBackground: {
height: '100%',
width: '100%',
backgroundColor: 'gray',
zIndex: -1
},
modalContent: {
position: 'absolute',
alignSelf: 'center',
zIndex: 1,
top: metrics.DEVICE_HEIGHT/2 - (Platform.OS == 'ios'? 120 : 100),
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
height: 200,
width: '80%',
borderRadius: 27,
backgroundColor: 'white',
opacity: 1
},
})
App.tsx render and import
import { ModalView } from './{your_path}/ModalComponent';
render() {
return (
<React.Fragment>
<StatusBar barStyle={'dark-content'} />
<AppRouter />
<ModalView />
</React.Fragment>
)
}
and to use it from any component
SomeComponent.tsx
import { _modalEmitter } from './{your_path}/ModalComponent'
// Some functions within your component
showModal(modalText, callbackOnSubmit, callbackOnClose) {
_modalEmitter.emit(strings.modalOpen, { text: modalText, onSubmit: callbackOnSubmit.bind(this), onClose: callbackOnClose.bind(this) })
}
closeModal() {
_modalEmitter.emit(strings.modalClose)
}
Hope I was able to help some of you, I used a very similar structure for in-app notifications
Happy coding
Change all "es6" and "es7" to "es" in your polyfills.ts and polyfills.ts (Optional).
import 'core-js/es6/symbol';
import 'core-js/es/symbol';
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
@JsonProperty("name")
public String mName;
@JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
By loading the .js
file first and then calling the function via onclick, there's less coding and it's fairly obvious what's going on. We'll call the JS file zipcodehelp.js
.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Button to call JS function.</title>
</head>
<body>
<h1>Use Button to execute function in '.js' file.</h1>
<script type="text/javascript" src="zipcodehelp.js"></script>
<button onclick="ZipcodeHelp();">Get Zip Help!</button>
</body>
</html>
And the contents of zipcodehelp.js
is :
function ZipcodeHelp() {
alert("If Zipcode is missing in list at left, do: \n\n\
1. Enter any zipcode and click Create Client. \n\
2. Goto Zipcodes and create new zip code. \n\
3. Edit this new client from the client list.\n\
4. Select the new zipcode." );
}
Hope that helps! Cheers!
–Ken
Your regex should work 'as-is'. Assuming that it is doing what you want it to.
wordA(\s*)wordB(?! wordc)
This means match wordA
followed by 0 or more spaces followed by wordB
, but do not match if followed by wordc
. Note the single space between ?!
and wordc
which means that wordA wordB wordc
will not match, but wordA wordB wordc
will.
Here are some example matches and the associated replacement output:
Note that all matches are replaced no matter how many spaces. There are a couple of other points: -
(?! wordc)
is a negative lookahead, so you wont match lines wordA wordB wordc
which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?!
to match the whitespace. You may want to be more precise and use (?!\swordc)
. If you want to match against more than one space before wordc you can use (?!\s*wordc)
for 0 or more spaces or (?!\s*+wordc)
for 1 or more spaces depending on what your intention is.
Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.
*
will match 0 or more spaces so it will match wordAwordB. You may want to consider +
if you want at least one space.
(\s*)
- the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s
.
Update based on comment
Hello the problem is not the expression but the HTML out put that are not considered as whitespace. it's a Joomla website.
Preserving your original regex you can use:
wordA((?:\s| )*)wordB(?!(?:\s| )wordc)
The only difference is that not the regex matches whitespace OR
. I replaced wordc
with \swordc
since that is more explicit. Note as I have already pointed out that the negative lookahead ?!
will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.
Example matches:
use #undef UNICODE
at the top of your main file.
sharer.php
The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.
Use dialog/feeds instead of sharer.php
https://www.facebook.com/dialog/feed?
app_id=145634995501895
&display=popup&caption=An%20example%20caption
&link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
&redirect_uri=https://developers.facebook.com/tools/explorer
For Linux:
/opt/lampp/bin/mysql -u root -p
To use just 'mysql -u root -p' command then add '/opt/lampp/bin' to the PATH of the environment variables.
Would this help?
final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));
You should use &
/ |
operators and be careful about operator precedence (==
has lower precedence than bitwise AND
and OR
):
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))
df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()
## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## | 2| b|3.0| 2| b|0.0|
## +---+---+---+---+---+---+
Following @Aravind's answer with more details
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
myServiceMethodSettingCookie(request, response); //Do service call passing the response
return new ModelAndView("CustomerAddView");
}
// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
final String cookieName = "my_cool_cookie";
final String cookieValue = "my cool value here !"; // you could assign it some encoded value
final Boolean useSecureCookie = false;
final int expiryTime = 60 * 60 * 24; // 24h in seconds
final String cookiePath = "/";
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
cookie.setMaxAge(expiryTime); // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
response.addCookie(cookie);
}
Related docs:
http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html
[Updated Dec 2020]: Tested and Included 5.0
version of Bootstrap.
I know this question is old. And the question did not mentioned which version of Bootstrap he was using. So i'll assume the answer to this question is resolved.
If any of you (like me) stumbled upon this question and looking for answer using current bootstrap 5.0 (2020) and 4.5 (2019) framework, then here's the solution.
Use d-flex justify-content-center
on your column div. This will center everything inside that column.
<div class="row">
<div class="col-4 d-flex justify-content-center">
// Image
</div>
</div>
If you want to align the text inside the col just use text-center
<div class="row">
<div class="col-4 text-center">
// text only
</div>
</div>
If you have text and image inside the column, you need to use d-flex
justify-content-center
and text-center
.
<div class="row">
<div class="col-4 d-flex justify-content-center text-center">
// for image and text
</div>
</div>
gem cleanup
uses system commands. Installed gems are just directories in the filesystem. If you want to batch delete, use rm -R
.
gem environment
and note the value of GEM PATHS
cd <your-gem-paths>/gems
ls -1 |grep rjb- |xargs rm -R
If you don't have password you can use the command without
-u
Like this
C:\wamp>bin\mysql\mysql5.7.11\bin\mysql.exe -u {User Name} {Database Name} < C:\File.sql
Or on the SQL console
mysql -u {User Name} -p {Database Name} < C:/File.sql
The most common causes are:
1. An incorrectly configured GOROOT
OR
2. GOPATH is not set
Try this:
var src = DateTime.Now;
var hm = new DateTime(src.Year, src.Month, src.Day, src.Hour, src.Minute, 0);
I had this problem and even after I have used the command npm install nodemon --save
in my application, I still had problem with nodemon.
I just resolved after I installed nodemon globally, using the command:npm install nodemon -g
I have published a package on PyPI: ez.
Use pip install ez
to install it.
It has packed common commands in shell and nicely my lib uses basically the same syntax as shell. e.g., cp(source, destination) can handle both file and folder! (wrapper of shutil.copy shutil.copytree and it decides when to use which one). Even more nicely, it can support vectorization like R!
Another example: no os.walk, use fls(path, regex) to recursively find files and filter with regular expression and it returns a list of files with or without fullpath
Final example: you can combine them to write very simply scripts:
files = fls('.','py$'); cp(files, myDir)
Definitely check it out! It has cost me hundreds of hours to write/improve it!
In a production environment you want your app to be started again on a machine restart etc, creating a /etc/init.d/ script and linking to the appropriate runlevel to start and stop it is the correct approach. Spring Boot will not extend to covering this as it is a operating system specific setup and the are tonnes of other options, do you want it running in a chroot jail, does it need to stop / start before some other software etc.
I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.
Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.
When a thread is executing and you want to execute the main UI thread which is blocked by current thread, then use the below:
current thread:
Dispatcher.CurrentDispatcher.Invoke(MethodName,
new object[] { parameter1, parameter2 }); // if passing 2 parameters to method.
Main UI thread:
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background, new Action(() => MethodName(parameter)));
npm link webpack worked for me.
My webpack configuration: "webpack": "^4.41.2", "webpack-dev-server": "^3.9.0", "webpack-cli": "^3.3.10"
I think the documentation is reasonably helpful!
If you read it again, it says that adding open graph elements on your website will make your website act as a facebook page and you'll get the ability to publish updates to them etc.
So I think it's up to you - you can either just have a page with no OG elements, which is less work but also less 'rewarding' for you.
If you do use og, then set type to: blog
Finally: fb:admins
or fb:app_id
- A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.
So just put your own fbid in there. As a tip, you can easily get this by looking at the url of your profile photo on facebook.
See the Scripting Guy! Blog:
How Can I Tell Whether a Value Exists in the Registry?
They discuss doing the check on a remote computer and show that if you read a string value from the key, and if the value is Null (as opposed to Empty), the key does not exist.
With respect to using the RegRead method, if the term "key" refers to the path (or folder) where registry values are kept, and if the leaf items in that key are called "values", using WshShell.RegRead(strKey) to detect key existence (as opposed to value existance) consider the following (as observed on Windows XP):
If strKey name is not the name of an existing registry path, Err.Description reads "Invalid root in registry key"... with an Err.Number of 0x80070002.
If strKey names a registry path that exists but does not include a trailing "\" the RegRead method appears to interpret strKey as a path\value reference rather than as a simple path reference, and returns the same Err.Number but with an Err.Description of "Unable to open registry key". The term "key" in the error message appears to mean "value". This is the same result obtained when strKey references a path\value where the path exists, but the value does not exist.
In python 2.7 you can use NumPy's numpy.std()
gives the population standard deviation.
In Python 3.4 statistics.stdev()
returns the sample standard deviation. The pstdv()
function is the same as numpy.std()
.
It should be like import package_name.Class_Name
--> If you want to import a specific class
(or)
import package_name.*
--> To import all classes in a package
Since it was a successful comment, I am adding it as an answer:
with files:
find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
The file .pgpass in a user's home directory or the file referenced by PGPASSFILE can contain passwords to be used if the connection requires a password (and no password has been specified otherwise). On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).
This file should contain lines of the following format:
hostname:port:database:username:password
(You can add a reminder comment to the file by copying the line above and preceding it with #.) Each of the first four fields can be a literal value, or *, which matches anything. The password field from the first line that matches the current connection parameters will be used. (Therefore, put more-specific entries first when you are using wildcards.) If an entry needs to contain : or \, escape this character with . A host name of localhost matches both TCP (host name localhost) and Unix domain socket (pghost empty or the default socket directory) connections coming from the local machine. In a standby server, a database name of replication matches streaming replication connections made to the master server. The database field is of limited usefulness because users have the same password for all databases in the same cluster.
On Unix systems, the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored. On Microsoft Windows, it is assumed that the file is stored in a directory that is secure, so no special permissions check is made.
Instead of appending element you can just do.
document.getElementById("p").textContent += " this has just been added";
document.getElementById("p").textContent += " this has just been added";
_x000D_
<p id ="p">This is some text</p>
_x000D_
<div class="author_">Lord Byron</div>
.author_ { font-family: 'Playfair Display', serif; font-size: 1.25em; font-weight: 700;letter-spacing: 0.25em; font-style: italic;_x000D_
position:relative;_x000D_
margin-top: -0.5em;_x000D_
color: black;_x000D_
z-index:1;_x000D_
overflow:hidden;_x000D_
text-align:center;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
.author_:after{_x000D_
left:20px;_x000D_
margin:0 -100% 0 0;_x000D_
display: inline-block;_x000D_
height: 10px;_x000D_
content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20200%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M1145%2085c17%2C7%208%2C24%20-4%2C29%20-12%2C4%20-40%2C6%20-48%2C-8%20-9%2C-15%209%2C-34%2026%2C-42%2017%2C-7%2045%2C-6%2062%2C2%2017%2C9%2019%2C18%2020%2C27%201%2C9%200%2C29%20-27%2C52%20-28%2C23%20-52%2C34%20-102%2C33%20-49%2C0%20-130%2C-31%20-185%2C-50%20-56%2C-18%20-74%2C-21%20-96%2C-23%20-22%2C-2%20-29%2C-2%20-56%2C7%20-27%2C8%20-44%2C17%20-44%2C17%20-13%2C5%20-15%2C7%20-40%2C16%20-25%2C9%20-69%2C14%20-120%2C11%20-51%2C-3%20-126%2C-23%20-181%2C-32%20-54%2C-9%20-105%2C-20%20-148%2C-23%20-42%2C-3%20-71%2C1%20-104%2C5%20-34%2C5%20-65%2C15%20-98%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}_x000D_
.author_:before {_x000D_
right:20px;_x000D_
margin:0 0 0 -100%;_x000D_
display: inline-block;_x000D_
height: 10px;_x000D_
content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20130%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M55%2068c-17%2C6%20-8%2C23%204%2C28%2012%2C5%2040%2C7%2048%2C-8%209%2C-15%20-9%2C-34%20-26%2C-41%20-17%2C-8%20-45%2C-7%20-62%2C2%20-18%2C8%20-19%2C18%20-20%2C27%20-1%2C9%200%2C29%2027%2C52%2028%2C23%2052%2C33%20102%2C33%2049%2C-1%20130%2C-31%20185%2C-50%2056%2C-19%2074%2C-21%2096%2C-23%2022%2C-2%2029%2C-2%2056%2C6%2027%2C8%2043%2C17%2043%2C17%2014%2C6%2016%2C7%2041%2C16%2025%2C9%2069%2C15%20120%2C11%2051%2C-3%20126%2C-22%20181%2C-32%2054%2C-9%20105%2C-20%20148%2C-23%2042%2C-3%2071%2C1%20104%2C6%2034%2C4%2065%2C14%2098%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}
_x000D_
<div class="author_">Lord Byron</div>
_x000D_
Convenient tool for SVG encoding url-encoder
In Xamarin.Android
For Fragment:
this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });
For Activity:
RunOnUiThread(() => { yourtextbox.Text="Hello"; });
Happy coding :-)
This error comes when using the following command in Windows. You can simply run the following command by removing the dot '.'
and the slash '/'
.
Instead of writing:
D:\Gesture Recognition\Gesture Recognition\Debug>./"Gesture Recognition.exe"
Write:
D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"
I had everything set up, but still couldn't see proper error pages for status code 500 on our staging server, despite the fact everything worked fine on local development servers.
I found this blog post from Rick Strahl that helped me.
I needed to add Response.TrySkipIisCustomErrors = true;
to my custom error handling code.
You might be able to resize the image with canvas
and export it using dataURI. Not sure about compression, though.
Take a look at this: Resizing an image in an HTML5 canvas
Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:
"android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
This might be not so obvious, but sometime is required to test the executable to appropriately call it without an external shell process:
function tkl_is_file_os_exec()
{
[[ ! -x "$1" ]] && return 255
local exec_header_bytes
case "$OSTYPE" in
cygwin* | msys* | mingw*)
# CAUTION:
# The bash version 3.2+ might require a file path together with the extension,
# otherwise will throw the error: `bash: ...: No such file or directory`.
# So we make a guess to avoid the error.
#
{
read -r -n 4 exec_header_bytes 2> /dev/null < "$1" ||
{
[[ -x "${1%.exe}.exe" ]] && read -r -n 4 exec_header_bytes 2> /dev/null < "${1%.exe}.exe"
} ||
{
[[ -x "${1%.com}.com" ]] && read -r -n 4 exec_header_bytes 2> /dev/null < "${1%.com}.com"
}
} &&
if [[ "${exec_header_bytes:0:3}" == $'MZ\x90' ]]; then
# $'MZ\x90\00' for bash version 3.2.42+
# $'MZ\x90\03' for bash version 4.0+
[[ "${exec_header_bytes:3:1}" == $'\x00' || "${exec_header_bytes:3:1}" == $'\x03' ]] && return 0
fi
;;
*)
read -r -n 4 exec_header_bytes < "$1"
[[ "$exec_header_bytes" == $'\x7fELF' ]] && return 0
;;
esac
return 1
}
# executes script in the shell process in case of a shell script, otherwise executes as usual
function tkl_exec_inproc()
{
if tkl_is_file_os_exec "$1"; then
"$@"
else
. "$@"
fi
return $?
}
myscript.sh:
#!/bin/bash
echo 123
return 123
In Cygwin:
> tkl_exec_inproc /cygdrive/c/Windows/system32/cmd.exe /c 'echo 123'
123
> tkl_exec_inproc /cygdrive/c/Windows/system32/chcp.com 65001
Active code page: 65001
> tkl_exec_inproc ./myscript.sh
123
> echo $?
123
In Linux:
> tkl_exec_inproc /bin/bash -c 'echo 123'
123
> tkl_exec_inproc ./myscript.sh
123
> echo $?
123
Had this issue when provisioning a new site for VVV in vvv-config.yml with a faulty syntax, vagrant up
would throw the error. Deleting and reverting to old configuration, running vagrant provision
helped
it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);
DECLARE @STARTDATE datetime;
DECLARE @EntDt datetime;
set @STARTDATE = '01/01/2009';
set @EntDt = '12/31/2009';
declare @dcnt int;
;with DateList as
(
select @STARTDATE DateValue
union all
select DateValue + 1 from DateList
where DateValue + 1 < convert(VARCHAR(15),@EntDt,101)
)
select count(*) as DayCnt from (
select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )
)a
option (maxrecursion 365);
Or... You can also to try Your Own Task
JAVA CODE:
class CustomString extends Task{
private String type, string, before, after, returnValue;
public void execute() {
if (getType().equals("replace")) {
replace(getString(), getBefore(), getAfter());
}
}
private void replace(String str, String a, String b){
String results = str.replace(a, b);
Project project = getProject();
project.setProperty(getReturnValue(), results);
}
..all getter and setter..
ANT SCRIPT
...
<project name="ant-test" default="build">
<target name="build" depends="compile, run"/>
<target name="clean">
<delete dir="build" />
</target>
<target name="compile" depends="clean">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes" includeantruntime="true"/>
</target>
<target name="declare" depends="compile">
<taskdef name="string" classname="CustomString" classpath="build/classes" />
</target>
<!-- Replacing characters in Ant property -->
<target name="run" depends="declare">
<property name="propA" value="This is a value"/>
<echo message="propA=${propA}" />
<string type="replace" string="${propA}" before=" " after="_" returnvalue="propB"/>
<echo message="propB=${propB}" />
</target>
CONSOLE:
run:
[echo] propA=This is a value
[echo] propB=This_is_a_value
The "Leader key" is a way of extending the power of VIM's shortcuts by using sequences of keys to perform a command. The default leader key is backslash. Therefore, if you have a map of <Leader>Q, you can perform that action by typing \Q.
System.Diagnostics.Process.Start("shutdown", "/s /t 0")
Should work.
For restart, it's /r
This will restart the PC box directly and cleanly, with NO dialogs.
kill $(ps -aef | grep java | grep apache | awk '{print $2}')
System.IO.File.Create(@"C:\Temp.txt");
As others have pointed out, you should dispose of this object or wrap it in an empty using statement.
using (System.IO.File.Create(@"C:\Temp.txt"));
If you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [(
brackets which wrap the variable.
You have a JSON object that contains an Array. You need to access the array results
. Change your code to:
this.data = res.json().results
If you want to see what you haven't git add
ed yet:
git diff myfile.txt
or if you want to see already added changes
git diff --cached myfile.txt
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
int fib(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
in fibonacci sequence first 2 numbers always sequels to 1 then every time the value became 1 or 2 it must return 1
TortoiseGit can compare tags now.
Left log is on remote, right is at local.
Using the Compare tags feature of Sync dialog:
Also see TortoiseGit issue 2973
How about Freebase? I think they have an API available, too.
Yeah it suck to get stuck in Scale View.
Host+Home will popup the Virtual machine settings. (by default Host is Right Control)
From there you can change the view settings, as the Menu bar is hidden in Scale View.
Had the same issue, especially when you checked the box not to show the 'Switch to Scale view' dialog.
This you can do while the VM is running.
If you are using Sentry
check the logged in user with Sentry::getUser()->id
. The error you get is that the Auth::user()
returns NULL and it tries to get id from NULL hence the error trying to get a property from a non-object
.
the library already have Java/Kotlin support, see github.
To simplify I did a class to be used simply, I added it on Encryption library to use it you just do as follow:
Add the gradle library:
compile 'se.simbio.encryption:library:2.0.0'
and use it:
Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);
if you not want add the Encryption library you can just copy the following class to your project. If you are in an android project you need to import android Base64 in this class, if you are in a pure java project you need to add this class manually you can get it here
Encryption.java
package se.simbio.encryption;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* A class to make more easy and simple the encrypt routines, this is the core of Encryption library
*/
public class Encryption {
/**
* The Builder used to create the Encryption instance and that contains the information about
* encryption specifications, this instance need to be private and careful managed
*/
private final Builder mBuilder;
/**
* The private and unique constructor, you should use the Encryption.Builder to build your own
* instance or get the default proving just the sensible information about encryption
*/
private Encryption(Builder builder) {
mBuilder = builder;
}
/**
* @return an default encryption instance or {@code null} if occur some Exception, you can
* create yur own Encryption instance using the Encryption.Builder
*/
public static Encryption getDefault(String key, String salt, byte[] iv) {
try {
return Builder.getDefaultBuilder(key, salt, iv).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* Encrypt a String
*
* @param data the String to be encrypted
*
* @return the encrypted String or {@code null} if you send the data as {@code null}
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported or if
* the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* or if this has no installed provider that can
* provide the requested by the Builder secret key
* type or it is {@code null}, empty or in an invalid
* format
* @throws NoSuchPaddingException if no installed provider can provide the padding
* scheme in the Builder digest algorithm
* @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
* the cipher
* @throws InvalidKeyException if the specified key can not be used to initialize
* the cipher instance
* @throws InvalidKeySpecException if the specified key specification cannot be used
* to generate a secret key
* @throws BadPaddingException if the padding of the data does not match the
* padding scheme
* @throws IllegalBlockSizeException if the size of the resulting bytes is not a
* multiple of the cipher block size
* @throws NullPointerException if the Builder digest algorithm is {@code null} or
* if the specified Builder secret key type is
* {@code null}
* @throws IllegalStateException if the cipher instance is not initialized for
* encryption or decryption
*/
public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
if (data == null) return null;
SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
}
/**
* This is a sugar method that calls encrypt method and catch the exceptions returning
* {@code null} when it occurs and logging the error
*
* @param data the String to be encrypted
*
* @return the encrypted String or {@code null} if you send the data as {@code null}
*/
public String encryptOrNull(String data) {
try {
return encrypt(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* This is a sugar method that calls encrypt method in background, it is a good idea to use this
* one instead the default method because encryption can take several time and with this method
* the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
* one for success and other for the exception
*
* @param data the String to be encrypted
* @param callback the Callback to handle the results
*/
public void encryptAsync(final String data, final Callback callback) {
if (callback == null) return;
new Thread(new Runnable() {
@Override
public void run() {
try {
String encrypt = encrypt(data);
if (encrypt == null) {
callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
}
callback.onSuccess(encrypt);
} catch (Exception e) {
callback.onError(e);
}
}
}).start();
}
/**
* Decrypt a String
*
* @param data the String to be decrypted
*
* @return the decrypted String or {@code null} if you send the data as {@code null}
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported or if
* the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* or if this has no installed provider that can
* provide the requested by the Builder secret key
* type or it is {@code null}, empty or in an invalid
* format
* @throws NoSuchPaddingException if no installed provider can provide the padding
* scheme in the Builder digest algorithm
* @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
* the cipher
* @throws InvalidKeyException if the specified key can not be used to initialize
* the cipher instance
* @throws InvalidKeySpecException if the specified key specification cannot be used
* to generate a secret key
* @throws BadPaddingException if the padding of the data does not match the
* padding scheme
* @throws IllegalBlockSizeException if the size of the resulting bytes is not a
* multiple of the cipher block size
* @throws NullPointerException if the Builder digest algorithm is {@code null} or
* if the specified Builder secret key type is
* {@code null}
* @throws IllegalStateException if the cipher instance is not initialized for
* encryption or decryption
*/
public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
if (data == null) return null;
byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
return new String(dataBytesDecrypted);
}
/**
* This is a sugar method that calls decrypt method and catch the exceptions returning
* {@code null} when it occurs and logging the error
*
* @param data the String to be decrypted
*
* @return the decrypted String or {@code null} if you send the data as {@code null}
*/
public String decryptOrNull(String data) {
try {
return decrypt(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* This is a sugar method that calls decrypt method in background, it is a good idea to use this
* one instead the default method because decryption can take several time and with this method
* the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
* one for success and other for the exception
*
* @param data the String to be decrypted
* @param callback the Callback to handle the results
*/
public void decryptAsync(final String data, final Callback callback) {
if (callback == null) return;
new Thread(new Runnable() {
@Override
public void run() {
try {
String decrypt = decrypt(data);
if (decrypt == null) {
callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
}
callback.onSuccess(decrypt);
} catch (Exception e) {
callback.onError(e);
}
}
}).start();
}
/**
* creates a 128bit salted aes key
*
* @param key encoded input key
*
* @return aes 128 bit salted key
*
* @throws NoSuchAlgorithmException if no installed provider that can provide the requested
* by the Builder secret key type
* @throws UnsupportedEncodingException if the Builder charset name is not supported
* @throws InvalidKeySpecException if the specified key specification cannot be used to
* generate a secret key
* @throws NullPointerException if the specified Builder secret key type is {@code null}
*/
private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
}
/**
* takes in a simple string and performs an sha1 hash
* that is 128 bits long...we then base64 encode it
* and return the char array
*
* @param key simple inputted string
*
* @return sha1 base64 encoded representation
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* @throws NullPointerException if the Builder digest algorithm is {@code null}
*/
private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
}
/**
* When you encrypt or decrypt in callback mode you get noticed of result using this interface
*/
public interface Callback {
/**
* Called when encrypt or decrypt job ends and the process was a success
*
* @param result the encrypted or decrypted String
*/
void onSuccess(String result);
/**
* Called when encrypt or decrypt job ends and has occurred an error in the process
*
* @param exception the Exception related to the error
*/
void onError(Exception exception);
}
/**
* This class is used to create an Encryption instance, you should provide ALL data or start
* with the Default Builder provided by the getDefaultBuilder method
*/
public static class Builder {
private byte[] mIv;
private int mKeyLength;
private int mBase64Mode;
private int mIterationCount;
private String mSalt;
private String mKey;
private String mAlgorithm;
private String mKeyAlgorithm;
private String mCharsetName;
private String mSecretKeyType;
private String mDigestAlgorithm;
private String mSecureRandomAlgorithm;
private SecureRandom mSecureRandom;
private IvParameterSpec mIvParameterSpec;
/**
* @return an default builder with the follow defaults:
* the default char set is UTF-8
* the default base mode is Base64
* the Secret Key Type is the PBKDF2WithHmacSHA1
* the default salt is "some_salt" but can be anything
* the default length of key is 128
* the default iteration count is 65536
* the default algorithm is AES in CBC mode and PKCS 5 Padding
* the default secure random algorithm is SHA1PRNG
* the default message digest algorithm SHA1
*/
public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
return new Builder()
.setIv(iv)
.setKey(key)
.setSalt(salt)
.setKeyLength(128)
.setKeyAlgorithm("AES")
.setCharsetName("UTF8")
.setIterationCount(1)
.setDigestAlgorithm("SHA1")
.setBase64Mode(Base64.DEFAULT)
.setAlgorithm("AES/CBC/PKCS5Padding")
.setSecureRandomAlgorithm("SHA1PRNG")
.setSecretKeyType("PBKDF2WithHmacSHA1");
}
/**
* Build the Encryption with the provided information
*
* @return a new Encryption instance with provided information
*
* @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
* @throws NullPointerException if the SecureRandomAlgorithm is {@code null} or if the
* IV byte array is null
*/
public Encryption build() throws NoSuchAlgorithmException {
setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
setIvParameterSpec(new IvParameterSpec(getIv()));
return new Encryption(this);
}
/**
* @return the charset name
*/
private String getCharsetName() {
return mCharsetName;
}
/**
* @param charsetName the new charset name
*
* @return this instance to follow the Builder patter
*/
public Builder setCharsetName(String charsetName) {
mCharsetName = charsetName;
return this;
}
/**
* @return the algorithm
*/
private String getAlgorithm() {
return mAlgorithm;
}
/**
* @param algorithm the algorithm to be used
*
* @return this instance to follow the Builder patter
*/
public Builder setAlgorithm(String algorithm) {
mAlgorithm = algorithm;
return this;
}
/**
* @return the key algorithm
*/
private String getKeyAlgorithm() {
return mKeyAlgorithm;
}
/**
* @param keyAlgorithm the keyAlgorithm to be used in keys
*
* @return this instance to follow the Builder patter
*/
public Builder setKeyAlgorithm(String keyAlgorithm) {
mKeyAlgorithm = keyAlgorithm;
return this;
}
/**
* @return the Base 64 mode
*/
private int getBase64Mode() {
return mBase64Mode;
}
/**
* @param base64Mode set the base 64 mode
*
* @return this instance to follow the Builder patter
*/
public Builder setBase64Mode(int base64Mode) {
mBase64Mode = base64Mode;
return this;
}
/**
* @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
* are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
*/
private String getSecretKeyType() {
return mSecretKeyType;
}
/**
* @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
* changed, if you are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
*
* @return this instance to follow the Builder patter
*/
public Builder setSecretKeyType(String secretKeyType) {
mSecretKeyType = secretKeyType;
return this;
}
/**
* @return the value used for salting
*/
private String getSalt() {
return mSalt;
}
/**
* @param salt the value used for salting
*
* @return this instance to follow the Builder patter
*/
public Builder setSalt(String salt) {
mSalt = salt;
return this;
}
/**
* @return the key
*/
private String getKey() {
return mKey;
}
/**
* @param key the key.
*
* @return this instance to follow the Builder patter
*/
public Builder setKey(String key) {
mKey = key;
return this;
}
/**
* @return the length of key
*/
private int getKeyLength() {
return mKeyLength;
}
/**
* @param keyLength the length of key
*
* @return this instance to follow the Builder patter
*/
public Builder setKeyLength(int keyLength) {
mKeyLength = keyLength;
return this;
}
/**
* @return the number of times the password is hashed
*/
private int getIterationCount() {
return mIterationCount;
}
/**
* @param iterationCount the number of times the password is hashed
*
* @return this instance to follow the Builder patter
*/
public Builder setIterationCount(int iterationCount) {
mIterationCount = iterationCount;
return this;
}
/**
* @return the algorithm used to generate the secure random
*/
private String getSecureRandomAlgorithm() {
return mSecureRandomAlgorithm;
}
/**
* @param secureRandomAlgorithm the algorithm to generate the secure random
*
* @return this instance to follow the Builder patter
*/
public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
mSecureRandomAlgorithm = secureRandomAlgorithm;
return this;
}
/**
* @return the IvParameterSpec bytes array
*/
private byte[] getIv() {
return mIv;
}
/**
* @param iv the byte array to create a new IvParameterSpec
*
* @return this instance to follow the Builder patter
*/
public Builder setIv(byte[] iv) {
mIv = iv;
return this;
}
/**
* @return the SecureRandom
*/
private SecureRandom getSecureRandom() {
return mSecureRandom;
}
/**
* @param secureRandom the Secure Random
*
* @return this instance to follow the Builder patter
*/
public Builder setSecureRandom(SecureRandom secureRandom) {
mSecureRandom = secureRandom;
return this;
}
/**
* @return the IvParameterSpec
*/
private IvParameterSpec getIvParameterSpec() {
return mIvParameterSpec;
}
/**
* @param ivParameterSpec the IvParameterSpec
*
* @return this instance to follow the Builder patter
*/
public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
mIvParameterSpec = ivParameterSpec;
return this;
}
/**
* @return the message digest algorithm
*/
private String getDigestAlgorithm() {
return mDigestAlgorithm;
}
/**
* @param digestAlgorithm the algorithm to be used to get message digest instance
*
* @return this instance to follow the Builder patter
*/
public Builder setDigestAlgorithm(String digestAlgorithm) {
mDigestAlgorithm = digestAlgorithm;
return this;
}
}
}
This works:
any(c.isalpha() for c in 'string')
I the following code I had to replace add a GET-parameter to all references to JS-files EXCEPT one.
<link rel="stylesheet" type="text/css" href="/login/css/ABC.css" />
<script type="text/javascript" language="javascript" src="/localization/DEF.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/GHI.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/md5.js"></script>
sendRequest('/application/srvc/EXCEPTION.js', handleChallengeResponse, null);
sendRequest('/application/srvc/EXCEPTION.js",handleChallengeResponse, null);
This is the Matcher used:
(?<!EXCEPTION)(\.js)
What that does is look for all occurences of ".js" and if they are preceeded by the "EXCEPTION" string, discard that result from the result array. That's called negative lookbehind. Since I spent a day on finding out how to do this I thought I should share.
How about this?
set search=%1
set replace=%2
set textfile=Input.txt
python -c "with open('%textfile%', 'rw') as f: f.write(f.read().replace('%search%', '%replace%'))"
Muhahaha
To convert a string to lower case in Python, use something like this.
list.append(sentence.lower())
I found this in the first result after searching for "python upper to lower case".
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
Look at the link, there is an answer for your question.
Sending Email in Android using JavaMail API without using the default/built-in app
I have modified @rahul kumars answer, so that it uses Observables instead:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";
@Injectable()
export class ScriptLoaderService {
private scripts: ScriptModel[] = [];
public load(script: ScriptModel): Observable<ScriptModel> {
return new Observable<ScriptModel>((observer: Observer<ScriptModel>) => {
var existingScript = this.scripts.find(s => s.name == script.name);
// Complete if already loaded
if (existingScript && existingScript.loaded) {
observer.next(existingScript);
observer.complete();
}
else {
// Add the script
this.scripts = [...this.scripts, script];
// Load the script
let scriptElement = document.createElement("script");
scriptElement.type = "text/javascript";
scriptElement.src = script.src;
scriptElement.onload = () => {
script.loaded = true;
observer.next(script);
observer.complete();
};
scriptElement.onerror = (error: any) => {
observer.error("Couldn't load script " + script.src);
};
document.getElementsByTagName('body')[0].appendChild(scriptElement);
}
});
}
}
export interface ScriptModel {
name: string,
src: string,
loaded: boolean
}
You have two options to fix the issue:
1- Manually make sure the two versions match.
2- Use the IDE's help as follows:
- Right mouse click on the error in the 'Problems' view
- Select the 'Quick Fix' menu item from the pop-up menu
- Select the right compiler level in the provided dialog and click 'Finish'.
Taken from Eclipse: Java compiler level and project facet mismatch
Also gives location of where you can access the Java compiler and facet version.
For those who are using Javascript on Windows (e.g. WScript / CScript / MSHTA). One can use ActiveX
. Specifically, the Scriptlet.Typelib
object:
WScript.Echo((new ActiveXObject("Scriptlet.TypeLib")).Guid)
Note that this answer only works on the technologies I listed, it will not work any browser, not even Microsoft Edge! So, your mileage will vary with this answer.
Except for adding the following to sqlnet.ora
SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8
I also added the following to both the Client and Server, which resolved my issue
SQLNET.AUTHENTICATION_SERVICES = (NONE)
Also see post ORA-28040: No matching authentication protocol
To your first question, you can't really do any query through YQL to get data for all companies. It's more oriented towards obtaining data for a smaller query. (I.e., it's not going to give you a full data dump of the whole Yahoo! Finance database.)
To your second question, here's how you can get started exploring the Yahoo! Finance tables in YQL:
finance
in the search fieldThen you can try some example queries like the following:
select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")
Update 2016-04-04: Here's a current screenshot showing the location of the Show Community Tables checkbox which must be clicked to see these finance tables:
You can mount a folder as a drive. From the command line, if you have a path C:\path\to\long\folder
you can map it to drive letter X:
using:
subst x: \path\to\long\folder
I can't answer all questions, but I will do my best.
As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.
Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.
WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).
In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.
Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.
About the protocol, as Wikipedia shows, it looks like this:
Client sends:
GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com
Server replies:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.
As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support
Upgrade: websocket
Connection: Upgrade
will reply with an error or with a page content.
In kotlin this can be implemented easily as follows:
/**
* If android version is Kitkat or above, users can change default sms application.
* This method will get default sms app and start default sms app.
*/
private fun openSMS() {
val message = "message here"
val phone = "255754......." //255 Tanzania code.
val uri = Uri.parse("smsto:+$phone")
val intent = Intent(Intent.ACTION_SENDTO, uri)
with(intent) {
putExtra("address", "+$phone")
putExtra("sms_body", message)
}
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT -> {
//Getting the default sms app.
val defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(context)
// Can be null in case that there is no default, then the user would be able to choose
// any app that support this intent.
if (defaultSmsPackageName != null) intent.setPackage(defaultSmsPackageName)
startActivity(intent)
}
else -> startActivity(intent)
}
}
This is modified answer of @mustafasevgi
You can use the extract_html
field of the summary REST endpoint for this: e.g. https://en.wikipedia.org/api/rest_v1/page/summary/Cat.
Note: This aims to simply the content a bit by removing most of the pronunciations, mainly in parentheses in some cases.
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
You may try
Android Studio top menu > File > Invalidate caches / restart...
Click on invalidate cache / restart button to restart your project
Resolve R.xxxx.xxx again if some of the fragment class R class didn't resolve properly
then rebuild your project
Hope it helps
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
(.*?)
does not work for me. I am trying to match comments surrounded by /* */
, which may contain multiple lines.
Try this:
([a]|[^a])
This regex matches a
or anything else expect a
. Absolutely, it means matching everything.
BTW, in my situation, /\*([a]|[^a])*/
matches C style comments.
Thank @mpen for a more concise way.
[\s\S]
I have used this URL to obtain multiple currency market quotes.
http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X
"USD",1.0000
"CAD",1.2458
"EUR",0.8396
They can be parsed in PHP like this:
$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');
$quote = array_map( 'str_getcsv', file($url) );
foreach ($quote as $key => $symb) {
$symbol = $quote[$key][0];
$value = $quote[$key][1];
}
try setting the display to block in your javascript instead of a blank value.
You need to make a system env variable with the name: ANDROID_SDK_ROOT and it's value should be C:\Users\your_user_name\AppData\Sdk\tools\bin worked for me
changing the width of the image will automatically change the height...
how many pictures do you want to have this functionality? If it's a lot and they all have DIFFERENT Heights you should probably just let the height change as well.
Lets say you have 5 images that have height 400px , in your html give those five tags the class of fixed
.fixed { width: 100%; height: 500px !important }
This should let the width change but keep the height the same.
All of these other answers include runtime overhead... like using ArrayList.toString().replaceAll(...) which are very wasteful.
I will give you the optimal algorithm with zero overhead; it doesn't look as pretty as the other options, but internally, this is what they are all doing (after piles of other hidden checks, multiple array allocation and other crud).
Since you already know you are dealing with strings, you can save a bunch of array allocations by performing everything manually. This isn't pretty, but if you trace the actual method calls made by the other implementations, you'll see it has the least runtime overhead possible.
public static String join(String separator, String ... values) {
if (values.length==0)return "";//need at least one element
//all string operations use a new array, so minimize all calls possible
char[] sep = separator.toCharArray();
// determine final size and normalize nulls
int totalSize = (values.length - 1) * sep.length;// separator size
for (int i = 0; i < values.length; i++) {
if (values[i] == null)
values[i] = "";
else
totalSize += values[i].length();
}
//exact size; no bounds checks or resizes
char[] joined = new char[totalSize];
int pos = 0;
//note, we are iterating all the elements except the last one
for (int i = 0, end = values.length-1; i < end; i++) {
System.arraycopy(values[i].toCharArray(), 0,
joined, pos, values[i].length());
pos += values[i].length();
System.arraycopy(sep, 0, joined, pos, sep.length);
pos += sep.length;
}
//now, add the last element;
//this is why we checked values.length == 0 off the hop
System.arraycopy(values[values.length-1].toCharArray(), 0,
joined, pos, values[values.length-1].length());
return new String(joined);
}
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()
Google has documented this https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css
The CSS format specifier allows you to customize the display in the console. Start the string with the specifier and give the style you wish to apply as the second parameter.
One example:
console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
width: '100%'
and alignSelf: 'stretch'
didn't work for me. Dimensions
didn't suite my task cause I needed to operate on a deeply nested view. Here's what worked for me, if I rewrite your code. I just added some more View
s and used flex
properties to achieve the needed layout:
{/* a column */}
<View style={styles.container}>
{/* some rows here */}
<Text style={styles.welcome}>
Welcome to React Natives
</Text>
{/* this row should take all available width */}
<View style={{ flexDirection: 'row' }}>
{/* flex 1 makes the view take all available width */}
<View style={{ flex: 1 }}>
<Text style={styles.line1}>
line1
</Text>
</View>
{/* I also had a button here, to the right of the text */}
</View>
{/* the rest of the rows */}
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
import csv
dic = {firstcol,secondcol} #dictionary
csv = open('result.csv', "w")
for key in dic.keys():
row ="\n"+ str(key) + "," + str(dic[key])
csv.write(row)
Consider this as the current update (Windows 10 (Version 1803) and Visual Studio 2017): I was unable to view the stack trace window and did find an option/menu item to view it. On investigating further, it seems this feature is not available on Windows 10. For further information please refer:
Copied from the above link: "This feature is not available in Windows 10, version 1507 and later versions of the WDK."
Top answer will not work in Jquery 1.9+ because of attr() method. Use prop() instead:
$(function() {
$('#select_all').change(function(){
var checkboxes = $(this).closest('form').find(':checkbox');
if($(this).prop('checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
});
});
You can change
Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
to
Range("B3:B65536").Copy
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues
BTW, if you have xls file (excel 2003), you would get an error if your lastrow
would be greater 3.
Try to use this code instead:
Sub Get_Data()
Dim lastrowDB As Long, lastrow As Long
Dim arr1, arr2, i As Integer
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")
For i = LBound(arr1) To UBound(arr1)
With Sheets("Sheet1")
lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
End With
Next
Application.CutCopyMode = False
End Sub
Note, above code determines last non empty row on DB
sheet in column A
(variable lastrowDB
). If you need to find lastrow for each destination column in DB
sheet, use next modification:
For i = LBound(arr1) To UBound(arr1)
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
End With
' NEXT CODE
Next
You could also use next approach instead Copy/PasteSpecial
. Replace
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
with
Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value
here's easy-to-use, thread-safe c++ functions to convert uint32_t native-endian to string, and string to native-endian uint32_t:
#include <arpa/inet.h> // inet_ntop & inet_pton
#include <string.h> // strerror_r
#include <arpa/inet.h> // ntohl & htonl
using namespace std; // im lazy
string ipv4_int_to_string(uint32_t in, bool *const success = nullptr)
{
string ret(INET_ADDRSTRLEN, '\0');
in = htonl(in);
const bool _success = (NULL != inet_ntop(AF_INET, &in, &ret[0], ret.size()));
if (success)
{
*success = _success;
}
if (_success)
{
ret.pop_back(); // remove null-terminator required by inet_ntop
}
else if (!success)
{
char buf[200] = {0};
strerror_r(errno, buf, sizeof(buf));
throw std::runtime_error(string("error converting ipv4 int to string ") + to_string(errno) + string(": ") + string(buf));
}
return ret;
}
// return is native-endian
// when an error occurs: if success ptr is given, it's set to false, otherwise a std::runtime_error is thrown.
uint32_t ipv4_string_to_int(const string &in, bool *const success = nullptr)
{
uint32_t ret;
const bool _success = (1 == inet_pton(AF_INET, in.c_str(), &ret));
ret = ntohl(ret);
if (success)
{
*success = _success;
}
else if (!_success)
{
char buf[200] = {0};
strerror_r(errno, buf, sizeof(buf));
throw std::runtime_error(string("error converting ipv4 string to int ") + to_string(errno) + string(": ") + string(buf));
}
return ret;
}
fair warning, as of writing, they're un-tested. but these functions are exactly what i was looking for when i came to this thread.
@ Tim, to add to your answer (its a little awkward fitting this into a comment).
As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.
I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.
function rgbToHex(r, g, b) {
if(r < 0 || r > 255) alert("r is out of bounds; "+r);
if(g < 0 || g > 255) alert("g is out of bounds; "+g);
if(b < 0 || b > 255) alert("b is out of bounds; "+b);
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}
Based on ejunker's answer, this is the solution working for me, not on a single server but on a cloud enviroment
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{ENV:HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.
public static class ReflectiveEnumerator
{
static ReflectiveEnumerator() { }
public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
{
List<T> objects = new List<T>();
foreach (Type type in
Assembly.GetAssembly(typeof(T)).GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
{
objects.Add((T)Activator.CreateInstance(type, constructorArgs));
}
objects.Sort();
return objects;
}
}
A few notes:
Assembly.GetAssembly(typeof(T))
because your base class might be in a different assembly. type.IsClass
and !type.IsAbstract
because it'll throw an exception if you try to instantiate an interface or abstract class.IComparable
so that they can be sorted.Is this what you want:
>>> d={'a':1,'b':2,'c':3}
>>> default_val=99
>>> for k in d:
... d[k]=default_val
...
>>> d
{'a': 99, 'b': 99, 'c': 99}
>>>
>>> d={'a':1,'b':2,'c':3}
>>> from collections import defaultdict
>>> d=defaultdict(lambda:99,d)
>>> d
defaultdict(<function <lambda> at 0x03D21630>, {'a': 1, 'c': 3, 'b': 2})
>>> d[3]
99
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
See What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
To summarize: the way a directive accesses its parent ($parent
) scope depends on the type of scope the directive creates:
default (scope: false
) - the directive does not create a new scope, so there is no inheritance here. The directive's scope is the same scope as the parent/container. In the link function, use the first parameter (typically scope
).
scope: true
- the directive creates a new child scope that prototypically inherits from the parent scope. Properties that are defined on the parent scope are available to the directive scope
(because of prototypal inheritance). Just beware of writing to a primitive scope property -- that will create a new property on the directive scope (that hides/shadows the parent scope property of the same name).
scope: { ... }
- the directive creates a new isolate/isolated scope. It does not prototypically inherit the parent scope. You can still access the parent scope using $parent
, but this is not normally recommended. Instead, you should specify which parent scope properties (and/or function) the directive needs via additional attributes on the same element where the directive is used, using the =
, @
, and &
notation.
transclude: true
- the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. If the directive also creates an isolate scope, the transcluded and the isolate scopes are siblings. The $parent
property of each scope references the same parent scope.
Angular v1.3 update: If the directive also creates an isolate scope, the transcluded scope is now a child of the isolate scope. The transcluded and isolate scopes are no longer siblings. The $parent
property of the transcluded scope now references the isolate scope.
The above link has examples and pictures of all 4 types.
You cannot access the scope in the directive's compile function (as mentioned here: https://github.com/angular/angular.js/wiki/Dev-Guide:-Understanding-Directives). You can access the directive's scope in the link function.
Watching:
For 1. and 2. above: normally you specify which parent property the directive needs via an attribute, then $watch it:
<div my-dir attr1="prop1"></div>
scope.$watch(attrs.attr1, function() { ... });
If you are watching an object property, you'll need to use $parse:
<div my-dir attr2="obj.prop2"></div>
var model = $parse(attrs.attr2);
scope.$watch(model, function() { ... });
For 3. above (isolate scope), watch the name you give the directive property using the @
or =
notation:
<div my-dir attr3="{{prop3}}" attr4="obj.prop4"></div>
scope: {
localName3: '@attr3',
attr4: '=' // here, using the same name as the attribute
},
link: function(scope, element, attrs) {
scope.$watch('localName3', function() { ... });
scope.$watch('attr4', function() { ... });
Try this:
data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)
m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()
m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()
In addition to what Salaryman said, take a look at the classes in PEAR, there are HTTP request classes there that you can use even if you do not have the cURL extension installed in your PHP distribution.
Simply delete the maintenance.flag
file in root folder and then delete the files of cache folder and session folder inside var/
folder.
Absolutely.
If the constructor doesn't receive valid input, or can't construct the object in a valid manner, it has no other option but to throw an exception and alert its caller.
add jquery ui plugin in your page.
function JsonDateFormate(dateFormate, jsonDateTime) {
return $.datepicker.formatDate(dateFormate, eval('new ' + jsonDateTime.slice(1, -1)));
};
I normally add a hidden reset button to the form. when needed just: $('#reset').click();
My solution would be to use filter after the map.
This should support every JS data type.
example:
const notUndefined = anyValue => typeof anyValue !== 'undefined'
const noUndefinedList = someList
.map(// mapping condition)
.filter(notUndefined); // by doing this,
//you can ensure what's returned is not undefined
Great technical answers in the post! I have nothing technically to add to that.
One of the main reasons why new features appear in languages and software in general is marketing or company politics! :-) This must not be under estimated!
I think this applies to certain extend to delegates and events too! i find them useful and add value to the C# language, but on the other hand the Java language decided not to use them! they decided that whatever you are solving with delegates you can already solve with existing features of the language i.e. interfaces e.g.
Now around 2001 Microsoft released the .NET framework and the C# language as a competitor solution to Java, so it was good to have NEW FEATURES that Java doesn't have.
In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.
But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:
{ Id: 1,
name:'john',
phones:[{title:'home',number:111111,...},
{title:'office',number:22222,...}]
}
sends
{ Id: 1,
name:'john',
phones:[object object]
phones:[object object]
}
you can't animate every property,
here's a reference to which are the animatable properties
visibility is animatable while display isn't...
in your case you could also animate opacity
or height
depending of the kind of effect you want to render_
Ok, I think I have a pretty cool solution.
Let's say you have file a
and file b
.
You have a def
or a class
in file b
that you want to use in module a
, but you have something else, either a def
, class
, or variable from file a
that you need in your definition or class in file b
.
What you can do is, at the bottom of file a
, after calling the function or class in file a
that is needed in file b
, but before calling the function or class from file b
that you need for file a
, say import b
Then, and here is the key part, in all of the definitions or classes in file b
that need the def
or class
from file a
(let's call it CLASS
), you say from a import CLASS
This works because you can import file b
without Python executing any of the import statements in file b
, and thus you elude any circular imports.
For example:
class A(object):
def __init__(self, name):
self.name = name
CLASS = A("me")
import b
go = B(6)
go.dostuff
class B(object):
def __init__(self, number):
self.number = number
def dostuff(self):
from a import CLASS
print "Hello " + CLASS.name + ", " + str(number) + " is an interesting number."
Voila.
This error popped up several times on several different projects.
What I finally figured out is that when I would build, there was already a copy of the system.web.mvc binary assembly in my bin folder.
To fix this, right-click on the assembly in the list of references and select "properties". Check to see if this is the latest version by looking at the "Version" property. If it is, switch "Copy Local" to true.
This will make sure that the version referenced in your project is the version that will end up in your binaries folder.
If you still get the error, try running nuGet to get the latest version, then try the aforementioned again.
Good luck - this error is a pain!
You need to seperate the functionality into a class or classes and launch that via one of two stubs. The console stub or service stub.
As its plain to see, when running windows, the myriad services that make up the infrastructure do not (and can't directly) present console windows to the user. The service needs to communicate with the user in a non graphical way: via the SCM; in the event log, to some log file etc. The service will also need to communicate with windows via the SCM, otherwise it will get shutdown.
It would obviously be acceptable to have some console app that can communicate with the service but the service needs to run independently without a requirement for GUI interaction.
The Console stub can very useful for debugging service behaviour but should not be used in a "productionized" environment which, after all, is the purpose of creating a service.
I haven't read it fully but this article seems to pint in the right direction.
<form action="" method="post" name="register_form" id="register_form" enctype="multipart/form-data">
<div class="text-input">
<label>Gender: </label>
<input class="form-control" type="radio" name="gender" id="male" value="male" />
<label for="male">Male</label>
<input class="form-control" type="radio" name="gender" id="female" value="female" />
<label for="female">Female</label>
</div>
<div class="text-input" align="center">
<input type="submit" name="register" value="Submit" onclick="return radioValidation();" />
</div>
</form>
<script type="text/javascript">
function radioValidation(){
var gender = document.getElementsByName('gender');
var genValue = false;
for(var i=0; i<gender.length;i++){
if(gender[i].checked == true){
genValue = true;
}
}
if(!genValue){
alert("Please Choose the gender");
return false;
}
}
</script>
Source: http://chandreshrana.blogspot.in/2016/11/radio-button-validation-in-javascript.html
If you are using new jqueryui above code will not help you use this
$('.datepicker').datepicker({dateFormat:"yy-mm-dd"});
Include in the GROUP BY
clause all SELECT
expressions that are not group function arguments.
Updated to use git push --mirror origin
instead of git push -f origin
as suggested in the comments.
This worked for me flawlessly.
git clone --mirror <URL to my OLD repo location>
cd <New directory where your OLD repo was cloned>
git remote set-url origin <URL to my NEW repo location>
git push --mirror origin
I have to mention though that this creates a mirror of your current repo and then pushes that to the new location. Therefore, this can take some time for large repos or slow connections.
I coded a form to a multidimensional JavaScript object myself to use it in production. The result is https://github.com/serbanghita/formToObject.js.
It depends on how and when you want to redirect the user to another page.
If you want to instantly redirect a user to another page without him seeing anything of a site in between, you should use the PHP header
redirect method.
If you have a Javascript and some action of the user has to result in him entering another page, that is when you should use window.location
.
The meta
tag refresh is often used on download sites whenever you see these "Your download should start automatically" messages. You can let the user load a page, wait for a certain amount of time, then redirect him (e.g. to a to-be-downloaded file) without Javascript.
I always use this command to remove those untracked files. One-line, Unix-style, clean output:
git ls-files --ignored --exclude-standard | sed 's/.*/"&"/' | xargs git rm -r --cached
It lists all your ignored files, replace every output line with a quoted line instead to handle paths with spaces inside, and pass everything to git rm -r --cached
to remove the paths/files/dirs from the index.
$("#formid").ajaxForm({ success: function(){ //to do after submit } });