- Where does
user.id
go afterpassport.serializeUser
has been called?
The user id (you provide as the second argument of the done
function) is saved in the session and is later used to retrieve the whole object via the deserializeUser
function.
serializeUser
determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}
. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}
- We are calling
passport.deserializeUser
right after it where does it fit in the workflow?
The first argument of deserializeUser
corresponds to the key of the user object that was given to the done
function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc).
In deserializeUser
that key is matched with the in memory array / database or any data resource.
The fetched object is attached to the request object as req.user
Visual Flow
passport.serializeUser(function(user, done) {
done(null, user.id);
}); ¦
¦
¦
+--------------------? saved to session
¦ req.session.passport.user = {id: '..'}
¦
?
passport.deserializeUser(function(id, done) {
+---------------+
¦
?
User.findById(id, function(err, user) {
done(err, user);
}); +--------------? user object attaches to the request as req.user
});
Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _claim;
public ClaimAuthorizeAttribute(string Claim)
{
_claim = Claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
{
return;
}
context.Result = new ForbidResult();
}
}
If it is a 2 byte string you can do something like in this concrete example where I switch on ISO639-2 language codes.
LANIDX_TYPE LanCodeToIdx(const char* Lan)
{
if(Lan)
switch(Lan[0]) {
case 'A': switch(Lan[1]) {
case 'N': return LANIDX_AN;
case 'R': return LANIDX_AR;
}
break;
case 'B': switch(Lan[1]) {
case 'E': return LANIDX_BE;
case 'G': return LANIDX_BG;
case 'N': return LANIDX_BN;
case 'R': return LANIDX_BR;
case 'S': return LANIDX_BS;
}
break;
case 'C': switch(Lan[1]) {
case 'A': return LANIDX_CA;
case 'C': return LANIDX_CO;
case 'S': return LANIDX_CS;
case 'Y': return LANIDX_CY;
}
break;
case 'D': switch(Lan[1]) {
case 'A': return LANIDX_DA;
case 'E': return LANIDX_DE;
}
break;
case 'E': switch(Lan[1]) {
case 'L': return LANIDX_EL;
case 'N': return LANIDX_EN;
case 'O': return LANIDX_EO;
case 'S': return LANIDX_ES;
case 'T': return LANIDX_ET;
case 'U': return LANIDX_EU;
}
break;
case 'F': switch(Lan[1]) {
case 'A': return LANIDX_FA;
case 'I': return LANIDX_FI;
case 'O': return LANIDX_FO;
case 'R': return LANIDX_FR;
case 'Y': return LANIDX_FY;
}
break;
case 'G': switch(Lan[1]) {
case 'A': return LANIDX_GA;
case 'D': return LANIDX_GD;
case 'L': return LANIDX_GL;
case 'V': return LANIDX_GV;
}
break;
case 'H': switch(Lan[1]) {
case 'E': return LANIDX_HE;
case 'I': return LANIDX_HI;
case 'R': return LANIDX_HR;
case 'U': return LANIDX_HU;
}
break;
case 'I': switch(Lan[1]) {
case 'S': return LANIDX_IS;
case 'T': return LANIDX_IT;
}
break;
case 'J': switch(Lan[1]) {
case 'A': return LANIDX_JA;
}
break;
case 'K': switch(Lan[1]) {
case 'O': return LANIDX_KO;
}
break;
case 'L': switch(Lan[1]) {
case 'A': return LANIDX_LA;
case 'B': return LANIDX_LB;
case 'I': return LANIDX_LI;
case 'T': return LANIDX_LT;
case 'V': return LANIDX_LV;
}
break;
case 'M': switch(Lan[1]) {
case 'K': return LANIDX_MK;
case 'T': return LANIDX_MT;
}
break;
case 'N': switch(Lan[1]) {
case 'L': return LANIDX_NL;
case 'O': return LANIDX_NO;
}
break;
case 'O': switch(Lan[1]) {
case 'C': return LANIDX_OC;
}
break;
case 'P': switch(Lan[1]) {
case 'L': return LANIDX_PL;
case 'T': return LANIDX_PT;
}
break;
case 'R': switch(Lan[1]) {
case 'M': return LANIDX_RM;
case 'O': return LANIDX_RO;
case 'U': return LANIDX_RU;
}
break;
case 'S': switch(Lan[1]) {
case 'C': return LANIDX_SC;
case 'K': return LANIDX_SK;
case 'L': return LANIDX_SL;
case 'Q': return LANIDX_SQ;
case 'R': return LANIDX_SR;
case 'V': return LANIDX_SV;
case 'W': return LANIDX_SW;
}
break;
case 'T': switch(Lan[1]) {
case 'R': return LANIDX_TR;
}
break;
case 'U': switch(Lan[1]) {
case 'K': return LANIDX_UK;
case 'N': return LANIDX_UN;
}
break;
case 'W': switch(Lan[1]) {
case 'A': return LANIDX_WA;
}
break;
case 'Z': switch(Lan[1]) {
case 'H': return LANIDX_ZH;
}
break;
}
return LANIDX_UNDEFINED;
}
LANIDX_* being constant integers used to index in arrays.
If you wish to list all tables, you must use:
\dt *.*
to indicate that you want all tables in all schemas. This will include tables in pg_catalog
, the system tables, and those in information_schema
. There's no built-in way to say "all tables in all user-defined schemas"; you can, however, set your search_path
to a list of all schemas of interest before running \dt
.
You may want to do this programmatically, in which case psql
backslash-commands won't do the job. This is where the INFORMATION_SCHEMA
comes to the rescue. To list tables:
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
BTW, if you ever want to see what psql
is doing in response to a backslash command, run psql
with the -E
flag. eg:
$ psql -E regress
regress=# \list
********* QUERY **********
SELECT d.datname as "Name",
pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
d.datcollate as "Collate",
d.datctype as "Ctype",
pg_catalog.array_to_string(d.datacl, E'\n') AS "Access privileges"
FROM pg_catalog.pg_database d
ORDER BY 1;
**************************
so you can see that psql
is searching pg_catalog.pg_database
when it gets a list of databases. Similarly, for tables within a given database:
SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','')
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;
It's preferable to use the SQL-standard, portable INFORMATION_SCHEMA
instead of the Pg system catalogs where possible, but sometimes you need Pg-specific information. In those cases it's fine to query the system catalogs directly, and psql -E
can be a helpful guide for how to do so.
This is my answer which solved the same problem. Fragment2.java is the fragment class which holds the layout of fragment2.xml.
public void onClick(View v) {
Fragment fragment2 = new Fragement2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Check your folder name. If your folder name having spaces, these kind of issues will generate. Rename without spaces. hope it will work.
Selenium has pretty good documentation. Here is a link to the specific part of the API you are looking for.
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();
An alternative approach may be to embed images in the email using the cid
method. (Basically including the image as an attachment, and then embedding it). In my experience, this approach seems to be well supported these days.
Source: https://www.campaignmonitor.com/blog/how-to/2008/08/embedding-images-revisited/
In lieu of a python goto equivalent I use the break statement in the following fashion for quick tests of my code. This assumes you have structured code base. The test variable is initialized at the start of your function and I just move the "If test: break" block to the end of the nested if-then block or loop I want to test, modifying the return variable at the end of the code to reflect the block or loop variable I'm testing.
def x:
test = True
If y:
# some code
If test:
break
return something
To set it for the current session, do:
SET time_zone = timezonename;
I presume you are talking about filling zeros of some existing mat? How about this? :)
mat *= 0;
You can try dirTimesJS.bat and fileTimesJS.bat
example:
C:\>dirTimesJS.bat %windir%
directory timestamps for C:\Windows :
Modified : 2020-11-22 22:12:55
Modified - milliseconds passed : 1604607175000
Modified day of the week : 4
Created : 2019-12-11 11:03:44
Created - milliseconds passed : 1575709424000
Created day of the week : 6
Accessed : 2020-11-16 16:39:22
Accessed - milliseconds passed : 1605019162000
Accessed day of the week : 2
C:\>fileTimesJS.bat %windir%\notepad.exe
file timestamps for C:\Windows\notepad.exe :
Modified : 2020-09-08 08:33:31
Modified - milliseconds passed : 1599629611000
Modified day of the week : 3
Created : 2020-09-08 08:33:31
Created - milliseconds passed : 1599629611000
Created day of the week : 3
Accessed : 2020-11-23 23:59:22
Accessed - milliseconds passed : 1604613562000
Accessed day of the week : 4
You need to store the psftp script (lines from open
to bye
) into a separate file and pass that to psftp
using -b
switch:
cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b
EDIT: For username+password: As you cannot use psftp
commands in a batch file, for the same reason, you cannot specify the username and the password as psftp
commands. These are inputs to the open
command. While you can specify the username with the open
command (open <user>@<IP>
), you cannot specify the password this way. This can be done on a psftp
command line only. Then it's probably cleaner to do all on the command-line:
cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>
And remove the open
, <user>
and <PW>
lines from your script.txt
.
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw
What you are doing atm is that you run psftp
without any parameter or commands. Once you exit it (like by typing bye
), your batch file continues trying to run open
command (and others), what Windows shell obviously does not understand.
If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:
(
echo cd ...
echo lcd ...
echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>
Just place jquery url on the top of your jquery code
like this--
<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#post').click(function() {
alert("test");
});
});
</script>
One issue with Bryan Rieger's useful answer is that on high-density displays, Apple devices report screen.width in dips, while Android devices report it in physical pixels. (See http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html .) I suggest using if (window.matchMedia('(max-device-width: 960px)').matches) {}
on browsers supporting matchMedia.
If you will still use JCrop, you will need only this php functions to crop the file:
$img_src = imagecreatefromjpeg($src);
$img_dest = imagecreatetruecolor($new_w,$new_h);
imagecopyresampled($img_dest,$img_src,0,0,$x,$y,$new_w,$new_h,$w,$h);
imagejpeg($img_dest,$dest);
client side:
jQuery(function($){
$('#target').Jcrop({
onChange: showCoords,
onSelect: showCoords,
onRelease: clearCoords
});
});
var x,y,w,h; //these variables are necessary to crop
function showCoords(c)
{
x = c.x;
y = c.y;
w = c.w;
h = c.h;
};
function clearCoords()
{
x=y=w=h=0;
}
If you are using bash with the extglob option enabled, you can remove just the trailing whitespace via:
shopt -s extglob
COMMAND=$'\nRE BOOT\r \n'
echo "|${COMMAND%%*([$'\t\r\n '])}|"
This outputs:
|
RE BOOT|
Or replace %% with ## to replace just the leading whitespace.
Change the default shell in vs code terminal to git bash.
now your project is open with bash console and right path, put "source venv\Scripts\activate" in Windows
While updating SDK tools, a dilog box presented with Constraint layout version that is going to get installed. Note that and update your dependency based on that. In my case it was installing beta3.
I changed my dependency like below. After that it worked.
compile 'com.android.support.constraint:constraint-layout:1.0.0-beta3'
Be aware that some browser extensions can add code to the pages. In my case I had an "Emmet in all textareas" plugin that messed up with my requireJs. Make sure that no extra code is beign added to your document by inspecting it in the browser.
The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.
Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.
It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.
I organize packages by feature, not by patterns or implementation roles. I think packages like:
beans
factories
collections
are wrong.
I prefer, for example:
orders
store
reports
so I can hide implementation details through package visibility. Factory of orders should be in the orders
package so details about how to create an order are hidden.
Don't declare the variable in the userform. Declare it as Public
in the module.
Public pass As String
In the Userform
Private Sub CommandButton1_Click()
pass = UserForm1.TextBox1
Unload UserForm1
End Sub
In the Module
Public pass As String
Public Sub Login()
'
'~~> Rest of the code
'
UserForm1.Show
driver.findElementByName("PASSWORD").SendKeys pass
'
'~~> Rest of the code
'
End Sub
You might want to also add an additional check just before calling the driver.find...
line?
If Len(Trim(pass)) <> 0 Then
This will ensure that a blank string is not passed.
You have to do write
in the same loop as read
.
If you want to pass the variable to your proxy backend, you have to set it with the proxy module.
location / {
proxy_pass http://example.com;
proxy_set_header Host example.com;
proxy_set_header HTTP_Country-Code $geoip_country_code;
proxy_pass_request_headers on;
}
And now it's passed to the proxy backend.
I do this for my .NET applications.
In my shared _Layout.cshtml
Page, I add this.
@{
var isMobileDevice = HttpContext.Current.Request.Browser.IsMobileDevice;
}
<html lang="en" class="@((isMobileDevice)?"ismobiledevice":"")">
Then to check on any page in your site (jQuery):
<script>
var isMobile = $('html').hasClass('ismobiledevice');
</script>
I think it would be simplest to create a new array, adding the unique values only as determined by indexOf.
This seems to me to be the most straightforward solution, though I don't know if it is the most efficient. Collation is not preserved.
var a = [34, 35, 45, 48, 49],
b = [48, 55];
var c = union(a, b);
function union(a, b) { // will work for n >= 2 inputs
var newArray = [];
//cycle through input arrays
for (var i = 0, l = arguments.length; i < l; i++) {
//cycle through each input arrays elements
var array = arguments[i];
for (var ii = 0, ll = array.length; ii < ll; ii++) {
var val = array[ii];
//only add elements to the new array if they are unique
if (newArray.indexOf(val) < 0) newArray.push(val);
}
}
return newArray;
}
it's the best solution of https or http use this :
<?php
$protocol = '//';
$site_url = $protocol.$_SERVER["HTTP_HOST"];
?>
But can't display https or http, so it only use to link your site content like image, etc.
if want to redirect your site in https, add this code in .htaccess file :
<IfModule mod_rewrite.c>
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^(.*)$ https://www.your-domain.com$1 [L]
</IfModule>
Change www.your-domain.com with your dowmain name.
You also need to increase maxBufferSize. Also note that you might need to increase the readerQuotas.
Like JaredPar said you can refer to Josh Smith's article towards Automation. However if you look through comments to his article you will find more elegant way of raising events against WPF controls
someButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
I personally prefer the one above instead of automation peers.
This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:
df.groupby(['group']).agg(['min','max','count','nunique'])
Hope you find it useful
Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.
Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.
This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.
For me both answers worked.
<Context docBase="/tmp/wars/hpong" path="" reloadable="true" />
<Service name="Catalina2"> <Connector port="8070" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8743" /> <Engine name="Catalina2" defaultHost="localhost"> <Host name="localhost" unpackWARs="true" autoDeploy="true"> <Context path="" docBase="/tmp/wars/hpong" reloadable="true"> <WatchedResource>WEB-INF/web.xml</WatchedResource> </Context> </Host> </Engine> </Service>
Note: when you declare docBase under context then ignore appBase at Host.
ROOT.war
and place it under webapps. So now unmatched url requests from other wars(contextpaths) will land into this war. This is better way to handle ROOT ("/**") context path. The second option is (double) loading the wars from Webapps folder as well. Also it only needs uncompressed war folder which is a headache.
(Alt + Shift + X) , then M
to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations
If the project is created using Xcode 6, then use the below mentioned code to detect the devices..
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] nativeBounds].size.width,(int)[[UIScreen mainScreen] nativeBounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
if([[UIScreen mainScreen] nativeBounds].size.height == 960 || [[UIScreen mainScreen] nativeBounds].size.height == 480){
printf("Device Type : iPhone 4,4s ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1136){
printf("Device Type : iPhone 5,5S/iPod 5 ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1334){
printf("Device Type : iPhone 6 ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 2208){
printf("Device Type : iPhone 6+ ");
}
}
}else{
printf("Device Type : iPad");
}
If the project was created in Xcode 5 and opened in Xcode 6, then use the below mentioned code to detect the devices.(This code works if no launching images for iPhone 6,6+ are assigned)
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] nativeBounds].size.width,(int)[[UIScreen mainScreen] nativeBounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
if([[UIScreen mainScreen] nativeBounds].size.height == 960 || [[UIScreen mainScreen] nativeBounds].size.height == 480){
printf("Device Type : iPhone 4,4s");
appType=1;
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1136 || [[UIScreen mainScreen] nativeBounds].size.height == 1704){
printf("Device Type : iPhone 5,5S,6,6S/iPod 5 ");
appType=3;
}
}
}else{
printf("Device Type : iPad");
appType=2;
}
If you are still using Xcode 5 all together then use the following code to detect the devices (iPhone 6 and 6+ will not be detected)
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] bounds].size.width,(int)[[UIScreen mainScreen] bounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
CGSize result = [[UIScreen mainScreen] bounds].size;
CGFloat scale = [UIScreen mainScreen].scale;
result = CGSizeMake(result.width * scale, result.height * scale);
if(result.height == 960 || result.height == 480){
printf("Device Type : iPhone 4,4S ");
}else if(result.height == 1136){
printf("Device Type : iPhone 5s/iPod 5");
}
}
}else{
printf("Device Type : iPad");
}
The practical reason for this is often that the python or django shells have opened a request to the DB and it wasn't closed properly; killing your terminal access often frees it up. I had this error on running command line tests today.
Edit: I get periodic upvotes on this. If you'd like to kill access without rebooting the terminal, then from commandline you can do:
from django import db
db.connections.close_all()
You have not defined a method around your code.
import java.io.*;
public class details
{
public static void main( String[] args )
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
In this case, I have assumed that you want your code to be executed in the main
method of the class. It is, of course, possible that this code goes in any other method.
CSS3 Simple Way
height: calc(100% - 10px); // 10px is height of your first div...
all major browsers these days support it, so go ahead if you don't have requirement to support vintage browsers.
The following code should do the trick:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="638dp" >
<TextView
android:id="@+id/textView1"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="64dp"
android:text="Email" />
<TextView
android:id="@+id/textView2"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="41dp"
android:text="Password" />
<TextView
android:id="@+id/textView3"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="47dp"
android:text="Confirm Password" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/textView4"
android:inputType="textEmailAddress" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentRight="true"
android:inputType="textPassword" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentRight="true"
android:inputType="textPassword" />
<TextView
android:id="@+id/textView4"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView3"
android:layout_marginTop="42dp"
android:text="Date of Birth" />
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView4" />
<TextView
android:id="@+id/textView5"
style="@style/normalcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/datePicker1"
android:layout_marginTop="60dp"
android:layout_toLeftOf="@+id/datePicker1"
android:text="Gender" />
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView5"
android:layout_alignBottom="@+id/textView5"
android:layout_alignLeft="@+id/editText3"
android:layout_marginLeft="24dp"
android:text="Male" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioButton1"
android:layout_below="@+id/radioButton1"
android:layout_marginTop="14dp"
android:text="Female" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="23dp"
android:layout_toLeftOf="@+id/radioButton2"
android:background="@drawable/rectbutton"
android:text="Sign Up" />
There is a nice generic way using the .data('events') collection:
function getEventsList($obj) {
var ev = new Array(),
events = $obj.data('events'),
i;
for(i in events) { ev.push(i); }
return ev.join(' ');
}
$obj.on(getEventsList($obj), function(e) {
console.log(e);
});
This logs every event that has been already bound to the element by jQuery the moment this specific event gets fired. This code was pretty damn helpful for me many times.
Btw: If you want to see every possible event being fired on an object use firebug: just right click on the DOM element in html tab and check "Log Events". Every event then gets logged to the console (this is sometimes a bit annoying because it logs every mouse movement...).
The general rule is to pick CHAR if all rows will have close to the same length. Pick VARCHAR (or NVARCHAR) when the length varies significantly. CHAR may also be a bit faster because all the rows are of the same length.
It varies by DB implementation, but generally, VARCHAR (or NVARCHAR) uses one or two more bytes of storage (for length or termination) in addition to the actual data. So (assuming you are using a one-byte character set) storing the word "FooBar"
The bottom line is CHAR can be faster and more space-efficient for data of relatively the same length (within two characters length difference).
Note: Microsoft SQL has 2 bytes of overhead for a VARCHAR. This may vary from DB to DB, but generally, there is at least 1 byte of overhead needed to indicate length or EOL on a VARCHAR.
As was pointed out by Gaven in the comments: Things change when it comes to multi-byte characters sets, and is a is case where VARCHAR becomes a much better choice.
A note about the declared length of the VARCHAR: Because it stores the length of the actual content, then you don't waste unused length. So storing 6 characters in VARCHAR(6), VARCHAR(100), or VARCHAR(MAX) uses the same amount of storage. Read more about the differences when using VARCHAR(MAX). You declare a maximum size in VARCHAR to limit how much is stored.
In the comments AlwaysLearning pointed out that the Microsoft Transact-SQL docs seem to say the opposite. I would suggest that is an error or at least the docs are unclear.
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
This problem occurs when a same library is added into your project multiple times. If you haven't added the library multiple times intentionaly, check out the dependency/private libraries of the libraries you have added in your project, most probably they have already included a library which is causing this conflict.
It is worth mentioning that sometimes NUnit Test Adapter files get corrupted in user folder C:\Users[User]\AppData\Local\Temp\VisualStudioTestExplorerExtensions\NUnit3TestAdapter.3.8.0/build/net35/NUnit3.TestAdapter.dll on Windows 10 and that causes Test Explorer to stop working as it should.
You will need to define the repository outside of buildscript
. The buildscript
configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.
Essentially you want to add code to the Calculate
event of the relevant Worksheet.
In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.
Alternatively, copy the code below into the editor of the sheet you want to use:
Private Sub Worksheet_Calculate()
If Sheets("MySheet").Range("A1").Value > 0.5 Then
MsgBox "Over 50%!", vbOKOnly
End If
End Sub
This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.
just don't validate:
flyway.setValidateOnMigrate(false);
So you want to remove dangling images? Am I correct?
systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer
systemctl start docker-image-cleanup.timer
https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units
I've solved my problem by this way: Edit the php.ini file:
The above is my solution,Hope it will work for u.
Cast the operands to floats:
float ans = (float)a / (float)b;
Make the source sheet visible before copying. Then copy the sheet so that the copy also stays visible. The copy will then be the active sheet. If you want, hide the source sheet again.
If you are not bound to use Hashmap, I would advise to use pair< T,T >. The individual elements can be accessed by first and second calls.
Have a look at this http://www.cplusplus.com/reference/utility/pair/
I used it here : http://codeforces.com/contest/507/submission/9531943
Kramdown supports it. It's compatible with standard Markdown syntax, but has many extensions, too. You would use it like this:
[link](url){:target="_blank"}
Finally I got it:
as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
Let me check:
as3:~/ngokevin-site# python
Python 2.7.6 (default, Dec 6 2013, 14:49:02)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.getdefaultencoding()
'utf8'
>>>
The above shows the default encoding of python is utf8
. Then the error is no more.
The above solution for the JsonCreationConverter<T>
is all over the internet, but has a flaw that manifests itself in rare occasions. The new JsonReader created in the ReadJson method does not inherit any of the original reader's configuration values (Culture, DateParseHandling, DateTimeZoneHandling, FloatParseHandling, etc...). These values should be copied over before using the new JsonReader in serializer.Populate().
This is the best I could come up with to fix some of the problems with the above implementation, but I still think there are some things being overlooked:
Update I updated this to have a more explicit method that makes a copy of an existing reader. This just encapsulates the process of copying over individual JsonReader settings. Ideally this function would be maintained in the Newtonsoft library itself, but for now, you can use the following:
/// <summary>Creates a new reader for the specified jObject by copying the settings
/// from an existing reader.</summary>
/// <param name="reader">The reader whose settings should be copied.</param>
/// <param name="jToken">The jToken to create a new reader for.</param>
/// <returns>The new disposable reader.</returns>
public static JsonReader CopyReaderForObject(JsonReader reader, JToken jToken)
{
JsonReader jTokenReader = jToken.CreateReader();
jTokenReader.Culture = reader.Culture;
jTokenReader.DateFormatString = reader.DateFormatString;
jTokenReader.DateParseHandling = reader.DateParseHandling;
jTokenReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jTokenReader.FloatParseHandling = reader.FloatParseHandling;
jTokenReader.MaxDepth = reader.MaxDepth;
jTokenReader.SupportMultipleContent = reader.SupportMultipleContent;
return jTokenReader;
}
This should be used as follows:
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
using (JsonReader jObjectReader = CopyReaderForObject(reader, jObject))
{
serializer.Populate(jObjectReader, target);
}
return target;
}
Older solution follows:
/// <summary>Base Generic JSON Converter that can help quickly define converters for specific types by automatically
/// generating the CanConvert, ReadJson, and WriteJson methods, requiring the implementer only to define a strongly typed Create method.</summary>
public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>Create an instance of objectType, based properties in the JSON object</summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">contents of JSON object that will be deserialized</param>
protected abstract T Create(Type objectType, JObject jObject);
/// <summary>Determines if this converted is designed to deserialization to objects of the specified type.</summary>
/// <param name="objectType">The target type for deserialization.</param>
/// <returns>True if the type is supported.</returns>
public override bool CanConvert(Type objectType)
{
// FrameWork 4.5
// return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
// Otherwise
return typeof(T).IsAssignableFrom(objectType);
}
/// <summary>Parses the json to the specified type.</summary>
/// <param name="reader">Newtonsoft.Json.JsonReader</param>
/// <param name="objectType">Target type.</param>
/// <param name="existingValue">Ignored</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
/// <returns>Deserialized Object</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
//Create a new reader for this jObject, and set all properties to match the original reader.
JsonReader jObjectReader = jObject.CreateReader();
jObjectReader.Culture = reader.Culture;
jObjectReader.DateParseHandling = reader.DateParseHandling;
jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jObjectReader.FloatParseHandling = reader.FloatParseHandling;
// Populate the object properties
serializer.Populate(jObjectReader, target);
return target;
}
/// <summary>Serializes to the specified type</summary>
/// <param name="writer">Newtonsoft.Json.JsonWriter</param>
/// <param name="value">Object to serialize.</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
})
->select('required column names')
->where('kg_shops.active', 1)
->get();
A bat file has no structure...it is how you would type it on the command line. So just open your favourite editor..copy the line of code you want to run..and save the file as whatever.bat or whatever.cmd
Taken from here:
You can use Notepad++ to accomplish this in three ways. Just so you know, Notepad++ is a more advanced version of Notepad, which supports syntax highlighting of different code files "out of the box" - PHP included!
Download & install it, fire it up, and load up your PHP file. You should automatically see it beautifully coloured (if not, because the file extension is something other than .php, go to Language -> PHP or Language -> P -> PHP).
If you need to change any of the colours, you can easily do so - just go to Settings -> Styler Configurator. From that menu, you can change the various highlighting and font options, to suit your needs - although the default usually suffices for most.
Then, go to Plugins -> NppExport. From there, you have three options you can consider:
Export to RTF Export to HTML Copy all formats to clipboard Start with the last one - "Copy all formats to clipboard" - which will copy the entire file with the highlighted syntax to the clipboard. Once you click it, then open Microsoft Word, and just hit paste! You should see the beautifully syntax-highlighted code. If something goes wrong, then you can try one of the other options (export to RTF/HTML), although I've never had a problem with the clipboard method.
In class do like this
@RequestMapping(value = "/saveData", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(
HttpServletResponse response,
Bean beanName
) throws MyException {
return new ResponseEntity<Boolean>(uiRequestProcessor.saveData(a), HttpStatus.OK);
}
In page do like this:
<form enctype="multipart/form-data" action="<%=request.getContextPath()%>/saveData" method="post" name="saveForm" id="saveForm">
<input type="text" value="${beanName.userName }" id="username" name="userName" />
</from>
Never use escape()
. It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.
If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
However whilst this is enough to put your user_id
in places like the input value
, it's not enough for id
because IDs can only use a limited selection of characters. (And %
isn't among them, so escape()
or even encodeURIComponent()
is no good.)
You could invent your own encoding scheme to put any characters in an ID, for example:
function encodeID(s) {
if (s==='') return '_';
return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
return '_'+match[0].charCodeAt(0).toString(16)+'_';
});
}
But you've still got a problem if the same user_id
occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById
, or worrying about how arbitrary strings are inserted into IDs.
eg.:
function addChut(user_id) {
var log= document.createElement('div');
log.className= 'log';
var textarea= document.createElement('textarea');
var input= document.createElement('input');
input.value= user_id;
input.readonly= True;
var button= document.createElement('input');
button.type= 'button';
button.value= 'Message';
var chut= document.createElement('div');
chut.className= 'chut';
chut.appendChild(log);
chut.appendChild(textarea);
chut.appendChild(input);
chut.appendChild(button);
document.getElementById('chuts').appendChild(chut);
button.onclick= function() {
alert('Send '+textarea.value+' to '+user_id);
};
return chut;
}
You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.
ETA:
I'm using jQuery at the moment as a framework
OK, then consider the jQuery 1.4 creation shortcuts, eg.:
var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});
...
The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.
You can keep a lookup of user_id
to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id
are restricted.
var chut_lookup= {};
...
function getChut(user_id) {
var key= '_map_'+user_id;
if (key in chut_lookup)
return chut_lookup[key];
return chut_lookup[key]= addChut(user_id);
}
(The _map_
prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object
member names, confuse it.)
curl -s -v -o/dev/null -H "Testheader: test" http://www.example.com
You could also use -I
option if you want to send a HEAD request and not a GET request.
For Linux user
$ alias ng="/home/jones/node_modules/@angular/cli/bin/ng"
then check angular/cli version
ng --version
Your problems have nothing to do with POST/GET but only with how you specify parameters in RouteAttribute
. To ensure this, I added support for both verbs in my samples.
Let's go back to two very simple working examples.
[Route("api/deliveryitems/{anyString}")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsOne(string anyString)
{
return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);
}
And
[Route("api/deliveryitems")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsTwo(string anyString = "default")
{
return Request.CreateResponse<string>(HttpStatusCode.OK, anyString);
}
The first sample says that the "anyString
" is a path segment parameter (part of the URL).
First sample example URL is:
xxx/api/deliveryItems/dkjd;dslkf;dfk;kkklm;oeop
"dkjd;dslkf;dfk;kkklm;oeop"
The second sample says that the "anyString
" is a query string parameter (optional here since a default value has been provided, but you can make it non-optional by simply removing the default value).
Second sample examples URL are:
xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
"dkjd;dslkf;dfk;kkklm;oeop"
xxx/api/deliveryItems
"default"
Of course, you can make it even more complex, like with this third sample:
[Route("api/deliveryitems")]
[HttpGet, HttpPost]
public HttpResponseMessage GetDeliveryItemsThree(string anyString, string anotherString = "anotherDefault")
{
return Request.CreateResponse<string>(HttpStatusCode.OK, anyString + "||" + anotherString);
}
Third sample examples URL are:
xxx/api/deliveryItems?anyString=dkjd;dslkf;dfk;kkklm;oeop
"dkjd;dslkf;dfk;kkklm;oeop||anotherDefault"
xxx/api/deliveryItems
anyString
is mandatory)xxx/api/deliveryItems?anotherString=bluberb&anyString=dkjd;dslkf;dfk;kkklm;oeop
"dkjd;dslkf;dfk;kkklm;oeop||bluberb"
When should you use path segment or query parameters? Some advice has already been given here: REST API Best practices: Where to put parameters?
Make sure that "Named Pipes" are enabled from "SQL Server Configuration Manager". This worked for me.
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
Right Click on the server tab, go for NEW-> Server. then choose recent version of tomcat server. Click on next, and then give path for your tomcat server.(You can download tomcat server from this link https://tomcat.apache.org/download-80.cgi#8.5.32). Click on finish.
You can start your server now..!!
If sudo apt-get install -f <package-name>
doesn't work, try aptitude:
sudo apt-get install aptitude
sudo aptitude install <package-name>
Aptitude will try to resolve the problem.
As an example, in my case, I still receive some error when try to install libcurl4-openssl-dev
:
sudo apt-get install -f libcurl4-openssl-dev
So i try aptitude, it turns out I have to downgrade some packages.
The following actions will resolve these dependencies: Keep the following packages at their current version: 1) libyaml-dev [Not Installed] Accept this solution? [Y/n/q/? (n) The following actions will resolve these dependencies: Downgrade the following packages: 1) libyaml-0-2 [0.1.4-3ubuntu3.1 (now) -> 0.1.4-3ubuntu3 (trusty)] Accept this solution? [Y/n/q/?] (Y)
See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS
filter when you do.
Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.
If you want to consider a regular expression based way of doing it
if(text.split("\\s").length > 1){
//text contains whitespace
}
If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).
Eclipse Classic is basically the full featured Eclipse without the Java EE part.
A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.
So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.
And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client.
Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.
So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.
But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified.
Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.
Now let's do some practices with nodejs:
Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.
config.env:
JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90
now install JWT using command
npm i jsonwebtoken
Example after user signup passing him JWT token so he can stay logged in and get access of resources.
exports.signup = catchAsync(async (req, res, next) => {
const newUser = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm,
});
const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN,
});
res.status(201).json({
status: 'success',
token,
data: {
newUser,
},
});
});
In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.
public void setHeight(DataGridView src)
{
src.Height= src.ColumnHeadersVisible ? src.ColumnHeadersHeight : 0 + src.Rows.OfType<DataGridViewRow>().Where(row => row.Visible).Sum(row => row.Height);
}
I have an answer:
<a href="#">
<div class="widget">
<div class="title" style="text-decoration: none;">Underlined. Why?</div>
</div>
</a>?
It works.
"Buffers" represent how much portion of RAM is dedicated to cache disk blocks. "Cached" is similar like "Buffers", only this time it caches pages from file reading.
quote from:
What you need is xml comments - basically, they follow this syntax (as vaguely described by Solmead):
C#
///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
return "blah";
}
VB
'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
Return "blah"
End Function
My case: Seeing the same INFO message.
Centos 6.2 x86_64 Tomcat 6.0.24
This fixed the problem for me:
yum install tomcat-native
boom!
It has a -force
parameter.????
Just got it. As regan pointed out, I had to add the user to the sudoers group. But the main reason was I'd forgotten to update the repositories cache, so apt-get couldn't find the sudo package. It's working now. Here's the completed code:
FROM ubuntu:12.04
RUN apt-get update && \
apt-get -y install sudo
RUN useradd -m docker && echo "docker:docker" | chpasswd && adduser docker sudo
USER docker
CMD /bin/bash
For some reason, I have to use
element.find('.fc-event-inner').empty();
to make it work, i guess i'm in day view.
I found this more useful for getting the absolute file location.
File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());
I found this post by Justin Tulk very helpful. After a couple of attempts, in what one would perceive to be the more official way with react/redux, it shows that it fails due to React's synthetic event pooling. His solution then uses some internal state to track the value changed/entered in the input, with a callback right after setState
which calls a throttled/debounced redux action that shows some results in realtime.
import React, {Component} from 'react'
import TextField from 'material-ui/TextField'
import { debounce } from 'lodash'
class TableSearch extends Component {
constructor(props){
super(props)
this.state = {
value: props.value
}
this.changeSearch = debounce(this.props.changeSearch, 250)
}
handleChange = (e) => {
const val = e.target.value
this.setState({ value: val }, () => {
this.changeSearch(val)
})
}
render() {
return (
<TextField
className = {styles.field}
onChange = {this.handleChange}
value = {this.props.value}
/>
)
}
}
To pull a remote branch locally, I do the following:
git checkout -b branchname
// creates a local branch with the same name and checks out on it
git pull origin branchname
// pulls the remote one onto your local one
The only time I did this and it didn't work, I deleted the repo, cloned it again and repeated the above 2 steps; it worked.
Here's a good reference on the different formatting you can use with regard to the date:
PUT http://{rm http address:port}/ws/v1/cluster/apps/{appid}/state
{
"state":"KILLED"
}
I am using the following construct, although you might want to avoid shell=True
. This gives you the output and error message for any command, and the error code as well:
process = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode
This code will work for you, because i had a simmilar problem and this worked for me. :)
1- Override Onstart() method in your fragment-dialog class.
@Override
public void onStart() {
super.onStart();
final AlertDialog D = (AlertDialog) getDialog();
if (D != null) {
Button positive = (Button) D.getButton(Dialog.BUTTON_POSITIVE);
positive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (edittext.equals("")) {
Toast.makeText(getActivity(), "EditText empty",Toast.LENGTH_SHORT).show();
} else {
D.dismiss(); //dissmiss dialog
}
}
});
}
}
Dog
Cat
I'm wondered by answers we have clear attribute to get empty input boxes, take a look at this code
/*empty input*/
input:empty{
border-color: red;
}
/*input with value*/
input:not(:empty){
border-color: black;
}
UPDATE
input, select, textarea {
border-color: @green;
&:empty {
border-color: @red;
}
}
More over for having a great look in the validation
input, select, textarea {
&[aria-invalid="true"] {
border-color: amber !important;
}
&[aria-invalid="false"], &.valid {
border-color: green !important;
}
}
This works for me:
File file = new File("c:\\myjar.jar");
URL url = file.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.mypackage.myclass");
file
PS /home/edward/Desktop>
Get-Content ./copy.txt
[Desktop Entry]
Name=calibre Exec=~/Apps/calibre/calibre
Icon=~/Apps/calibre/resources/content-server/calibre.png
Type=Application*
Start by get the content from file and trim the white spaces if any found in each line of the text document. That becomes the object passed to the where-object to go through the array looking at each member of the array with string length greater then 0. That object is passed to replace the content of the file you started with. It would probably be better to make a new file... Last thing to do is reads back the newly made file's content and see your awesomeness.
(Get-Content ./copy.txt).Trim() | Where-Object{$_.length -gt 0} | Set-Content ./copy.txt
Get-Content ./copy.txt
After lots of searching This code work for me:
Check the permission already has: Check WRITE_EXTERNAL_STORAGE permission Allowed or not?
if(isReadStorageAllowed()){
//If permission is already having then showing the toast
//Toast.makeText(SplashActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
//Existing the method with return
return;
}else{
requestStoragePermission();
}
private boolean isReadStorageAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED)
return true;
//If permission is not granted returning false
return false;
}
//Requesting permission
private void requestStoragePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}
Implement Override onRequestPermissionsResult method for checking is the user allow or denie
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Checking the request code of our request
if(requestCode == REQUEST_WRITE_STORAGE){
//If permission is granted
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Displaying a toast
Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
}else{
//Displaying another toast if permission is not granted
Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
}
}
Most of the time this compile error comes when unicode(UTF-8 encoded) file compiling
javac -encoding UTF-8 HelloWorld.java
and also You can add this compile option to your IDE
ex: Intellij idea
(File>settings>Java Compiler) add as additional command line parameter
-encoding : encoding Set the source file encoding name, such as EUC-JP and UTF-8.. If -encoding is not specified, the platform default converter is used. (DOC)
inline
instructs the compiler to attempt to embed the function content into the calling code instead of executing an actual call.
For small functions that are called frequently that can make a big performance difference.
However, this is only a "hint", and the compiler may ignore it, and most compilers will try to "inline" even when the keyword is not used, as part of the optimizations, where its possible.
for example:
static int Inc(int i) {return i+1};
.... // some code
int i;
.... // some more code
for (i=0; i<999999; i = Inc(i)) {/*do something here*/};
This tight loop will perform a function call on each iteration, and the function content is actually significantly less than the code the compiler needs to put to perform the call. inline
will essentially instruct the compiler to convert the code above into an equivalent of:
int i;
....
for (i=0; i<999999; i = i+1) { /* do something here */};
Skipping the actual function call and return
Obviously this is an example to show the point, not a real piece of code.
static
refers to the scope. In C it means that the function/variable can only be used within the same translation unit.
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
New feature in Windows - run bash on ubuntu on windows - available in Windows 10 "Insiders" builds after the Build conference:
https://blogs.windows.com/buildingapps/2016/03/30/run-bash-on-ubuntu-on-windows/
Split on newlines (environment agnostic) and print regularly -- no need to worry about encoding or xss:
@if (!string.IsNullOrWhiteSpace(text))
{
var lines = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
<p>@line</p>
}
}
(remove empty entries is optional)
If you are using anaconda step 1: where python step 2: open anaconda prompt in administrator mode step 3: cd <python path> step 4: install the package in this location
Inspired by an answer of @walid2mi:
(Get-Item 'c:\temp\myfile.txt').Basename
Please note: this only works if the given file really exists.
The definitive discussion of arrays is at http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#27803 . This makes clear that Java arrays are objects. The class of these objects is defined in 10.8.
Section 8.4.1 of the language spec, http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#40420 , describe how arguments are passed to methods. Since Java syntax is derived from C and C++, the behavior is similar. Primitive types are passed by value, as with C. When an object is passed, an object reference (pointer) is passed by value, mirroring the C syntax of passing a pointer by value. See 4.3.1, http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.3 ,
In practical terms, this means that modifying the contents of an array within a method is reflected in the array object in the calling scope, but reassigning a new value to the reference within the method has no effect on the reference in the calling scope, which is exactly the behavior you would expect of a pointer to a struct in C or an object in C++.
At least part of the confusion in terminology stems from the history of high level languages prior to the common use of C. In prior, popular, high level languages, directly referencing memory by address was something to be avoided to the extent possible, and it was considered the job of the language to provide a layer of abstraction. This made it necessary for the language to explicitly support a mechanism for returning values from subroutines (not necessarily functions). This mechanism is what is formally meant when referring to 'pass by reference'.
When C was introduced, it came with a stripped down notion of procedure calling, where all arguments are input-only, and the only value returned to the caller is a function result. However, the purpose of passing references could be achieved through the explicit and broad use of pointers. Since it serves the same purpose, the practice of passing a pointer as a reference to a value is often colloquially referred to a passing by reference. If the semantics of a routine call for a parameter to be passed by reference, the syntax of C requires the programmer to explicitly pass a pointer. Passing a pointer by value is the design pattern for implementing pass by reference semantics in C.
Since it can often seem like the sole purpose of raw pointers in C is to create crashing bugs, subsequent developments, especially Java, have sought to return to safer means to pass parameters. However, the dominance of C made it incumbent on the developers to mimic the familiar style of C coding. The result is references that are passed similarly to pointers, but are implemented with more protections to make them safer. An alternative would have been the rich syntax of a language like Ada, but this would have presented the appearance of an unwelcome learning curve, and lessened the likely adoption of Java.
In short, the design of parameter passing for objects, including arrays, in Java,is esentially to serve the semantic intent of pass by reference, but is imlemented with the syntax of passing a reference by value.
Would be safer to do this.
@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}
So the controller for that action runs as well, to populate any model the view needs.
Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.
That's because abc
is undefined at the moment of the template rendering. You can use safe navigation operator (?
) to "protect" template until HTTP call is completed:
{{abc?.xyz?.name}}
You can read more about safe navigation operator here.
Update:
Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf
directive to overcome this problem:
<div *ngIf="arr && arr.length > 0">
{{arr[0].name}}
</div>
Read more about NgIf
directive here.
I have solved the issue using below code in my DBContext
public partial class Q4Sandbox : DbContext { public Q4Sandbox() : base("name=Q4Sandbox") { } public virtual DbSet Employees { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance; } }
Thanks to a SO member.
If you haven't commit the local changes yet since the last pull/clone, you can use:
git checkout *
git pull
checkout
will clear your local changes with the last local commit, and
pull
will sincronize it to the remote repository
For Ubuntu default version is /usr/lib/gradle/default
.
In case of update, you don't need to reassign link in idea/studio.
The new hooks way of doing this is to use useEffect instead of componentWillReceiveProps the old way:
componentWillReceiveProps(nextProps) {
// You don't have to do this check first, but it can help prevent an unneeded render
if (nextProps.startTime !== this.state.startTime) {
this.setState({ startTime: nextProps.startTime });
}
}
becomes the following in a functional hooks driven component:
// store the startTime prop in local state
const [startTime, setStartTime] = useState(props.startTime)
//
useEffect(() => {
if (props.startTime !== startTime) {
setStartTime(props.startTime);
}
}, [props.startTime]);
we set the state using setState, using useEffect we check for changes to the specified prop, and take the action to update the state on change of the prop.
Here's a demo: http://www.w3.org/Style/Examples/007/center-example
A method (JSFiddle example)
CSS:
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table
}
#content {
display: table-cell;
text-align: center;
vertical-align: middle;
}
HTML:
<div id="content">
Content goes here
</div>
Another method (JSFiddle example)
CSS
body, html, #wrapper {
width: 100%;
height: 100%
}
#wrapper {
display: table
}
#main {
display: table-cell;
vertical-align: middle;
text-align:center
}
HTML
<div id="wrapper">
<div id="main">
Content goes here
</div>
</div>
If you are not giving export default then it throws an error. check if you have given module.exports = Speaker; //spelling mistake here you have written exoprts and check in all the modules whether you have exported correct.
Windows version:
cd \Program Files\NVIDIA Corporation\NVSMI
nvidia-smi
If you have already installed all your dependencies, and you want to avoid having to download your production packages from NPM again, you can simply type:
npm prune --production
This will remove your dev dependencies from your node_modules
folder, which is helpful if you're trying to automate a two step process like
Running npm prune
in between will save you from having to reinstall everything!
You can create a new dictionary by sorting the current dictionary by key as per your question.
This is your dictionary
d = {2:3, 1:89, 4:5, 3:0}
Create a new dictionary d1 by sorting this d using lambda function
d1 = dict(sorted(d.items(), key = lambda x:x[0]))
d1 should be {1: 89, 2: 3, 3: 0, 4: 5}, sorted based on keys in d.
The jQuery way to click a link is
$('#LinkID').click();
For mailTo link, you have to write the following code
$('#LinkID')[0].click();
Here's my attempt with Javascript and CSS3 animation So the HTML:
<div id="handle">Fade</div>
<div id="slideSource">Whatever you want images or text here</div>
The CSS3 with transitions:
div#slideSource {
opacity:1;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;
transition: opacity 3s;
}
div#slideSource.fade {
opacity:0;
}
The Javascript part. Check if the className exists, if it does then add the class and transitions.
document.getElementById('handle').onclick = function(){
if(slideSource.className){
document.getElementById('slideSource').className = '';
} else {
document.getElementById('slideSource').className = 'fade';
}
}
Just click and it will fade in and out. I would recommend using JQuery as Itai Sagi mentioned. I left out Opera and MS, so I would recommend using prefixr to add that in the css. This is my first time posting on stackoverflow but it should work fine.
Try
yum list installed | grep reponame
On one of my servers:
yum list installed | grep remi ImageMagick2.x86_64 6.6.5.10-1.el5.remi installed memcache.x86_64 1.4.5-2.el5.remi installed mysql.x86_64 5.1.54-1.el5.remi installed mysql-devel.x86_64 5.1.54-1.el5.remi installed mysql-libs.x86_64 5.1.54-1.el5.remi installed mysql-server.x86_64 5.1.54-1.el5.remi installed mysqlclient15.x86_64 5.0.67-1.el5.remi installed php.x86_64 5.3.5-1.el5.remi installed php-cli.x86_64 5.3.5-1.el5.remi installed php-common.x86_64 5.3.5-1.el5.remi installed php-domxml-php4-php5.noarch 1.21.2-1.el5.remi installed php-fpm.x86_64 5.3.5-1.el5.remi installed php-gd.x86_64 5.3.5-1.el5.remi installed php-mbstring.x86_64 5.3.5-1.el5.remi installed php-mcrypt.x86_64 5.3.5-1.el5.remi installed php-mysql.x86_64 5.3.5-1.el5.remi installed php-pdo.x86_64 5.3.5-1.el5.remi installed php-pear.noarch 1:1.9.1-6.el5.remi installed php-pecl-apc.x86_64 3.1.6-1.el5.remi installed php-pecl-imagick.x86_64 3.0.1-1.el5.remi.1 installed php-pecl-memcache.x86_64 3.0.5-1.el5.remi installed php-pecl-xdebug.x86_64 2.1.0-1.el5.remi installed php-soap.x86_64 5.3.5-1.el5.remi installed php-xml.x86_64 5.3.5-1.el5.remi installed remi-release.noarch 5-8.el5.remi installed
It works.
Issue Log: App Not Setup. This app is still in development mode. and you dont have access to it. register test user or ask an app admin for permission
HOW TO CHANGE TO LIVE MODE
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. toggle the switch from OFF to ON
HOW TO ADD AS TEST OR ADMIN
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. go to : Roles > Roles > Press Add for example administrator
4. Search your new admin/tester Facebook account.
5. admin must enter facebook password to confirm.then submit
the new admin must go to developer.facebook page and accept the request
6. go to : https://developers.facebook.com
7. Profile > Requests > Confirm
8. Congratulation you have been assign as new Admin
HOW TO GET AND SET HASHKEY FOR DEVELOPMENT
as Refer to Facebook Login Documentation
https://developers.facebook.com/docs/android/getting-started/#create_hash
The most preferable solution by me is by code ( Troubleshooting Sample Apps )
it will print out the hash key. you can update it on
https://developers.facebook.com/apps/yourFacebookappID/settings/basic/
on Android > Key Hashes section
a step by step process on how to get the hashKey.
step by step process on how Update on Facebook Developer.
Open Facebook Developer Page. You need access as to update the Facebook Developer page.
https://developers.facebook.com
I have remixed the answer by @isubuz and this answer by @Umur Kontaci on attribute directives into a version where your controller doesn't call a DOM-like operation like "dismiss", but instead tries to be more MVVM style, setting a boolean property isInEditMode
. The view in turn links this bit of info to the attribute directive that opens/closes the bootstrap modal.
var app = angular.module('myApp', []);_x000D_
_x000D_
app.directive('myModal', function() {_x000D_
return {_x000D_
restrict: 'A',_x000D_
scope: { myModalIsOpen: '=' },_x000D_
link: function(scope, element, attr) {_x000D_
scope.$watch(_x000D_
function() { return scope.myModalIsOpen; },_x000D_
function() { element.modal(scope.myModalIsOpen ? 'show' : 'hide'); }_x000D_
);_x000D_
}_x000D_
} _x000D_
});_x000D_
_x000D_
app.controller('MyCtrl', function($scope) {_x000D_
$scope.isInEditMode = false;_x000D_
$scope.toggleEditMode = function() { _x000D_
$scope.isInEditMode = !$scope.isInEditMode;_x000D_
};_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MyCtrl as vm">_x000D_
_x000D_
<div class="modal fade" my-modal my-modal-is-open="isInEditMode">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-body">_x000D_
Modal body! IsInEditMode == {{isInEditMode}}_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button class="btn" ng-click="toggleEditMode()">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<p><button class="btn" ng-click="toggleEditMode()">Toggle Edit Mode</button></p> _x000D_
<pre>isInEditMode == {{isInEditMode}}</pre>_x000D_
_x000D_
</div>
_x000D_
One option would be to use the onResume of your first activity.
@Override
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
}
Or you can start Activity for Result:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
In secondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
if you don't want to return data:
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
Now in your FirstActivity class write following code for onActivityResult()
method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
//Update List
}
if (resultCode == RESULT_CANCELED) {
//Do nothing?
}
}
}//onActivityResult
Here is a good article from the MDC which explains the problems (and solutions) to form autocompletion. Microsoft has published something similar here, as well.
To be honest, if this is something important to your users, 'breaking' standards in this way seems appropriate. For example, Amazon uses the 'autocomplete' attribute quite a bit, and it seems to work well.
If you want to remove the warning entirely, you can use JavaScript to apply the attribute to browsers that support it (IE and Firefox are the important browsers) using someForm.setAttribute( "autocomplete", "off" ); someFormElm.setAttribute( "autocomplete", "off" );
Finally, if your site is using HTTPS, IE automatically turns off autocompletion (as do some other browsers, as far as I know).
Update
As this answer still gets quite a few upvotes, I just wanted to point out that in HTML5, you can use the 'autocomplete' attribute on your form element. See the documentation on W3C for it.
Check out androPHP I use it for testing on android ANdroPHP.
If you want to completely abuse the data.frame (as I do) and like to keep the $ functionality, one way is to split you data.frame into one-line data.frames gathered in a list :
> df = data.frame(x=c('a','b','c'), y=3:1)
> df
x y
1 a 3
2 b 2
3 c 1
# 'convert' into a list of data.frames
ldf = lapply(as.list(1:dim(df)[1]), function(x) df[x[1],])
> ldf
[[1]]
x y
1 a 3
[[2]]
x y
2 b 2
[[3]]
x y
3 c 1
# and the 'coolest'
> ldf[[2]]$y
[1] 2
It is not only intellectual masturbation, but allows to 'transform' the data.frame into a list of its lines, keeping the $ indexation which can be useful for further use with lapply (assuming the function you pass to lapply uses this $ indexation)
Like konsolebox suggested, the posters grep solution
grep -v -f file2 file1
actually works great (fast) if you simply add the -F
option, to treat the patterns as fixed strings instead of regular expressions. I verified this on a pair of ~1000 line file lists I had to compare. With -F
it took 0.031 s (real), while without it took 2.278 s (real), when redirecting grep output to wc -l
.
These tests also included the -x
switch, which are necessary part of the solution in order to ensure totally accuracy in cases where file2 contains lines which match part of, but not all of, one or more lines in file1.
So a solution that does not require the inputs to be sorted, is fast, flexible (case sensitivity, etc) is:
grep -F -x -v -f file2 file1
This doesn't work with all versions of grep, for example it fails in macOS, where a line in file 1 will be shown as not present in file 2, even though it is, if it matches another line that is a substring of it. Alternatively you can install GNU grep on macOS in order to use this solution.
If you want to revert the file to its state in master
:
git checkout origin/master [filename]
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
ES6 array destructuring is used to swap two variables. See example
var [x,y]=[1,2];
[x,y]=[y,x];
Easier way possible with :
x === 1
and y === 2
;
But after destructuring, x
is y
, i.e. 2
, and y
is x
, i.e. 1
.
This looks like an old thread but there is one more variant of how we can set an environment variable in the Gradle task.
task runSomeRandomTask(type: NpmTask, dependsOn: [npmInstall]) {
environment = [ 'NODE_ENV': 'development', BASE_URL: '3000' ]
args = ['run']
}
The above Gradle task integrates the Gradle and npm tasks.
This way we can pass multiple environment variables. Hope this helps to broaden the understanding which the answers above have already provided. Cheers!!
You probably want to use a JSON list instead of a dictionary as the toplevel element.
So, initialize the file with an empty list:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
json.dump([], f)
Then, you can append new entries to this list:
with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append(entry)
json.dump(feeds, feedsjson)
Note that this will be slow to execute because you will rewrite the full contents of the file every time you call add
. If you are calling it in a loop, consider adding all the feeds to a list in advance, then writing the list out in one go.
The official length according to the offical Apache docs is 8,192, but many folks have run into trouble at ~4,000.
MS Internet Explorer is usually the limiting factor anyway, as it caps the maximum URL size at 2,048.
Just write :
$(document).ready( function () {
$('#example').dataTable( {
"lengthChange": false
} );
} );
CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.
I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.
you can use something like this.It worked out for me
doc = parse('C:\\eve.xml')
my_node_list = doc.getElementsByTagName("name")
my_n_node = my_node_list[0]
my_child = my_n_node.firstChild
my_text = my_child.data
print my_text
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
pwd
: to check where you are (If necessary)
cd
: change directory
In your case if I understand you, you need:
cd c/project
You could just use glob
with recursive = true
, the pattern **
will match any files and zero or more directories, subdirectories and symbolic links to directories.
import glob, os
os.chdir("C:\\Users\\username\\Desktop\\MAIN_DIRECTORY")
for file in glob.glob("*/.csv", recursive = true):
print(file)
If you have tsocks or proxychains installed and configured, you can
$ tsocks git clone <you_repository>
or
$ proxychains git clone <you_repository>
to make it shorter, I created a symbol link /usr/bin/p
for proxychains
, so I can use it like this
p git clone <you_repository>
and I can use it to proxy any command,
p <cmd-need-be-proxied>
by the way, proxychains is not updated for a long time, you may wanna try proxychians-ng
I opened "Passwords and Keys" application in my Unity and removed unwanted keys from Secure Keys -> OpenSSH keys And they automatically had been removed from ssh-agent -l as well.
This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:
/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
for (var l = 0; l < ph[i].length; l++) {
/* create a function which swaps an image, and calls the next function in the queue */
theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
/* set the animation speed */
theQueue.delay(200,'anim');
}
}
/* start the animation */
theQueue.dequeue('anim');
This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.
change line code of /node_modules/react-native/local-cli/runIOS/findMatchingSimulator.js
line 55
if (
simulator.availability !== '(available)' &&
simulator.isAvailable !== true
) {
continue;
}
replace which:
if (
simulator.availability !== '(available)' &&
simulator.isAvailable !== true
) {
continue;
}
Using jquery, try this. if your button id is say id= clickme
$("clickme").on('çlick', function(){
$(this).css('background-color', 'grey'); .......
Might sound a strange solution, but you can give it a try :
<?php $jsEnabledVar = 0; ?>
<script type="text/javascript">
var jsenabled = 1;
if(jsenabled == 1)
{
<?php $jsEnabledVar = 1; ?>
}
</script>
<noscript>
var jsenabled = 0;
if(jsenabled == 0)
{
<?php $jsEnabledVar = 0; ?>
}
</noscript>
Now use the value of '$jsEnabledVar' throughout the page. You may also use it to display a block indicating the user that JS is turned off.
hope this will help
spinner.setSelection(Adapter.NO_SELECTION, false);
In both examples, you are assigning a new int[10]
to a reference variable.
Assigning to a reference variable either way will be equal in performance.
int[] array = new int[10];
The notation above is considered best practice for readability.
Cheers
After updating my Android SDK I stumbled upon this very problem and I tried many ways without success. What was most irritating to me when searching for a fix, were the lots of answers suggesting to change the CompileSdkVersion to a certain number while obviously this number changes with time, so here's what I did instead.
I created a new project and ran it on the emulator to make sure it's working, then checked its "\android\app\build.gradle" file and copied the numeric value of CompileSdkVersion and pasted into the same file in my other project that could not be built properly anymore. Now my problem's gone. Hope that helps.
Enter SQL*Plus with:
sqlplus /nolog
And then:
connect sys@<SID> AS sysdba
My guess is that you have a problem since you don't close your select-tag after the loop. Could that do the trick?
<select name="owner">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>
Create a shortcut of anaconda prompt onto desktop or taskbar, and then in the properties of that shortcut make sure u modify the last path in "Target:" to the path of ur environment:
C:\Users\BenBouali\Anaconda3\ WILL CHANGE INTO C:\Users\BenBouali\Anaconda3\envs\tensorflow-gpu
and this way u can use that shortcut to open a certain environment when clicking it, you can add it to ur path too and now you'll be able to run it from windows run box by just typing in the name of the shortcut.
We can take help of Pandas:
import pandas as pd
As mentioned above in the problem We have:
datetime(2017, 10, 20)
If execute this line in the jupyter notebook we have an output like this:
datetime.datetime(2017, 10, 20, 0, 0)
Using weekday() and weekday_name:
If you want weekdays in integer number format then use:
pd.to_datetime(datetime(2017, 10, 20)).weekday()
The output will be:
4
And if you want it as name of the day like Sunday, Monday, Friday, etc you can use:
pd.to_datetime(datetime(2017, 10, 20)).weekday_name
The output will be:
'Friday'
If having a dates column in Pandas dataframe then:
Now suppose if you have a pandas dataframe having a date column like this: pdExampleDataFrame['Dates'].head(5)
0 2010-04-01
1 2010-04-02
2 2010-04-03
3 2010-04-04
4 2010-04-05
Name: Dates, dtype: datetime64[ns]
Now If we want to know the name of the weekday like Monday, Tuesday, ..etc we can use .weekday_name
as follows:
pdExampleDataFrame.head(5)['Dates'].dt.weekday_name
the output will be:
0 Thursday
1 Friday
2 Saturday
3 Sunday
4 Monday
Name: Dates, dtype: object
And if we want the integer number of weekday from this Dates column then we can use:
pdExampleDataFrame.head(5)['Dates'].apply(lambda x: x.weekday())
The output will look like this:
0 3
1 4
2 5
3 6
4 0
Name: Dates, dtype: int64
DECLARE @SQL AS VARCHAR(8000)
SELECT @SQL = ISNULL(@SQL+',','') + ColumnName FROM TableName
SELECT @SQL
I am unable to get this working with the javac compiler, and I get the same error.
Error:(9, 14) java: package lombok does not exist
I have enabled annotation processor, and have also tried rebuilding the project, invalidate cache/restart. Doesn't help.
I did however get it to work partially with eclipse compiler. I say partial because although the build passes successfully, the editor still complains about "Cannot resolve symbol".
Idea - 15.04 community edition Lombok - 1.16.6 Lombok plugin (https://github.com/mplushnikov/lombok-intellij-plugin) - 0.9.8 JDK - 1.8.0_51
Update: Ok, I finally got this working. Mine was a gradle project, and lombok was configured as a custom "provided" configuration. Worked fine after adding this in build.gradle
idea {
module {
scopes.PROVIDED.plus += [configurations.provided]
}
}
So, 3 steps
The question is what do you want the div's height/width to be a percent of?
By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.
So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:
obj.style.width = '50%';
You can also access through docker exec command by:
$ docker exec -it postgres-container bash
# su postgres
$ psql
Or
$ docker exec -it postgres-container psql -U postgres
NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.
Comment with <leader>cc
. Uncomment with <leader>cu
. And toggle comments with <leader>c<space>
.
(The default <leader>
key in vim is \
)
By postfixing the URL with ?WSDL
If the URL is for example:
http://webservice.example:1234/foo
You use:
http://webservice.example:1234/foo?WSDL
And the wsdl will be delivered.
This code will return the absolute path to the main script.
import os
def whereAmI():
return os.path.dirname(os.path.realpath(__import__("__main__").__file__))
This will work even in a module.
As of 2016, you can do this more simply than in any of the answers already given:
$('#myChosenBox').val();
where "myChosenBox" is the id of the original select input. Or, in the change event:
$('#myChosenBox').on('change', function(e, params) {
alert(e.target.value); // OR
alert(this.value); // OR
alert(params.selected); // also in Panagiotis Kousaris' answer
}
In the Chosen doc, in the section near the bottom of the page on triggering events, it says "Chosen triggers a number of standard and custom events on the original select field." One of those standard events is the change event, so you can use it in the same way as you would with a standard select input. You don't have to mess around with using Chosen's applied classes as selectors if you don't want to. (For the change
event, that is. Other events are often a different matter.)
From JavaEE docs ServletResponse#setContentType
Sets the content type of the response being sent to the client, if the response has not been committed yet.
The given content type may include a character encoding specification, for example,
response.setContentType("text/html;charset=UTF-8");
The response's character encoding is only set from the given content type if this method is called before getWriter
is called.
This method may be called repeatedly to change content type and character encoding.
This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter
has been called or after the response has been committed.
Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up notitle
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set up full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
I have also faced this problem.Double check the result in the error window.
In my case, a tailing \
was crashing xcopy (as I was using $(TargetDir)
). In my case $(SolutionDir)..\bin
. If you're using any other output, this needs to be adjusted.
Also note that start xcopy
does not fix it, if the error is gone after compiling. It might have just been suppressed by the command line and no file has actually been copied!
You can btw manually execute your xcopy commands in a command shell. You will get more details when executing them there, pointing you in the right direction.
Seems to work fine.
If you have an empty BEGIN ... END block you might see
Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.
My recommendation is to use basename
.
It is by default in Ubuntu, visually simple code and deal with majority of cases.
Here are some sub-cases to deal with spaces and multi-dot/sub-extension:
pathfile="../space fld/space -file.tar.gz"
echo ${pathfile//+(*\/|.*)}
It usually get rid of extension from first .
, but fail in our ..
path
echo **"$(basename "${pathfile%.*}")"**
space -file.tar # I believe we needed exatly that
Here is an important note:
I used double quotes inside double quotes to deal with spaces. Single quote will not pass due to texting the $. Bash is unusual and reads "second "first" quotes" due to expansion.
However, you still need to think of .hidden_files
hidden="~/.bashrc"
echo "$(basename "${hidden%.*}")" # will produce "~" !!!
not the expected "" outcome. To make it happen use $HOME
or /home/user_path/
because again bash is "unusual" and don't expand "~" (search for bash BashPitfalls)
hidden2="$HOME/.bashrc" ; echo '$(basename "${pathfile%.*}")'
Json.NET does this...
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }
More examples: Serializing Collections with Json.NET
If you're just interested in timestamps in GMT you can also do this, which can be conveniently adapted for different intervals (hour: 1000 * 60 * 60
, 12 hours: 1000 * 60 * 60 * 12
, etc.)
const interval = 1000 * 60 * 60 * 24; // 24 hours in milliseconds
let startOfDay = Math.floor(Date.now() / interval) * interval;
let endOfDay = startOfDay + interval - 1; // 23:59:59:9999
Try echo $'a\nb'
.
If you want to store it in a variable and then use it with the newlines intact, you will have to quote your usage correctly:
var=$'a\nb\nc'
echo "$var"
Or, to fix your example program literally:
var="a b c"
for i in $var; do
p="`echo -e "$p\\n$i"`"
done
echo "$p"
Regarding the elegant connection.setUseCaches
solution above: sadly, it won't work without some additional effort. You will need to install a ResponseCache
using ResponseCache.setDefault
. Otherwise, HttpURLConnection
will silently ignore the setUseCaches(true)
bit.
See the comments at the top of FileResponseCache.java
for details:
(I'd post this in a comment, but I apparently don't have enough SO karma.)
res.json
forces the argument to JSON. res.send
will take an non-json object or non-json array and send another type. For example:
This will return a JSON number.
res.json(100)
This will return a status code and issue a warning to use sendStatus.
res.send(100)
If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json
.
Well, it's worth noting that they don't mean the same thing at all.
If the DEBUG symbol isn't defined, then in the first case the SetPrivateValue
itself won't be called... whereas in the second case it will exist, but any callers who are compiled without the DEBUG symbol will have those calls omitted.
If the code and all its callers are in the same assembly this difference is less important - but it means that in the first case you also need to have #if DEBUG
around the calling code as well.
Personally I'd recommend the second approach - but you do need to keep the difference between them clear in your head.
(question) Don't you get that info in
select * from pg_user;
or using the view pg_stat_activity:
select * from pg_stat_activity;
Added:
the view says:
One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.
can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...
something like that.
<EditText
android:id="@+id/txtDate"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="2dp"
android:clickable="false"
android:cursorVisible="false"
android:gravity="center" />
and use following :
txtDate.setKeyListener(null);
This fixed my problem but it crashed unless I changed
action:@selector(switchToNewsDetails:event:)
to
action:@selector(switchToNewsDetails: forEvent:)
You can use sys.exit()
to exit from the middle of the main function.
However, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__
- then you can use return as normal.
private class ObjectAdapter extends BaseAdapter {
private Context context;
private List<Object>objects;
public ObjectAdapter(Context context, List<Object> objects) {
this.context = context;
this.objects = objects;
}
@Override
public int getCount() {
return objects.size();
}
@Override
public Object getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
holder.text = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(getItem(position).toString()));
return convertView;
}
class ViewHolder {
TextView text;
}
}
I needed to more item instead of just one. So, I wrote this:
public static TList GetSelectedRandom<TList>(this TList list, int count)
where TList : IList, new()
{
var r = new Random();
var rList = new TList();
while (count > 0 && list.Count > 0)
{
var n = r.Next(0, list.Count);
var e = list[n];
rList.Add(e);
list.RemoveAt(n);
count--;
}
return rList;
}
With this, you can get elements how many you want as randomly like this:
var _allItems = new List<TModel>()
{
// ...
// ...
// ...
}
var randomItemList = _allItems.GetSelectedRandom(10);
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
The more "functional" approach without using those ugly while loops:
def tryAgain(retries=0):
if retries > 10: return
try:
# Do stuff
except:
retries+=1
tryAgain(retries)
tryAgain()
Here's a workaround for installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit MS Office version installed:
Now you can start a 32-bit MS Office application without the "re-configuring" issue. Note that the "mso.dll" registry value will already be present if a 64-bit version of MS Office is installed. In this case the value should not be deleted or renamed.
Also if you do not want to use the "/passive" command line parameter you can edit the AceRedist.msi file to remove the MS Office architecture check:
You can now use this file to install the Microsoft Access Database Engine 2010 redistributable on a system where a "conflicting" version of MS Office is installed (e.g. 64-bit version on system with 32-bit MS Office version) Make sure that you rename the "mso.dll" registry value as explained above (if needed).
Basically you can put HTML anywhere outside of PHP tags. It's also very beneficial to do all your necessary data processing before displaying any data, in order to separate logic and presentation.
The data display itself could be at the bottom of the same PHP file or you could include a separate PHP file consisting of mostly HTML.
I prefer this compact style:
<?php
/* do your processing here */
?>
<html>
<head>
<title><?=$title?></title>
</head>
<body>
<?php foreach ( $something as $item ) : ?>
<p><?=$item?></p>
<?php endforeach; ?>
</body>
</html>
Note: you may need to use <?php echo $var; ?>
instead of <?=$var?>
depending on your PHP setup.
Can use setdiff
function:
If there are more columns to keep than to delete: Suppose you want to delete 2 columns say col1, col2 from a data.frame DT; you can do the following:
DT<-DT[,setdiff(names(DT),c("col1","col2"))]
If there are more columns to delete than to keep: Suppose you want to keep only col1 and col2:
DT<-DT[,c("col1","col2")]
The equivalent in a more modern and browser compatible way, using modern addEventListener APIs.
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
along with below command line parameters ,
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
Sometimes in the linux servers , imx connection doesn't get succeeded. that is because , in cloud linux host, in /etc/hosts so that the hostname resolves to the host address.
the best way to fix it is, ping the particular linux server from other machine in network and use that host IP address in the
-Djava.rmi.server.hostname=IP address that obtained when you ping that linux server.
But never rely on the ipaddress that you get from linux server using ifconfig.me. the ip that you get there is masked one which is present in the host file.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
I am bit late to comment in this question but it might be useful for some other people.
You can make your android phone to work like keyboard, mouse, camera, sound streaming system, tethering device. In short what ever usb gadget you see in the market and until and unless hardware doesn't limit you. Such as speed, or gadget interface not available.
USB device is of two type, host and gadget. So gadget device acts like client and usually has usb otg interface in most of the phones. So in gadget end, you can make your phone to behave like different device at all by switching between different configuration(you are already doing it when you go into usb settings and make your device as mass storage or anything else).
But for doing all these you have to modify android kernel. If you are a android device developer you can for sure do it.
It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12
.
[note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]
keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:
Re-enter new password:
Enter source keystore password:
[Storing myp12file.p12]
Now the file myp12file.p12
contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12
command. For example,
openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
friendlyName: mykey
localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----
Prints out the private key unencrypted.
Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.
use function: atoi for array to integer, atof for array to float type; or
char c = '5';
int b = c - 48;
printf("%d", b);
There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select '1,2,3,a,b,c,d' str from dual
3 )
4 select regexp_substr(str,'[^,]+',1,level) element
5 from x
6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /
ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d
7 rows selected.
Or in PL/SQL
SQL> create type str_tbl is table of varchar2(100);
2 /
Type created.
SQL> create or replace function parse_list( p_list in varchar2 )
2 return str_tbl
3 pipelined
4 is
5 begin
6 for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
7 from dual
8 connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
9 loop
10 pipe row( x.element );
11 end loop
12 return;
13 end;
14
15 /
Function created.
SQL> select *
2 from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));
COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f
9 rows selected.
.buttonDisabled{
background-color: unset !important;
color: unset !important;
}
When I see Spring framework source code,I find this way
Properties props = getPropertiesFromSomeWhere();
// change properties to map
Map<String,String> map = new HashMap(props)
Here's an idea using Object.defineProperty
which directly modifies the way a property is accessed.
Code:
function bind(base, el, varname) {
Object.defineProperty(base, varname, {
get: () => {
return el.value;
},
set: (value) => {
el.value = value;
}
})
}
Usage:
var p = new some_class();
bind(p,document.getElementById("someID"),'variable');
p.variable="yes"
fiddle: Here
If you are wanting to configure this locally on OS X 10.8 serving Angular with Apache then you might find the following in your .htaccess file helps:
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteBase /~yourusername/appname/public/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png|jpg|jpeg|gif|txt)
RewriteRule (.*) index.html [L]
</IfModule>
Options +FollowSymlinks if not set may give you a forbidden error in the logs like so:
Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden
Rewrite base is required otherwise requests will be resolved to your server root which locally by default is not your project directory unless you have specifically configured your vhosts, so you need to set the path so that the request finds your project root directory. For example on my machine I have a /Users/me/Sites directory where I keep all my projects. Like the old OS X set up.
The next two lines effectively say if the path is not a directory or a file, so you need to make sure you have no files or directories the same as your app route paths.
The next condition says if request not ending with file extensions specified so add what you need there
And the [L] last one is saying to serve the index.html file - your app for all other requests.
If you still have problems then check the apache log, it will probably give you useful hints:
/private/var/log/apache2/error_log
No, there isn't in HTML. There is a good reason why the developers chose to go out of their way to remove support for an element whose implementation was otherwise untouched for upwards of a decade.
That said... you could emulate it using a CSS animation, but if I were you, I wouldn't risk CSS animations being axed due to being abused in this manner :)
The solution that worked for me in win and linux is the folling
// GET api/values
[HttpGet("cifrado/{xml}")]
public ActionResult<IEnumerable<string>> Cifrado(String xml)
{
String nombreXML = DateTime.Now.ToString("ddMMyyyyhhmmss").ToString();
String archivo = "/app/files/"+nombreXML + ".XML";
String comando = " --armor --recipient [email protected] --encrypt " + archivo;
try{
System.IO.File.WriteAllText(archivo, xml);
//String comando = "C:\\GnuPG\\bin\\gpg.exe --recipient [email protected] --armor --encrypt C:\\Users\\Administrador\\Documents\\pruebas\\nuevo.xml ";
ProcessStartInfo startInfo = new ProcessStartInfo() {FileName = "/usr/bin/gpg", Arguments = comando };
Process proc = new Process() { StartInfo = startInfo, };
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
proc.WaitForExit();
Console.WriteLine(proc.StandardOutput.ReadToEnd());
return new string[] { "Archivo encriptado", archivo + " - "+ comando};
}catch (Exception exception){
return new string[] { archivo, "exception: "+exception.ToString() + " - "+ comando };
}
}
If we use=> .equals method
if(obj.equals(null))
// Which mean null.equals(null) when obj will be null.
When your obj will be null it will throw Null Point Exception.
so we should use ==
if(obj == null)
it will compare the references.
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
I have created a function that allows me to obtain this feature:
function redirect_blank(url) {
var a = document.createElement('a');
a.target="_blank";
a.href=url;
a.click();
}
I had an array of strings, not objects and i used this approach:
ng-repeat="name in names | unique"
with this filter:
angular.module('app').filter('unique', unique);
function unique(){
return function(arry){
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
};
if(arry === undefined || arry.length === 0){
return '';
}
else {
return arry.getUnique();
}
};
}
Swift 3:
self.btn.sendActions(for: .touchUpInside)
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break
. That will do it.
The issue you have encountered is that UDF
s cannot modify the Excel environment, they can only return a value to the calling cell.
There are several alternatives
For the sample given you don't actually need VBA. This formula will work
='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2
Use a rather messy work around: See this answer
You can use ExecuteExcel4Macro
or OLEDB
ctype_digit
was built precisely for this purpose.
It's a ProgressDialog, with setIndeterminate(true).
From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)