Another solution if you have installed android-studio-bundle-143.2915827-windows and gradle2.14
You can verify in C:\Program Files\Android\Android Studio\gradle if you have gradle-2.14.
Then you must go to C:\Users\\AndroidStudioProjects\android_app\
And in this build.gradle you put this code:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
Then, go to C:\Users\Raul\AndroidStudioProjects\android_app\Desnutricion_infantil\app
And in this build.gradle you put:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '24.0.0'
defaultConfig {
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
}
dependencies {
compile 'com.android.support:appcompat-v7:23.3.0'
}
You must check your sdk version and the buildTools. compileSdkVersion 23 buildToolsVersion '24.0.0'
Save all changes and restart AndroidStudio and all should be fine !
If you are using at least git 1.7.7 (which taught clone
the --config
option), to turn the current directory into a working copy:
git clone example.com/my.git ./.git --mirror --config core.bare=false
This works by:
.git
folder--mirror
makes the new clone into a purely metadata folder as .git
needs to be--config core.bare=false
countermands the implicit bare=true
of the --mirror
option, thereby allowing the repository to have an associated working directory and act like a normal cloneThis obviously won't work if a .git
metadata directory already exists in the directory you wish to turn into a working copy.
The USB drivers in \extras\google\usb_driver didn't work for me.
However the official drivers from Samsung did: http://developer.samsung.com/android/tools-sdks/Samsung-Andorid-USB-Driver-for-Windows
Note: I'm using a Samsung Galaxy S2 with Android 4.0 on Windows 7 64bit
Try this instead in the end:
exec (@query)
If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.
OR
EXECUTE sp_executesql @query
And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.
Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.
On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?
public DataSet GetDataSet(string ConnectionString, string SQL)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
///conn.Open();
da.Fill(ds);
///conn.Close();
return ds;
}
Take a look at the Wikipedia link
JavaScript, despite the name, is essentially unrelated to the Java programming language, although both have the common C syntax, and JavaScript copies many Java names and naming conventions. The language was originally named "LiveScript" but was renamed in a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. The key design principles within JavaScript are inherited from the Self and Scheme programming languages.
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
I was having session file not found error while tried various ways, finally achieved like this. Made the function as static (which I want to call in the another controller), and called like
require_once('Welcome.php');
Welcome::hello();
sudo dscl . -create /Users/joeadmin
sudo dscl . -create /Users/joeadmin UserShell /bin/bash
sudo dscl . -create /Users/joeadmin RealName "Joe Admin"
sudo dscl . -create /Users/joeadmin UniqueID "510"
sudo dscl . -create /Users/joeadmin PrimaryGroupID 20
sudo dscl . -create /Users/joeadmin NFSHomeDirectory /Users/joeadmin
sudo dscl . -passwd /Users/joeadmin password
sudo dscl . -append /Groups/admin GroupMembership joeadmin
press enter after every sentence
Then do a:
sudo reboot
Change joeadmin to whatever you want, but it has to be the same all the way through. You can also put a password of your choice after password.
#include <stdio.h>
#include <math.h>
/*
To define a new type name with typedef, follow these steps:
1. Write the statement as if a variable of the desired type were being declared.
2. Where the name of the declared variable would normally appear, substitute the new type name.
3. In front of everything, place the keyword typedef.
*/
// typedef a primitive data type
typedef double distance;
// typedef struct
typedef struct{
int x;
int y;
} point;
//typedef an array
typedef point points[100];
points ps = {0}; // ps is an array of 100 point
// typedef a function
typedef distance (*distanceFun_p)(point,point) ; // TYPE_DEF distanceFun_p TO BE int (*distanceFun_p)(point,point)
// prototype a function
distance findDistance(point, point);
int main(int argc, char const *argv[])
{
// delcare a function pointer
distanceFun_p func_p;
// initialize the function pointer with a function address
func_p = findDistance;
// initialize two point variables
point p1 = {0,0} , p2 = {1,1};
// call the function through the pointer
distance d = func_p(p1,p2);
printf("the distance is %f\n", d );
return 0;
}
distance findDistance(point p1, point p2)
{
distance xdiff = p1.x - p2.x;
distance ydiff = p1.y - p2.y;
return sqrt( (xdiff * xdiff) + (ydiff * ydiff) );
}
I had similar issues (I tried to create a nested RecyclerViews something like Google PlayStore design). The best way to deal with this is by subclassing the child RecyclerViews and overriding the 'onInterceptTouchEvent' and 'onTouchEvent' methods. This way you get complete control of how those events behave and eventually scrolling.
Dictionary<string, double> accounts;
i found that my google payment account was not activated. i activated it and the error was solved. link for vitrification: google account verification
Code that is built into shared libraries should normally be position-independent code, so that the shared library can readily be loaded at (more or less) any address in memory. The -fPIC
option ensures that GCC produces such code.
In C++17 this is called structured bindings, which allows for the following:
std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
std::cout << k << "=" << v << "\n";
}
In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().
When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that
You can pass an array and let php/curl do the dirty work of encoding etc.
This gives you last used row in a specified column.
Optionally you can specify worksheet, else it will takes active sheet.
Function shtRowCount(colm As Integer, Optional ws As Worksheet) As Long
If ws Is Nothing Then Set ws = ActiveSheet
If ws.Cells(Rows.Count, colm) <> "" Then
shtRowCount = ws.Cells(Rows.Count, colm).Row
Exit Function
End If
shtRowCount = ws.Cells(Rows.Count, colm).Row
If shtRowCount = 1 Then
If ws.Cells(1, colm) = "" Then
shtRowCount = 0
Else
shtRowCount = 1
End If
End If
End Function
Sub test()
Dim lgLastRow As Long
lgLastRow = shtRowCount(2) 'Column B
End Sub
@echo on>out.txt
@echo off
setlocal enabledelayedexpansion
set "parentfolder=%CD%"
for /r . %%g in (*.*) do (
set "var=%%g"
set var=!var:%parentfolder%=!
echo !var! >> out.txt
)
In scenarios where you want to avoid using row_count(), you can also use a left join:
select ds.DocumentID, ds.Status, ds.DateCreated
from DocumentStatusLogs ds
left join DocumentStatusLogs filter
ON ds.DocumentID = filter.DocumentID
-- Match any row that has another row that was created after it.
AND ds.DateCreated < filter.DateCreated
-- then filter out any rows that matched
where filter.DocumentID is null
For the example schema, you could also use a "not in subquery", which generally compiles to the same output as the left join:
select ds.DocumentID, ds.Status, ds.DateCreated
from DocumentStatusLogs ds
WHERE ds.ID NOT IN (
SELECT filter.ID
FROM DocumentStatusLogs filter
WHERE ds.DocumentID = filter.DocumentID
AND ds.DateCreated < filter.DateCreated)
Note, the subquery pattern wouldn't work if the table didn't have at least one single-column unique key/constraint/index, in this case the primary key "Id".
Both of these queries tend to be more "expensive" than the row_count() query (as measured by Query Analyzer). However, you might encounter scenarios where they return results faster or enable other optimizations.
Point A: Don't use list as a variable name Point B: You don't need the [0] just
print(list[x])
I managed to connect to postgres with SQL Developer. I downloaded postgres jdbc driver and saved it in a folder. I run SQL Developer -> Tools -> Preferences -> Search -> JDBC I defined postgres jdbc driver for the Database and Data Modeler (optional).
This is the trick. When creating new connection define Hostname like localhost/crm? where crm is the database name. Test the connection, works fine.
Do I really have to first convert it into an array of arrays of key-value pairs?
No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:
function* entries(obj) {
for (let key in obj)
yield [key, obj[key]];
}
const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'
In my case, it was because I was moving a project from Eclipse 7.1 to an older install of 7.0 on a different computer. You may want to check your eclipse versions.
You can get your result by simply use substr():
Syntax substr(string,start,length)
Example
<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>
Output :
Hello
There is a really simple way to do this using a more recent version of SQL Server Management Studio (I'm using 18.4)
Login gone! No messing around with dlls or bin files.
Couldn't you just write all the commands into a .cmd file in the temp folder and then execute that file?
Update:
I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.
I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.
There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com
try to do this in the behind code
public diagboxclass()
{
List<object> list = new List<object>();
list = GetObjectList();
Imported.ItemsSource = null;
Imported.ItemsSource = list;
}
Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.
ianhanniballake is right. You can get all the functionality of Activity
from FragmentActivity
. In fact, FragmentActivity
has more functionality.
Using FragmentActivity
you can easily build tab and swap
format. For each tab you can use different Fragment
(Fragments
are reusable). So for any FragmentActivity
you can reuse the same Fragment
.
Still you can use Activity
for single pages like list down something and edit element of the list in next page.
Also remember to use Activity
if you are using android.app.Fragment
; use FragmentActivity
if you are using android.support.v4.app.Fragment
. Never attach a android.support.v4.app.Fragment
to an android.app.Activity
, as this will cause an exception to be thrown.
I answered a very similar question, and here is a way of doing this :
First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts
In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.
This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.
animations.ts
import { trigger, state, style, transition,
animate, group, query, stagger, keyframes
} from '@angular/animations';
export const SlideInOutAnimation = [
trigger('slideInOut', [
state('in', style({
'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
})),
state('out', style({
'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
})),
transition('in => out', [group([
animate('400ms ease-in-out', style({
'opacity': '0'
})),
animate('600ms ease-in-out', style({
'max-height': '0px'
})),
animate('700ms ease-in-out', style({
'visibility': 'hidden'
}))
]
)]),
transition('out => in', [group([
animate('1ms ease-in-out', style({
'visibility': 'visible'
})),
animate('600ms ease-in-out', style({
'max-height': '500px'
})),
animate('800ms ease-in-out', style({
'opacity': '1'
}))
]
)])
]),
]
Then in your app.component, we import the animation and create the method that will toggle the animation state.
app.component.ts
import { SlideInOutAnimation } from './animations';
@Component({
...
animations: [SlideInOutAnimation]
})
export class AppComponent {
animationState = 'in';
...
toggleShowDiv(divName: string) {
if (divName === 'divA') {
console.log(this.animationState);
this.animationState = this.animationState === 'out' ? 'in' : 'out';
console.log(this.animationState);
}
}
}
And here is how your app.component.html would look like :
<div class="wrapper">
<button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
<div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
THIS DIV IS ANIMATED</div>
<div class="content">THIS IS CONTENT DIV</div>
</div>
slideInOut refers to the animation trigger defined in animations.ts
Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/
Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [ ..., BrowserAnimationsModule ],
...
})
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
return Array( quantity ).fill(1).map( n => return n * Math.abs(~~(Math.random() * (1000 - 1 + 1)) + 1) );
One line.
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
In case people are still visiting for a working solution, here is what worked for me:-- This is for Appcompat support library. This is in continuation to ActionBar styling explained here
Following is the styles.xml file.
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- This is the styling for action bar -->
<item name="actionBarStyle">@style/MyActionBar</item>
<!--To change the text styling of options menu items</item>-->
<item name="android:itemTextAppearance">@style/MyActionBar.MenuTextStyle</item>
<!--To change the background of options menu-->
<item name="android:itemBackground">@color/skyBlue</item>
</style>
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="background">@color/red</item>
<item name="titleTextStyle">@style/MyActionBarTitle</item>
</style>
<style name="MyActionBarTitle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/white</item>
</style>
<style name="MyActionBar.MenuTextStyle"
parent="style/TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/red</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">25sp</item>
</style>
</resources>
and this is how it looks--MenuItem background color is skyblue and MenuItem text color is pink with textsize as 25sp:--
The reason your original dataframe does not update is because chained indexing may cause you to modify a copy rather than a view of your dataframe. The docs give this advice:
When setting values in a pandas object, care must be taken to avoid what is called chained indexing.
You have a few alternatives:-
loc
+ Boolean indexingloc
may be used for setting values and supports Boolean masks:
df.loc[df['my_channel'] > 20000, 'my_channel'] = 0
mask
+ Boolean indexingYou can assign to your series:
df['my_channel'] = df['my_channel'].mask(df['my_channel'] > 20000, 0)
Or you can update your series in place:
df['my_channel'].mask(df['my_channel'] > 20000, 0, inplace=True)
np.where
+ Boolean indexingYou can use NumPy by assigning your original series when your condition is not satisfied; however, the first two solutions are cleaner since they explicitly change only specified values.
df['my_channel'] = np.where(df['my_channel'] > 20000, 0, df['my_channel'])
My solution is similar to ATom's one, but easier to implement. You don't need to create a class that shadows FirebaseMessagingService completely, you can just override the method that receives the Intent (which is public, at least in version 9.6.1) and take the information to be displayed from the extras. The "hacky" part is that the method name is indeed obfuscated and is gonna change every time you update the Firebase sdk to a new version, but you can look it up quickly by inspecting FirebaseMessagingService with Android Studio and looking for a public method that takes an Intent as the only parameter. In version 9.6.1 it's called zzm. Here's how my service looks like:
public class MyNotificationService extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage) {
// do nothing
}
@Override
public void zzm(Intent intent) {
Intent launchIntent = new Intent(this, SplashScreenActivity.class);
launchIntent.setAction(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R equest code */, launchIntent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setLargeIcon(rawBitmap)
.setContentTitle(intent.getStringExtra("gcm.notification.title"))
.setContentText(intent.getStringExtra("gcm.notification.body"))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as.
grant SELECT on TABLE_NAME to READ_USERNAME;
Try this, it should work for what you need:
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff f
return true;
}
return false;
}
});
I just found a way that allow you not directly access the status bar height, but calculate it.
Navigation Bar height - topLayoutGuide length = status bar height
Swift:
let statusBarHeight = self.topLayoutGuide.length-self.navigationController?.navigationBar.frame.height
self.topLayoutGuide.length
is the top area that's covered by the translucent bar, and self.navigationController?.navigationBar.frame.height
is the translucent bar excluding status bar, which is usually 44pt. So by using this method you can easily calculate the status bar height without worring about status bar height change due to phone calls.
Doesn't look like you are using the correct overload of ActionLink. Try this:-
<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>
This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-
<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%>
Here is my object inspector that is more readable. Because the code takes to long to write down here you can download it at http://etto-aa-js.googlecode.com/svn/trunk/inspector.js
Use like this :
document.write(inspect(object));
This answer was last revised for Swift 5.2 and iOS 13.4 SDK.
It's all a matter of new syntax and slightly revised APIs. The underlying functionality of UIKit hasn't changed. This is true for a vast majority of iOS SDK frameworks.
let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "myVCID")
self.present(vc, animated: true)
If you're having problems with init(coder:)
, please refer to EridB's answer.
I'd prefer not to use an HTML5 only element such as <section>
. Also grouping the input fields might painful if you try to generate the form with code. It's always better to produce similar markup for each one and only change the class names. Therefore I would recommend a solution that looks like this :
CSS
label, input {
display: block;
}
ul.form {
width : 500px;
padding: 0px;
margin : 0px;
list-style-type: none;
}
ul.form li {
width : 500px;
}
ul.form li input {
width : 200px;
}
ul.form li textarea {
width : 450px;
height: 150px;
}
ul.form li.twoColumnPart {
float : left;
width : 250px;
}
HTML
<form name="message" method="post">
<ul class="form">
<li class="twoColumnPart">
<label for="name">Name</label>
<input id="name" type="text" value="" name="name">
</li>
<li class="twoColumnPart">
<label for="email">Email</label>
<input id="email" type="text" value="" name="email">
</li>
<li>
<label for="subject">Subject</label>
<input id="subject" type="text" value="" name="subject">
</li>
<li>
<label for="message">Message</label>
<textarea id="message" type="text" name="message"></textarea>
</li>
</ul>
</form>
An update with Xcode 11.4 simulator
To capture a screen shot, click on 'Camera' icon/action button, on the top bar of simulator.
OR
Select Save Screen Shot
menu item, from File
menu.
File => Save Screen Shot
Use ? + S to capture a screen shot.
(Use window + s, if you are using windows/non-apple keyboard).
See for more details: How to change simulator scale options with Xcode 9+.
Tip 1: How do you get screen shot with 100% (a scale with actual device size) that can be uploaded on AppStore?
Disable Optimize Rendering for Window scale
from Debug
menu, before you take a screen shot.
Here is an option
Menubar ? Debug ? Disable "Optimize Rendering for Window scale"
Tip 2: Where is screen shot saved (Default Path)? How to change default path?
Simulator saves screen shot file on (logged-in user's) desktop and it's default path.
To change default path (with Xcode 9+), press and hold ? Option (alt) button from keyboard, while you take a screen shot.
Or
Using Mac Keyboad: Press keys ? Option + ? + s all together.
It will show to a dialog with file storage options and also allows to set/change default path.
Tip 3: How to take a screen shot with Device Bezel?
Enable Show Device Bezel
from Window
menu.
Here is an option
Menubar ? Window ? Enable "Show Device Bezel"
Now,
Simulator
window/frame, that you want to capture. It will save screenshot with device bezel (with shadow effect in background) on (logged-in user's) desktop.You can also remove the Simulator toolbar as described here.
You need to make the object first, then use []
to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2018:
If you're able to use ES6 and Babel, you can use this new feature:
{
[yourKeyVariable]: someValueArray,
}
I wish I could comment, but I'll just have to leave this here:
Scotty.NET's answer and user2176745's redo for later versions are both great, but they both miss something that my version of AngularJS (v1.3.15) breaks on:
i is not defined in $scope.makeTodos.
As such, replacing with this function fixes it for more recent angular versions.
$scope.makeTodos = function() {
var i;
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:'todo '+i, done:false});
}
};
You can always use the DATALENGTH Function to determine if you have extra white space characters in text fields. This won't make the text visible but will show you where there are extra white space characters.
SELECT DATALENGTH('MyTextData ') AS BinaryLength, LEN('MyTextData ') AS TextLength
This will produce 11 for BinaryLength and 10 for TextLength.
In a table your SQL would like this:
SELECT *
FROM tblA
WHERE DATALENGTH(MyTextField) > LEN(MyTextField)
This function is usable in all versions of SQL Server beginning with 2005.
For column types Rails supports out of the box - like the string in this question - the best approach is to set the column default in the database itself as Daniel Kristensen indicates. Rails will introspect on the DB and initialize the object accordingly. Plus, that makes your DB safe from somebody adding a row outside of your Rails app and forgetting to initialize that column.
For column types Rails doesn't support out of the box - e.g. ENUM columns - Rails won't be able to introspect the column default. For these cases you do not want to use after_initialize (it is called every time an object is loaded from the DB as well as every time an object is created using .new), before_create (because it occurs after validation), or before_save (because it occurs upon update too, which is usually not what you want).
Rather, you want to set the attribute in a before_validation on: create, like so:
before_validation :set_status_because_rails_cannot, on: :create
def set_status_because_rails_cannot
self.status ||= 'P'
end
In my case it was the missing .pub
extension of a key. I pasted it from clipboard and saved as mykey
. The following command returned described error:
ssh-copy-id -i mykey localhost
After renaming it with mv mykey mykey.pub
, works correctly.
ssh-copy-id -i mykey.pub localhost
I faced the same error and did some research to only see that there could be different scenarios to this error. Let me share my findings.
Scenario 1: There cannot be spaces beside the =
(equals) sign
$ export TEMP_ENV = example-value
-bash: export: `=': not a valid identifier
// this is the answer to the question
$ export TEMP_ENV =example-value
-bash: export: `=example-value': not a valid identifier
$ export TEMP_ENV= example-value
-bash: export: `example-value': not a valid identifier
Scenario 2: Object value assignment should not have spaces besides quotes
$ export TEMP_ENV={ "key" : "json example" }
-bash: export: `:': not a valid identifier
-bash: export: `json example': not a valid identifier
-bash: export: `}': not a valid identifier
Scenario 3: List value assignment should not have spaces between values
$ export TEMP_ENV=[1,2 ,3 ]
-bash: export: `,3': not a valid identifier
-bash: export: `]': not a valid identifier
I'm sharing these, because I was stuck for a couple of hours trying to figure out a workaround. Hopefully, it will help someone in need.
In swift :
#if (arch(i386) || arch(x86_64))
...
#endif
From Detect if app is being built for device or simulator in Swift
PEP 3101 proposes the replacement of the %
operator with the new, advanced string formatting in Python 3, where it would be the default.
This is how I got rid of it:
First of all, try toObject()
instead of toJSON()
maybe?
Secondly, you'll need to call it on the actual documents and not the array, so maybe try something more annoying like this:
var flatUsers = users.map(function() {
return user.toObject();
})
return res.end(JSON.stringify(flatUsers));
It's a guess, but I hope it helps
You can specify the number as keyboardType for the TextField using:
keyboardType: TextInputType.number
Check my main.dart file
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return new MaterialApp(
home: new HomePage(),
theme: new ThemeData(primarySwatch: Colors.blue),
);
}
}
class HomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new HomePageState();
}
}
class HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.white,
body: new Container(
padding: const EdgeInsets.all(40.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new TextField(
decoration: new InputDecoration(labelText: "Enter your number"),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
),
],
)),
);
}
}
Sometime we might don't want to apply ordering on our result set to add serial number. But if we are going to use ROW_NUMBER()
then we have to have a ORDER BY
clause. So, for that we can simply apply a tricks to avoid any ordering on the result set.
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS ItemNo, ItemName FROM ItemMastetr
For that we don't need to apply order by on our result set. We'll just add ItemNo
on our given result set.
'JavaType' works !!
I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution.
Code:
JsonMarshallerUnmarshaller<T> {
T targetClass;
public ArrayList<T> unmarshal(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper.getDeserializationConfig()
.withAnnotationIntrospector(introspector);
mapper.getSerializationConfig()
.withAnnotationIntrospector(introspector);
JavaType type = mapper.getTypeFactory().
constructCollectionType(
ArrayList.class,
targetclass.getClass());
try {
Class c1 = this.targetclass.getClass();
Class c2 = this.targetclass1.getClass();
ArrayList<T> temp = (ArrayList<T>)
mapper.readValue(jsonString, type);
return temp ;
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
}
Create .jshintrc
file in the root dir and add there the latest js version: "esversion": 9
and asi version: "asi": true
(it will help you to avoid using semicolons)
{
"esversion": 9,
"asi": true
}
I modified my response to include the code for a test app I did.
Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).
First the javascript:
function test()
{
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };
$.ajax({
type: "POST",
url: "/Home/SaveList",
data: postData,
success: function(data){
alert(data.Result);
},
dataType: "json",
traditional: true
});
}
And here's the code in my controller class:
public JsonResult SaveList(List<String> values)
{
return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}
When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!
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.
You can use the Positioned.fill
with Align
inside a Stack
:
Stack(
children: <Widget>[
Positioned.fill(
child: Align(
alignment: Alignment.centerRight,
child: ....
),
),
],
),
You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.
You could use a generator expression with a default value and then next
it:
next((x for x in seq if predicate(x)), None)
Although for this one-liner you need to be using Python >= 2.6.
This rather popular article further discusses this issue: Cleanest Python find-in-list function?.
If you want to use the call operator, the arguments can be an array stored in a variable:
$prog = 'c:\windows\system32\cmd.exe'
$myargs = '/c','dir','/x'
& $prog $myargs
The call operator works with ApplicationInfo objects too.
$prog = get-command cmd
$myargs = -split '/c dir /x'
& $prog $myargs
You can use the IF
statement in a new cell to replace text, such as:
=IF(A4="C", "Other", A4)
This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.
EDIT
Assuming that the Employee_Count
values are in B1-B10, you can use this:
=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)
This function doesn't even require the data to be sorted; the LARGE
function will find the 10th largest number in the series, and then the rest of the formula will compare against that.
We can use data.table to get it quickly. First create df without factors,
df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)), stringsAsFactors=F)
Now you can use
setDT(df)
for (jj in 1:ncol(df)) set(df, i = which(df[[jj]]==""), j = jj, v = NA)
and you can convert it back to a data.frame
setDF(df)
If you only want to use data.frame and keep factors it's more difficult, you need to work with
levels(df$value)[levels(df$value)==""] <- NA
where value is the name of every column. You need to insert it in a loop.
In my case, I was running into this problem with a 1st gen Asus Nexus 7. I had increased the logging buffer size from 256K to 4M. As soon as I restored it to the default value (Settings>Developer Settings>Logger buffer sizes), unplugged and plugged the tablet back in, it worked perfectly.
See Tejas Lagvankar's post about this subject. Below are some key differences between Service and IntentService and other components.
In the debugger you don't need to add back slashes, the input field understands the special chars.
In java code you need to escape the special chars
I was facing the same issue and the reason was single backslah. I used double backslash in my "Data source" and it worked
connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";
Avoid using C-Style casts.
C-style casts are a mix of const and reinterpret cast, and it's difficult to find-and-replace in your code. A C++ application programmer should avoid C-style cast.
For anyone else ever looking for an IIS WCF error 413 : Request entity to large and using a WCF service in Sharepoint, this is the information for you. The settings in the application host and web.config suggested in other sites/posts don't work in SharePoint if using the MultipleBaseAddressBasicHttpBindingServiceHostFactory. You can use SP Powershell to get the SPWebService.Content service, create a new SPWcvSettings object and update the settings as above for your service (they won't exist). Remember to just use the name of the service (e.g. [yourservice.svc]) when creating and adding the settings. See this site for more info https://robertsep.wordpress.com/2010/12/21/set-maximum-upload-filesize-sharepoint-wcf-service
To get JSON posted without the application/json
content type, use request.get_json(force=True)
.
@app.route('/process_data', methods=['POST'])
def process_data():
req_data = request.get_json(force=True)
language = req_data['language']
return 'The language value is: {}'.format(language)
The best that worked for me:
<receiver android:name="com.AEDesign.communication.WifiReceiver" >
<intent-filter android:priority="100">
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(info != null && info.isConnected()) {
// Do your work.
// e.g. To check the Network Name or other info:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
}
}
}
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Explained by Red Hat:
Cache Pages:
A cache is the part of the memory which transparently stores data so that future requests for that data can be served faster. This memory is utilized by the kernel to cache disk data and improve i/o performance.
The Linux kernel is built in such a way that it will use as much RAM as it can to cache information from your local and remote filesystems and disks. As the time passes over various reads and writes are performed on the system, kernel tries to keep data stored in the memory for the various processes which are running on the system or the data that of relevant processes which would be used in the near future. The cache is not reclaimed at the time when process get stop/exit, however when the other processes requires more memory then the free available memory, kernel will run heuristics to reclaim the memory by storing the cache data and allocating that memory to new process.
When any kind of file/data is requested then the kernel will look for a copy of the part of the file the user is acting on, and, if no such copy exists, it will allocate one new page of cache memory and fill it with the appropriate contents read out from the disk.
The data that is stored within a cache might be values that have been computed earlier or duplicates of original values that are stored elsewhere in the disk. When some data is requested, the cache is first checked to see whether it contains that data. The data can be retrieved more quickly from the cache than from its source origin.
SysV shared memory segments are also accounted as a cache, though they do not represent any data on the disks. One can check the size of the shared memory segments using ipcs -m command and checking the bytes column.
Buffers:
Buffers are the disk block representation of the data that is stored under the page caches. Buffers contains the metadata of the files/data which resides under the page cache. Example: When there is a request of any data which is present in the page cache, first the kernel checks the data in the buffers which contain the metadata which points to the actual files/data contained in the page caches. Once from the metadata the actual block address of the file is known, it is picked up by the kernel for processing.
I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.
public void Foo(int a, int b, int? c)
{
if(c.HasValue)
{
// do something with a,b and c
}
else
{
// do something with a and b only
}
}
Spring cron expression for every day 1:01:am
@Scheduled(cron = "0 1 1 ? * *")
for more information check this information:
https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm
git gc --aggressive
is one way to force the prune process to take place (to be sure: git gc --aggressive --prune=now
). You have other commands to clean the repo too. Don't forget though, sometimes git gc
alone can increase the size of the repo!
It can be also used after a filter-branch
, to mark some directories to be removed from the history (with a further gain of space); see here. But that means nobody is pulling from your public repo. filter-branch
can keep backup refs in .git/refs/original
, so that directory can be cleaned too.
Finally, as mentioned in this comment and this question; cleaning the reflog can help:
git reflog expire --all --expire=now
git gc --prune=now --aggressive
An even more complete, and possibly dangerous, solution is to remove unused objects from a git repository
Update Feb. 2021, eleven years later: the new git maintenance
command (man page) should supersede git gc
, and can be scheduled.
Based on the previous answers, and cobbled together from various places in stack overflow, here is the solution I came up with which handles the case when you actually want to submit your changes:
window.thisPage = window.thisPage || {};
window.thisPage.isDirty = false;
window.thisPage.closeEditorWarning = function (event) {
if (window.thisPage.isDirty)
return 'It looks like you have been editing something' +
' - if you leave before saving, then your changes will be lost.'
else
return undefined;
};
$("form").on('keyup', 'textarea', // You can use input[type=text] here as well.
function () {
window.thisPage.isDirty = true;
});
$("form").submit(function () {
QC.thisPage.isDirty = false;
});
window.onbeforeunload = window.thisPage.closeEditorWarning;
It's worth noting that IE11 seems to require that the closeEditorWarning
function returns undefined
for it not to show an alert.
To validate all dynamically generated elements could add a special class to each of these elements and use each() function, something like
$("#DivIdContainer .classToValidate").each(function () {
$(this).rules('add', {
required: true
});
});
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
use hibernate annotation
@ColumnDefault("-1")
private Long clientId;
You can also use array_column()
. It's available from PHP 5.5: php.net/manual/en/function.array-column.php
It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.
print_r(array_column($myarray, 'email'));
Shameless plug: I'm working on Bokeh: a simple, scalable and blazing-fast task queue built on ZeroMQ. It supports pluggable data stores for persisting tasks, currently in-memory, Redis and Riak are supported. Check it out.
Download Wget from here http://downloads.sourceforge.net/gnuwin32/wget-1.11.4-1-setup.exe
Then install it.
Then make some .bat file and put this into it
@echo off
for /F "tokens=2,3,4 delims=/ " %%i in ('date/t') do set y=%%k
for /F "tokens=2,3,4 delims=/ " %%i in ('date/t') do set d=%%k%%i%%j
for /F "tokens=5-8 delims=:. " %%i in ('echo.^| time ^| find "current" ') do set t=%%i%%j
set t=%t%_
if "%t:~3,1%"=="_" set t=0%t%
set t=%t:~0,4%
set "theFilename=%d%%t%"
echo %theFilename%
cd "C:\Program Files\GnuWin32\bin"
wget.exe --output-document C:\backup\file_%theFilename%.zip http://someurl/file.zip
Adjust the URL and the file path in the script
You can create a class based on a Button with specific images for MouseHover and MouseDown like this:
public class AdvancedImageButton : Button {
public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }
protected override void OnMouseEnter(System.EventArgs e)
{
base.OnMouseEnter(e);
if (HoverImage == null) return;
if (PlainImage == null) PlainImage = base.Image;
base.Image = HoverImage;
}
protected override void OnMouseLeave(System.EventArgs e)
{
base.OnMouseLeave(e);
if (HoverImage == null) return;
base.Image = PlainImage;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (PressedImage == null) return;
if (PlainImage == null) PlainImage = base.Image;
base.Image = PressedImage;
}
}
This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.
It changes the rules for override priority of css cascades. See the CSS2 spec.
Go to the project "Properties" => "Web", and on the "Servers" section change the port to something else that is not used in and save it. You will be asked to created a virtual directory and click "Yes". Now run the project and it will work now.
You can input the following command on Linux:
find ./ -name "*." | xargs svn add
In UNIX I had this problem, I edited catalina.sh
manually and entered
export JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.24
echo "Using JAVA_HOME: $JAVA_HOME"
as the first 2 lines. I tried setting the JAVA_HOME
in /etc/profile
but it did not help.
This worked finally.
Keep in mind, I'm completely biased (PMC Chair of CXF), but my thoughts:
From a strictly "can the project do what I need it to do" perspective, both are pretty equivalent. There some "edge case" things that CXF can do that Axis 2 cannot and vice versa. But for 90% of the use cases, either will work fine.
Thus, it comes down to a bunch of other things other than "check box features".
API - CXF pushes "standards based" API's (JAX-WS compliant) whereas Axis2 general goes toward proprietary things. That said, even CXF may require uses of proprietary API's to configure/control various things outside the JAX-WS spec. For REST, CXF also uses standard API's (JAX-RS compliant) instead of proprietary things. (Yes, I'm aware of the JAX-WS runtime in Axis2, but the tooling and docs and everything doesn't target it)
Community aspects and supportability - CXF prides itself on responding to issues and making "fixpacks" available to users. CXF did 12 fixpacks for 2.0.x (released two years ago, so about every 2 months), 6 fixpacks to 2.1.x, and now 3 for 2.2.x. Axis2 doesn't really "support" older versions. Unless a "critical" issue is hit, you may need to wait till the next big release (they average about every 9-10 months or so) to get fixes. (although, with either, you can grab the source code and patch/fix yourself. Gotta love open source.)
Integration - CXF has much better Spring integration if you use Spring. All the configuration and such is done through Spring. Also, people tend to consider CXF as more "embeddable" (I've never looked at Axis2 from this perspective) into other applications. Not sure if things like that matter to you.
Performance - they both perform very well. I think Axis2's proprietary ADB databinding is a bit faster than CXF, but if you use JAXB (standards based API's again), CXF is a bit faster. When using more complex scenarios like WS-Security, the underlying security "engine" (WSS4J) is the same for both so the performance is completely comparable.
Not sure if that answers the question at all. Hope it at least provides some information.
:-)
Dan
This is known as a Shebang
:
http://en.wikipedia.org/wiki/Shebang_(Unix)
#!interpreter [optional-arg]
A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).
When a shell executes the script it will use the specified interpreter.
Example:
#!/bin/bash
# file: foo.sh
echo 1
$ chmod u+x foo.sh
$ ./foo.sh
1
I had the same problem. My .sql file was 830 MB and the phpMyAdmin import size allowed was 50MB (just as shown in the screenshot). When I zipped the file to .zip its size became about 80 MB. Then I zipped it to bzip2 format, and I was amazed to see that the file size was compressed to just 12MB (from 830MB to 12MB!!!). As phpMyAdmin allows three compression types i.e. .zip , .gzip and .bzip2 , therefore I uploaded the compressed bzip2 file and viola.... it was imported to the database!!! So by using the right compression, I was able to import a 830MB .sql file into phpMyAdmin.
NOTE: phpMyAdmin import page clearly instructs that the compressed filename should be like filename.sql.bz2 . It should not be like filename.bz2 .
NOTE 2: You can compress your .sql file to bzip2 compressed file using 7-Zip software. cPanel also has an option to compress a file to bzip2 format.
I would go through the packet capture and see if there are any records that I know I should be seeing to validate that the filter is working properly and to assuage any doubts.
That said, please try the following filter and see if you're getting the entries that you think you should be getting:
dns and ip.dst==159.25.78.7 or dns and ip.src==159.57.78.7
As far as I understand, you want to prepend column1, column2, column3
to your existing one, two, three
.
I would use ed
in place of sed
, since sed
write on the standard output and not in the file.
The command:
printf '0a\ncolumn1, column2, column3\n.\nw\n' | ed testfile.csv
should do the work.
perl -i
is worth taking a look as well.
I was working with 3 files: The python script, the image, and the trained model.
Everything worked when I moved these 3 files into their own folder instead of in the directory with the other python scripts.
When you call for i in a:
, you are getting the actual elements, not the indexes. When we reach the last element, that is 3
, b.append(a[i+1]-a[i])
looks for a[4]
, doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like
for i in range(0, len(a)-1): Do something
Your current code won't work yet for the do something part though ;)
Having is only used with aggregation but where with non aggregation statements If you have where word put it before aggregation (group by)
This:
string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);
\x20 is ascii hex for 'space' character
you can add more individual characters that you want to be allowed. If you want for example "?" to be ok in the return string add \x3f.
I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ?+x:, you can detect the x key AND check if event.metaKey is set to true. For example:
var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);
When pressing x on it's own, this will output 120, false
. When pressing ?+x, it will output 120, true
This only seems to work in Safari - not Chrome
If you want to check if some string is present in another string, use something like String.contains
If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.
Example: Suppose you have some regex a(b|c) that checks if a string matches ab
or ac
.*(a(b|c)).*
will check if a string contains a ab
or ac
.
A disadvantage of this method is that it will not give you the location of the match.
You need to either provide a body for both the getter and setter, or neither. Since you have non-trivial logic in your setter, you need a manually-implemented getter like so:
get { return _hour; }
If you decide you don't need the logic in the setter, you could go with an automatically-implemented property like so:
public int Hour { get; set; }
The MAC address of a client (in the sense of the computer that issued the HTTP request) is overwritten by every router between the client and the server.
Client IP is conveniently provided to the script in $_SERVER['REMOTE_ADDR']
. In some scenarios, particularly if your web server is behind a proxy (i.e. a caching proxy) $_SERVER['REMOTE ADDR']
will return the IP of the proxy, and there will be an extra value, often $_SERVER['HTTP_X_FORWARDED_FOR']
, that contains the IP of the original request client.
Sometimes, particularly when you're dealing with an anonymizing proxy that you don't control, the proxy won't return the real IP address, and all you can hope for is the IP address of the proxy.
I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).
private static void playSound(String sound){
// cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
URL file = cl.getResource(sound);
final Media media = new Media(file.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :
static{
JFXPanel fxPanel = new JFXPanel();
}
Lodash isEqual()
method is the best way to compare two JSON object.
This will not consider the order of the keys in object and check for the equality of object. Example
const object1={
name:'ABC',
address:'India'
}
const object2={
address:'India',
name:'ABC'
}
JSON.stringify(object1)===JSON.stringify(object2)
// false
_.isEqual(object1, object2)
//true
Reference-https://lodash.com/docs/#isEqual
If sequence is not going to change than JSON.stringify()
will be fast as compared to Lodash isEqual()
method
Reference-https://www.measurethat.net/Benchmarks/Show/1854/0/lodash-isequal-test
Form1:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
Form2:
public partial class Form2 : Form
{
Form opener;
public Form2(Form parentForm)
{
InitializeComponent();
opener = parentForm;
}
private void button1_Click(object sender, EventArgs e)
{
opener.Close();
this.Close();
}
}
It looks like you are trying to start the Python interpreter by running the command python
.
However the interpreter is already started. It is interpreting python
as a name of a variable, and that name is not defined.
Try this instead and you should hopefully see that your Python installation is working as expected:
print("Hello world!")
There are a few efficient ways to implement this. Let's start with required imports:
from pyspark.sql.functions import col, expr, when
You can use Hive IF
function inside expr:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)
or when
+ otherwise
:
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
Finally you could use following trick:
from pyspark.sql.functions import coalesce, lit
new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
With example data:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])
you can use this as follows:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))
and the result is:
+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+
One approach would be to take a defaults object and merge it with the target object. The target object would override values in the defaults object.
jQuery has the .extend()
method that does this. jQuery is not needed however as there are vanilla JS implementations such as can be found here:
http://gomakethings.com/vanilla-javascript-version-of-jquery-extend/
Simply download node from the official website, this worked for me! :)
You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item
{
public string name { get; set; }
public string index { get; set; }
public string optional { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Usage:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex json
s
In jaxws-rt-2.2.10-ources.jar!\com\sun\xml\ws\transport\http\client\HttpTransportPipe.java
:
public Packet process(Packet request) {
Map<String, List<String>> userHeaders = (Map<String, List<String>>) request.invocationProperties.get(MessageContext.HTTP_REQUEST_HEADERS);
if (userHeaders != null) {
reqHeaders.putAll(userHeaders);
So, Map<String, List<String>>
from requestContext with key MessageContext.HTTP_REQUEST_HEADERS
will be copied to SOAP headers.
Sample of Application Authentication with JAX-WS via headers
BindingProvider.USERNAME_PROPERTY
and BindingProvider.PASSWORD_PROPERTY
keys are processed special way in HttpTransportPipe.addBasicAuth()
, adding standard basic authorization Authorization
header.
See also Message Context in JAX-WS
For each element inside document body
modify their text using .text(fn) function.
$("body *").text(function() {
return $(this).text().replace("x", "xy");
});
Predicate
has methods and
, or
and negate
.
However, String::isEmpty
is not a Predicate
, it's just a String -> Boolean
lambda and it could still become anything, e.g. Function<String, Boolean>
. Type inference is what needs to happen first. The filter
method infers type implicitly. But if you negate it before passing it as an argument, it no longer happens. As @axtavt mentioned, explicit inference can be used as an ugly way:
s.filter(((Predicate<String>) String::isEmpty).negate()).count()
There are other ways advised in other answers, with static not
method and lambda most likely being the best ideas. This concludes the tl;dr section.
However, if you want some deeper understanding of lambda type inference, I'd like to explain it a bit more to depth, using examples. Look at these and try to figure out what happens:
Object obj1 = String::isEmpty;
Predicate<String> p1 = s -> s.isEmpty();
Function<String, Boolean> f1 = String::isEmpty;
Object obj2 = p1;
Function<String, Boolean> f2 = (Function<String, Boolean>) obj2;
Function<String, Boolean> f3 = p1::test;
Predicate<Integer> p2 = s -> s.isEmpty();
Predicate<Integer> p3 = String::isEmpty;
Predicate
to Object
- silly but validPredicate
to Function
, it's no longer about inferencetest
that is defined by its lambdaInteger
doesn't have isEmpty
methodString::isEmpty
static method with Integer
argumentI hope this helps get some more insight into how type inferrence works.
you can solve this, taking the input
tag inside a div
,
then put the padding property on div
tag. This work's for me...
Like this:
<div class="paded">
<input type="text" />
</div>
and css:
.paded{
padding-right: 20px;
}
I encountered the same error today although I was using Jersey 1.x, and had the right jars in my classpath. For those who'd like to follow the vogella tutorial to the letter, and use the 1.x jars, you'd need to add the jersey libraries to WEB-INF/lib folder. This will certainly resolve the problem.
The value is null, you have to check why... (in addition to the implementation of the solutions proposed here)
Check the hardware Connections.
Generically, do
/while
is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while
or even a for
loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:
do {
char c = read_input();
process_input(c);
} while (c != 'Q');
Here is the script i used and it works like a charm. I used the boolean method Ender suggested as the other ones using only the IE specific script adds something to IE but doesn´t take the original code out.
<script>runFancy = true;</script>
<!--[if IE]>
<script type="text/javascript">
runFancy = false;
</script> // <div>The HTML version for IE went here</div>
<![endif]-->
// Below is the script used for all other browsers:
<script src="accmenu/acac1.js" charset="utf-8" type="text/javascript"></script><script>ac1init_doc('',0)</script>
Make sure you fill in your domain name and it must not end with a path.
example
http://yourdomain.com (good)
http://yourdomain.com/folder (error)
I'm not sure how you think you can do it other than character-by-character -- it's inherently a character-by-character operation. There is certainly code out there to do this for you, but there is no "simpler" way than doing it character-by-character.
First, you need to strip the 0b
prefix, and left-zero-pad the string so it's length is divisible by 8, to make dividing the bitstring up into characters easy:
bitstring = bitstring[2:]
bitstring = -len(bitstring) % 8 * '0' + bitstring
Then you divide the string up into blocks of eight binary digits, convert them to ASCII characters, and join them back into a string:
string_blocks = (bitstring[i:i+8] for i in range(0, len(bitstring), 8))
string = ''.join(chr(int(char, 2)) for char in string_blocks)
If you actually want to treat it as a number, you still have to account for the fact that the leftmost character will be at most seven digits long if you want to go left-to-right instead of right-to-left.
Where I work we have 2 Sprints to an Iteration. The Iteration demo is before the business stakeholders that don't want to meet after every Sprint, but that is our interpretation of the terminology. Some places may have the terms having equally meaning, I'm just pointing out that where I work they aren't the same thing.
No, sprints can have varying lengths. Where I work we had a half a Sprint to align our Sprints with the Iterations that others in the project from another department were using.
The split method of a string is what you need. In fact the tokenizer class in Java is deprecated in favor of Java's string split method.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
I feel you should be using the Consumer interface instead of Function<T, R>
.
A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)
In your case, you can create a consumer elsewhere in your code like this:
Consumer<Integer> myFunction = x -> {
System.out.println("processing value: " + x);
.... do some more things with "x" which returns nothing...
}
Then you can replace your myForEach
code with below snippet:
public static void myForEach(List<Integer> list, Consumer<Integer> myFunction)
{
list.forEach(x->myFunction.accept(x));
}
You treat myFunction as a first-class object.
This will give you the full name of the month.
select datename(month, S0.OrderDateTime)
If you only want the first three letters you can use this
select convert(char(3), S0.OrderDateTime, 0)
The rep.row function seems to sometimes make lists for columns, which leads to bad memory hijinks. I have written the following which seems to work well:
library(plyr)
rep.row <- function(r, n){
colwise(function(x) rep(x, n))(r)
}
ifstream inFile;
string name, temp;
int age;
inFile.open("file.txt");
getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
RegisteredClientScriptBlock
adds the script at the top of the page on the post-back with no assurance about the order, meaning that either the call is being injected after the function declaration (your js file with the function is inlined after your call) or when the script tries to execute the div is probably not there yet 'cause the page is still rendering. A good idea is probably to simulate the two scenarios I described above on firebug and see if you get similar errors.
My guess is this would work if you append the script at the bottom of the page with RegisterStartupScript
- worth a shot at least.
Anyway, as an alternative solution if you add the runat="server"
attribute to the div you will be able to access it by its id in the codebehind (without reverting to js - how cool that might be), and make it disappear like this:
data.visible = false
All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!
ContextCompat.getDrawable(mContext, drawable)
From documented method
public static final android.graphics.drawable.Drawable getDrawable(@NotNull android.content.Context context,
@android.support.annotation.DrawableRes int id
This is how I come up with the IP
func ReadUserIP(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
return IPAddress
}
X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)
X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For
You could use the @Consumes annotation to get the full body:
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
@Path("doc")
public class BodyResource
{
@POST
@Consumes(MediaType.APPLICATION_XML)
public void post(Document doc) throws TransformerConfigurationException, TransformerException
{
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.transform(new DOMSource(doc), new StreamResult(System.out));
}
}
Note: Don't forget the "Content-Type: application/xml" header by the request.
Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:
BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)
You could also do something as follow
public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
or
EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).
For the validation, I had to use Apache's EnumUtils
library since the type of enum is not known at compile time.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
Set<String> notAllowedNames = enumNames.stream()
.filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
.collect(Collectors.toSet());
if (notAllowedNames.size() > 0) {
String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
.collect(Collectors.joining(", "));
throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
.collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
+ "of the following : " + validEnumNames);
}
}
I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551
It depends on the property type that you are parsing.
If the json property is a number (e.g. 5) you can cast to Long directly, so you could do:
(long) jsonObj.get("id") // with id = 5, cast `5` to long
After getting the long,you could cast again to int, resulting in:
(int) (long) jsonObj.get("id")
If the json property is a number with quotes (e.g. "5"), is is considered a string, and you need to do something similar to Integer.parseInt() or Long.parseLong();
Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long
The only issue is, if you sometimes receive id's a string or as a number (you cant predict your client's format or it does it interchangeably), you might get an exception, especially if you use parseInt/Long on a null json object.
If not using Java Generics, the best way to deal with these runtime exceptions that I use is:
if(jsonObj.get("id") == null) {
// do something here
}
int id;
try{
id = Integer.parseInt(jsonObj.get("id").toString());
} catch(NumberFormatException e) {
// handle here
}
You could also remove that first if and add the exception to the catch. Hope this helps.
Regardless of what your object is and for what table in the database the only thing you need to have is the primary key in the object.
var dbValue = EntityObject.Entry(obj).GetDatabaseValues();
if (dbValue == null)
{
Don't exist
}
Dim dbValue = EntityObject.Entry(obj).GetDatabaseValues()
If dbValue Is Nothing Then
Don't exist
End If
First, some similarities that have not been mentioned yet. Ruby supports open classes, but modules as open too. After all, Class inherits from Module in the Class inheritance chain and so Class and Module do have some similar behavior.
But you need to ask yourself what is the purpose of having both a Class and a Module in a programming language? A class is intended to be a blueprint for creating instances, and each instance is a realized variation of the blueprint. An instance is just a realized variation of a blueprint (the Class). Naturally then, Classes function as object creation. Furthermore, since we sometimes want one blueprint to derive from another blueprint, Classes are designed to support inheritance.
Modules cannot be instantiated, do not create objects, and do not support inheritance. So remember one module does NOT inherit from another!
So then what is the point of having Modules in a language? One obvious usage of Modules is to create a namespace, and you will notice this with other languages too. Again, what's cool about Ruby is that Modules can be reopened (just as Classes). And this is a big usage when you want to reuse a namespace in different Ruby files:
module Apple
def a
puts 'a'
end
end
module Apple
def b
puts 'b'
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c527c98>
> f.a
=> a
> f.b
=> b
But there is no inheritance between modules:
module Apple
module Green
def green
puts 'green'
end
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c462420>
> f.green
NoMethodError: undefined method `green' for #<Fruit:0x007fe90c462420>
The Apple module did not inherit any methods from the Green module and when we included Apple in the Fruit class, the methods of the Apple module are added to the ancestor chain of Apple instances, but not methods of the Green module, even though the Green module was defined in the Apple module.
So how do we gain access to the green method? You have to explicitly include it in your class:
class Fruit
include Apple::Green
end
=> Fruit
> f.green
=> green
But Ruby has another important usage for Modules. This is the Mixin facility, which I describe in another answer on SO. But to summarize, mixins allow you to define methods into the inheritance chain of objects. Through mixins, you can add methods to the inheritance chain of object instances (include) or the singleton_class of self (extend).
Lets say your HTML looks something like this:
<div class="box">
<!-- stuff -->
<p class="bet_time">Bet 5 days ago</p>
</div>
Then, with CSS, you can make that text appear in the bottom right like so:
.box {
position:relative;
}
.bet_time {
position:absolute;
bottom:0;
right:0;
}
The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time
positions its right edge to the right edge of .box
and its bottom edge to the bottom edge of .box
You can use expect in your bash script.
From http://www.seanodonnell.com/code/?id=21
#!/usr/bin/expect
#########################################
#$ file: htpasswd.sh
#$ desc: Automated htpasswd shell script
#########################################
#$
#$ usage example:
#$
#$ ./htpasswd.sh passwdpath username userpass
#$
######################################
set htpasswdpath [lindex $argv 0]
set username [lindex $argv 1]
set userpass [lindex $argv 2]
# spawn the htpasswd command process
spawn htpasswd $htpasswdpath $username
# Automate the 'New password' Procedure
expect "New password:"
send "$userpass\r"
expect "Re-type new password:"
send "$userpass\r"
As the others said, you can't. You can find good examples of HTML-php forms on the web, here's a very useful link that combines HTML with javascript for validation and php for sending the email.
Please check the full article (includes zip example) in the source: http://www.html-form-guide.com/contact-form/php-email-contact-form.html
HTML:
<form method="post" name="contact_form"
action="contact-form-handler.php">
Your Name:
<input type="text" name="name">
Email Address:
<input type="text" name="email">
Message:
<textarea name="message"></textarea>
<input type="submit" value="Submit">
</form>
JS:
<script language="JavaScript">
var frmvalidator = new Validator("contactform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email",
"Please enter a valid email address");
</script>
PHP:
<?php
$errors = '';
$myemail = '[email protected]';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
In Swift 2.2 - 5 you can now do:
if object is String
{
}
Then to filter your array:
let filteredArray = originalArray.filter({ $0 is Array })
If you have multiple types to check:
switch object
{
case is String:
...
case is OtherClass:
...
default:
...
}
See debug_print_backtrace
. I guess you can call flush
afterwards if you want.
They are both accepted in T-SQL. However, it seems that using <>
works a lot faster than !=
. I just ran a complex query that was using !=
, and it took about 16 seconds on average to run. I changed those to <>
and the query now takes about 4 seconds on average to run. That's a huge improvement!
Example:
defaults.yaml
url: https://www.google.com
environment.py
from ruamel import yaml
data = yaml.safe_load(open('defaults.yaml'))
data['url']
Below is a minimal code to achieve the effect.
This also works responsively since the border-radius
is in percentage.
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
I agree with what @fge said, more over. Lets look at example. Consider you have a method:
class A {
public void foo(OtherClass other) {
SomeData data = new SomeData("Some inner data");
other.doSomething(data);
}
}
Now if you want to check the inner data you can use the captor:
// Create a mock of the OtherClass
OtherClass other = mock(OtherClass.class);
// Run the foo method with the mock
new A().foo(other);
// Capture the argument of the doSomething function
ArgumentCaptor<SomeData> captor = ArgumentCaptor.forClass(SomeData.class);
verify(other, times(1)).doSomething(captor.capture());
// Assert the argument
SomeData actual = captor.getValue();
assertEquals("Some inner data", actual.innerData);
This Stack Overflow quesion is the current top Google result for "random string Python". The current top answer is:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
This is an excellent method, but the PRNG in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
Using random.SystemRandom()
instead of just random uses /dev/urandom on *nix machines and CryptGenRandom()
in Windows. These are cryptographically secure PRNGs. Using random.choice
instead of random.SystemRandom().choice
in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.
If you're using python3.6 or above, you can use the new secrets module as mentioned in MSeifert's answer:
''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
The module docs also discuss convenient ways to generate secure tokens and best practices.
You can also use select(2) if you want microsecond precision (this works on platform that don't have usleep(3))
The following code will wait for 1.5 second:
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>`
int main() {
struct timeval t;
t.tv_sec = 1;
t.tv_usec = 500000;
select(0, NULL, NULL, NULL, &t);
}
`
The $GLOBALS
array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
On modern x86_64 CPUs you can use the hardware random number generator via _rdrand64_step()
Example code:
#include <immintrin.h>
uint64_t randVal;
if(!_rdrand64_step(&randVal)) {
// Report an error here: random number generation has failed!
}
// If no error occured, randVal contains a random 64-bit number
The offset under Windows 10 is 0x022C (x64-bit-Application) and 0x0160 (x32-bit-Application):
public static int GetNativeThreadId(Thread thread)
{
var f = typeof(Thread).GetField("DONT_USE_InternalThread",
BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
var pInternalThread = (IntPtr)f.GetValue(thread);
var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 0x022C : 0x0160); // found by analyzing the memory
return nativeId;
}
I think you're looking for the UNION clause, a la
(SELECT * from us_music where `genre` = 'punk')
UNION
(SELECT * from de_music where `genre` = 'punk')
I believe that I have the simplest answer. You don't need the string.h library in this program, nor the stdbool.h library. Simply using pointers and pointer arithmetic will help you become a better C programmer.
Simply return 0 for False (no substring found), or 1 for True (yes, a substring "sub" is found within the overall string "str"):
#include <stdlib.h>
int is_substr(char *str, char *sub)
{
int num_matches = 0;
int sub_size = 0;
// If there are as many matches as there are characters in sub, then a substring exists.
while (*sub != '\0') {
sub_size++;
sub++;
}
sub = sub - sub_size; // Reset pointer to original place.
while (*str != '\0') {
while (*sub == *str && *sub != '\0') {
num_matches++;
sub++;
str++;
}
if (num_matches == sub_size) {
return 1;
}
num_matches = 0; // Reset counter to 0 whenever a difference is found.
str++;
}
return 0;
}
Maybe late to the party but in my case it was RHEL 6.8:
Copy certificate.crt
issued by hosting to:
/etc/pki/ca-trust/source/anchors/
Then:
update-ca-trust force-enable (ignore not found warnings)
update-ca-trust extract
Hope it helps
Because the GUID space is larger than the number of 32-bit integers, you're guaranteed to have collisions if you have enough GUIDs. Given that you understand that and are prepared to deal with collisions, however rare, GetHashCode() is designed for exactly this purpose and should be preferred.
I used the advice of Kevin Jones above with the following --skip-networking change for slightly better security:
sudo systemctl set-environment MYSQLD_OPTS="--skip-grant-tables --skip-networking"
[user@machine ~]$ mysql -u root
Then when attempting to reset the password I received an error, but googling elsewhere suggested I could simply forge ahead. The following worked:
mysql> select user(), current_user();
+--------+-----------------------------------+
| user() | current_user() |
+--------+-----------------------------------+
| root@ | skip-grants user@skip-grants host |
+--------+-----------------------------------+
1 row in set (0.00 sec)
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'sup3rPw#'
ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.02 sec)
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'sup3rPw#'
Query OK, 0 rows affected (0.08 sec)
mysql> exit
Bye
[user@machine ~]$ systemctl stop mysqld
[user@machine ~]$ sudo systemctl unset-environment MYSQLD_OPTS
[user@machine ~]$ systemctl start mysqld
At that point I was able to log in.
One of the best methods to compare two colors by human perception is CIE76. The difference is called Delta-E. When it is less than 1, the human eye can not recognize the difference.
There is wonderful color utilities class ColorUtils (code below), which includes CIE76 comparison methods. It is written by Daniel Strebel,University of Zurich.
From ColorUtils.class I use the method:
static double colorDifference(int r1, int g1, int b1, int r2, int g2, int b2)
r1,g1,b1 - RGB values of the first color
r2,g2,b2 - RGB values ot the second color that you would like to compare
If you work with Android, you can get these values like this:
r1 = Color.red(pixel);
g1 = Color.green(pixel);
b1 = Color.blue(pixel);
ColorUtils.class by Daniel Strebel,University of Zurich:
import android.graphics.Color;
public class ColorUtil {
public static int argb(int R, int G, int B) {
return argb(Byte.MAX_VALUE, R, G, B);
}
public static int argb(int A, int R, int G, int B) {
byte[] colorByteArr = {(byte) A, (byte) R, (byte) G, (byte) B};
return byteArrToInt(colorByteArr);
}
public static int[] rgb(int argb) {
return new int[]{(argb >> 16) & 0xFF, (argb >> 8) & 0xFF, argb & 0xFF};
}
public static int byteArrToInt(byte[] colorByteArr) {
return (colorByteArr[0] << 24) + ((colorByteArr[1] & 0xFF) << 16)
+ ((colorByteArr[2] & 0xFF) << 8) + (colorByteArr[3] & 0xFF);
}
public static int[] rgb2lab(int R, int G, int B) {
//http://www.brucelindbloom.com
float r, g, b, X, Y, Z, fx, fy, fz, xr, yr, zr;
float Ls, as, bs;
float eps = 216.f / 24389.f;
float k = 24389.f / 27.f;
float Xr = 0.964221f; // reference white D50
float Yr = 1.0f;
float Zr = 0.825211f;
// RGB to XYZ
r = R / 255.f; //R 0..1
g = G / 255.f; //G 0..1
b = B / 255.f; //B 0..1
// assuming sRGB (D65)
if (r <= 0.04045)
r = r / 12;
else
r = (float) Math.pow((r + 0.055) / 1.055, 2.4);
if (g <= 0.04045)
g = g / 12;
else
g = (float) Math.pow((g + 0.055) / 1.055, 2.4);
if (b <= 0.04045)
b = b / 12;
else
b = (float) Math.pow((b + 0.055) / 1.055, 2.4);
X = 0.436052025f * r + 0.385081593f * g + 0.143087414f * b;
Y = 0.222491598f * r + 0.71688606f * g + 0.060621486f * b;
Z = 0.013929122f * r + 0.097097002f * g + 0.71418547f * b;
// XYZ to Lab
xr = X / Xr;
yr = Y / Yr;
zr = Z / Zr;
if (xr > eps)
fx = (float) Math.pow(xr, 1 / 3.);
else
fx = (float) ((k * xr + 16.) / 116.);
if (yr > eps)
fy = (float) Math.pow(yr, 1 / 3.);
else
fy = (float) ((k * yr + 16.) / 116.);
if (zr > eps)
fz = (float) Math.pow(zr, 1 / 3.);
else
fz = (float) ((k * zr + 16.) / 116);
Ls = (116 * fy) - 16;
as = 500 * (fx - fy);
bs = 200 * (fy - fz);
int[] lab = new int[3];
lab[0] = (int) (2.55 * Ls + .5);
lab[1] = (int) (as + .5);
lab[2] = (int) (bs + .5);
return lab;
}
/**
* Computes the difference between two RGB colors by converting them to the L*a*b scale and
* comparing them using the CIE76 algorithm { http://en.wikipedia.org/wiki/Color_difference#CIE76}
*/
public static double getColorDifference(int a, int b) {
int r1, g1, b1, r2, g2, b2;
r1 = Color.red(a);
g1 = Color.green(a);
b1 = Color.blue(a);
r2 = Color.red(b);
g2 = Color.green(b);
b2 = Color.blue(b);
int[] lab1 = rgb2lab(r1, g1, b1);
int[] lab2 = rgb2lab(r2, g2, b2);
return Math.sqrt(Math.pow(lab2[0] - lab1[0], 2) + Math.pow(lab2[1] - lab1[1], 2) + Math.pow(lab2[2] - lab1[2], 2));
}
}
to set JAVA_HOME permenantly in mac make sure you have JDK installed in your system, if jdk is not installed you can download it from here https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
After installing jdk follow these steps :-
1) Open Terminal
2) Type "vim .bash_profile"
3) press "i" to edit or enter the path
4) Type your java instalation dir :- export JAVA_HOME=$(/usr/libexec/java_home)
5) Click ESC then type ":wq" (save and quit in vim)
6) Then type "source .bash_profile"
7) type "echo $JAVA_HOME" if you see the path you are all set.
THANK YOU
You will also get this error if you have a generic declaration for both your class and your method. For example the code shown below gives this compile error.
public class Foo <T> {
T var;
public <T> void doSomething(Class <T> cls) throws InstantiationException, IllegalAccessException {
this.var = cls.newInstance();
}
}
This code does compile (note T removed from method declaration):
public class Foo <T> {
T var;
public void doSomething(Class <T> cls) throws InstantiationException, IllegalAccessException {
this.var = cls.newInstance();
}
}
For a long time I have used the alternative:
('netscape' in window) && / rv:/.test(navigator.userAgent)
because I don't trust user agent strings. Some bugs are not detectable using feature detection, so detecting the browser is required for some workarounds.
Also if you are working around a bug in Gecko, then the bug is probably also in derivatives of Firefox, and this code should work with derivatives too (Do Waterfox and Pale Moon have 'Firefox' in the user agent string?).
Facebook Developer Wiki (unofficial) contain not only list of FQL error codes but others too it's somehow updated but not contain full list of possible error codes.
There is no any official or updated (I mean really updated) list of error codes returned by Graph API. Every list that can be found online is outdated and not help that much...
There is official list describing some of API Errors and basic recovery tactics. Also there is couple of offcial lists for specific codes:
Your regexp use ^
and $
so it tries to match the entire string. And if you want only a boolean as the result, use test
instead of match
.
var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
if(format.test(string)){
return true;
} else {
return false;
}
One way to test private methods is through reflection. This applies to NUnit and XUnit, too:
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object[] parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
There is a workaround for the usual problem of spaces and newlines:
Use a character that is not in the original array (like $'\1'
or $'\4'
or similar).
This function gets the job done:
# Sort an Array may have spaces or newlines with a workaround (wa=$'\4')
sortarray(){ local wa=$'\4' IFS=''
if [[ $* =~ [$wa] ]]; then
echo "$0: error: array contains the workaround char" >&2
exit 1
fi
set -f; local IFS=$'\n' x nl=$'\n'
set -- $(printf '%s\n' "${@//$nl/$wa}" | sort -n)
for x
do sorted+=("${x//$wa/$nl}")
done
}
This will sort the array:
$ array=( a b 'c d' $'e\nf' $'g\1h')
$ sortarray "${array[@]}"
$ printf '<%s>\n' "${sorted[@]}"
<a>
<b>
<c d>
<e
f>
<gh>
This will complain that the source array contains the workaround character:
$ array=( a b 'c d' $'e\nf' $'g\4h')
$ sortarray "${array[@]}"
./script: error: array contains the workaround char
wa
(workaround char) and a null IFS$*
.[[ $* =~ [$wa] ]]
.exit 1
set -f
IFS=$'\n'
) a loop variable x
and a newline var (nl=$'\n'
).$@
)."${@//$nl/$wa}"
.sort -n
.set --
.for x
sorted+=(…)
"${x//$wa/$nl}"
.display: none;
_x000D_
This should make the element disappear and not take up any space.
Was missing the use of calc
in the answers, which is a cleaner solution.
#logo {
position: absolute;
left: calc(50% - 25px);
height: 50px;
width: 50px;
background: red;
}
Works in most modern browsers: http://caniuse.com/calc
Maybe it's too soon to use it without a fallback, but I thought maybe for future visitors it would be helpful.
What about putting the query results in an array, where you can do a count($array) and use the query resulting rows after? Example:
$sc='SELECT * FROM comments';
$res=array();
foreach($db->query($sc) as $row){
$res[]=$row;
}
echo "num rows: ".count($res);
echo "Select output:";
foreach($res as $row){ echo $row['comment'];}
First, have to check
SELECT * FROM university
WHERE course_name LIKE '%&%'
Next, have to update
UPDATE university SET course_name = REPLACE(course_name, '&', '&') WHERE id = 1
Results: Engineering & Technology => Engineering & Technology
1.) Storage of database passwords Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.
2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.
The query should then look like this:
select hashedPassword from users where username=?
Then compare the password to the input.
Further questions?
SOAP stands for Simple (sic) Object Access Protocol. It was intended to be a way to do Remote Procedure Calls to remote objects by sending XML over HTTP.
WSDL is Web Service Description Language. A request ending in '.wsdl' to an endpoint will result in an XML message describing request and response that a use can expect. It descibes the contract between service & client.
REST uses HTTP to send messages to services.
SOAP is a spec, REST is a style.
First, set up a loading image in a div. Next, get the div element. Then, set a function that edits the css to make the visibility to "hidden". Now, in the <body>
, put the onload to the function name.
A simpler scan would be:
String1.scan(/<(\S+)>/).last
There are the following way to select first child
1) $('.second div:first-child')
2) $('.second *:first-child')
3) $('div:first-child', '.second')
4) $('*:first-child', '.second')
5) $('.second div:nth-child(1)')
6) $('.second').children().first()
7) $('.second').children().eq(0)
If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :
For eg.
Dim dt As New DataTable
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")
Create an example data.frame and add a column to it.
df = data.frame(a = seq(1, 3), b = seq(4,6), c = seq(7,9))
df['d'] <- seq(10,12)
df
a b c d
1 1 4 7 10
2 2 5 8 11
3 3 6 9 12
Rearrange by column index
df[, colnames(df)[c(1:2,4,3)]]
or by column name
df[, c('a', 'b', 'd', 'c')]
The result is
a b d c
1 1 4 10 7
2 2 5 11 8
3 3 6 12 9
When you export a class module and open the file in Notepad, you'll notice, near the top, a bunch of hidden attributes (the VBE doesn't display them, and doesn't expose functionality to tweak most of them either). One of them is VB_PredeclaredId
:
Attribute VB_PredeclaredId = False
Set it to True
, save, and re-import the module into your VBA project.
Classes with a PredeclaredId
have a "global instance" that you get for free - exactly like UserForm
modules (export a user form, you'll see its predeclaredId attribute is set to true).
A lot of people just happily use the predeclared instance to store state. That's wrong - it's like storing instance state in a static class!
Instead, you leverage that default instance to implement your factory method:
[Employee
class]
'@PredeclaredId
Option Explicit
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As Employee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As Employee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
With that, you can do this:
Dim empl As Employee
Set empl = Employee.Create("Johnny", 69)
Employee.Create
is working off the default instance, i.e. it's considered a member of the type, and invoked from the default instance only.
Problem is, this is also perfectly legal:
Dim emplFactory As New Employee
Dim empl As Employee
Set empl = emplFactory.Create("Johnny", 69)
And that sucks, because now you have a confusing API. You could use '@Description
annotations / VB_Description
attributes to document usage, but without Rubberduck there's nothing in the editor that shows you that information at the call sites.
Besides, the Property Let
members are accessible, so your Employee
instance is mutable:
empl.Name = "Jane" ' Johnny no more!
The trick is to make your class implement an interface that only exposes what needs to be exposed:
[IEmployee
class]
Option Explicit
Public Property Get Name() As String : End Property
Public Property Get Age() As Integer : End Property
And now you make Employee
implement IEmployee
- the final class might look like this:
[Employee
class]
'@PredeclaredId
Option Explicit
Implements IEmployee
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As IEmployee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As IEmployee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
Private Property Get IEmployee_Name() As String
IEmployee_Name = Name
End Property
Private Property Get IEmployee_Age() As Integer
IEmployee_Age = Age
End Property
Notice the Create
method now returns the interface, and the interface doesn't expose the Property Let
members? Now calling code can look like this:
Dim empl As IEmployee
Set empl = Employee.Create("Immutable", 42)
And since the client code is written against the interface, the only members empl
exposes are the members defined by the IEmployee
interface, which means it doesn't see the Create
method, nor the Self
getter, nor any of the Property Let
mutators: so instead of working with the "concrete" Employee
class, the rest of the code can work with the "abstract" IEmployee
interface, and enjoy an immutable, polymorphic object.
You might consider wrapping the operations. For example:
class Utils
{
public static double divide(int num, int denom) {
return ((double) num) / denom;
}
}
This allows you to look up (just once) whether the cast does exactly what you want. This method could also be subject to tests, to ensure that it continues to do what you want. It also doesn't matter what trick you use to cause the division (you could use any of the answers here), as long as it results in the correct result. Anywhere you need to divide two integers, you can now just call Utils::divide
and trust that it does the right thing.
While the others answers are correct in so far as they show what a mere +
usually does (namely, leave the number as it is, if it is one), they are incomplete in so far as they don't explain what happens.
To be exact, +x
evaluates to x.__pos__()
and ++x
to x.__pos__().__pos__()
.
I could imagine a VERY weird class structure (Children, don't do this at home!) like this:
class ValueKeeper(object):
def __init__(self, value): self.value = value
def __str__(self): return str(self.value)
class A(ValueKeeper):
def __pos__(self):
print 'called A.__pos__'
return B(self.value - 3)
class B(ValueKeeper):
def __pos__(self):
print 'called B.__pos__'
return A(self.value + 19)
x = A(430)
print x, type(x)
print +x, type(+x)
print ++x, type(++x)
print +++x, type(+++x)
You MUST add below part to enable NameVirtualHost
functionality with given IP.
NameVirtualHost IP_Address:443
Well, your syntax doesn't match the link you included, which specifies:
CREATE TABLE name (column defs)
CONSTRAINT constraint_name -- This is new
UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE
I just wanted to add that using the novalidate attribute in your form will only prevent the browser from sending the form. The browser still evaluates the data and adds the :valid and :invalid pseudo classes.
I found this out because the valid and invalid pseudo classes are part of the HTML5 boilerplate stylesheet which I have been using. I just removed the entries in the CSS file that related to the pseudo classes. If anyone finds another solution please let me know.
Sometimes the .gz
extension is wrongfully appended to the filename.
file foo.csv.gz
to know the actual file type.foo.csv
or whatever the actual file type is.LINQ to SQL only supports 1 to 1 mapping of database tables, views, sprocs and functions available in Microsoft SQL Server. It's a great API to use for quick data access construction to relatively well designed SQL Server databases. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.
LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.
This is a good introductory article on MSDN: Introducing LINQ to Relational Data
While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.
You then run the jar directly by java -jar example.jar.
For me, the problem was that I set up a new layoutmanager every time I changed my adapter, loosing que scroll position on recyclerView.
This is a stronger regex replace that won't replace %% that are already doubled in the input.
str = str.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%");
SELECT
tab1.std_name, tab1.stdCode, tab1.payment,
SUBSTRING_INDEX(tab1.payment, '|', 1) as rupees,
SUBSTRING(tab1.payment, LENGTH(SUBSTRING_INDEX(tab1.payment, '|', 1)) + 2,LENGTH(SUBSTRING_INDEX(tab1.payment, '|', 2))) as date
FROM (
SELECT DISTINCT
si.std_name, hfc.stdCode,
if(isnull(hfc.payDate), concat(hfc.coutionMoneyIn,'|', year(hfc.startDtae), '-', monthname(hfc.startDtae)), concat(hfc.payMoney, '|', monthname(hfc.payDate), '-', year(hfc.payDate))) AS payment
FROM hostelfeescollection hfc
INNER JOIN hostelfeecollectmode hfm ON hfc.tranId = hfm.tranId
INNER JOIN student_info_1 si ON si.std_code = hfc.stdCode
WHERE hfc.tranId = 'TRAN-AZZZY69454'
) AS tab1
Password Strength Algorithm:
Password Length:
5 Points: Less than 4 characters
10 Points: 5 to 7 characters
25 Points: 8 or more
Letters:
0 Points: No letters
10 Points: Letters are all lower case
20 Points: Letters are upper case and lower case
Numbers:
0 Points: No numbers
10 Points: 1 number
20 Points: 3 or more numbers
Characters:
0 Points: No characters
10 Points: 1 character
25 Points: More than 1 character
Bonus:
2 Points: Letters and numbers
3 Points: Letters, numbers, and characters
5 Points: Mixed case letters, numbers, and characters
Password Text Range:
>= 90: Very Secure
>= 80: Secure
>= 70: Very Strong
>= 60: Strong
>= 50: Average
>= 25: Weak
>= 0: Very Weak
Settings Toggle to true or false, if you want to change what is checked in the password
var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"
Check password
function checkPassword(strPassword)
{
// Reset combination count
var nScore = 0;
// Password length
// -- Less than 4 characters
if (strPassword.length < 5)
{
nScore += 5;
}
// -- 5 to 7 characters
else if (strPassword.length > 4 && strPassword.length < 8)
{
nScore += 10;
}
// -- 8 or more
else if (strPassword.length > 7)
{
nScore += 25;
}
// Letters
var nUpperCount = countContain(strPassword, m_strUpperCase);
var nLowerCount = countContain(strPassword, m_strLowerCase);
var nLowerUpperCount = nUpperCount + nLowerCount;
// -- Letters are all lower case
if (nUpperCount == 0 && nLowerCount != 0)
{
nScore += 10;
}
// -- Letters are upper case and lower case
else if (nUpperCount != 0 && nLowerCount != 0)
{
nScore += 20;
}
// Numbers
var nNumberCount = countContain(strPassword, m_strNumber);
// -- 1 number
if (nNumberCount == 1)
{
nScore += 10;
}
// -- 3 or more numbers
if (nNumberCount >= 3)
{
nScore += 20;
}
// Characters
var nCharacterCount = countContain(strPassword, m_strCharacters);
// -- 1 character
if (nCharacterCount == 1)
{
nScore += 10;
}
// -- More than 1 character
if (nCharacterCount > 1)
{
nScore += 25;
}
// Bonus
// -- Letters and numbers
if (nNumberCount != 0 && nLowerUpperCount != 0)
{
nScore += 2;
}
// -- Letters, numbers, and characters
if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
{
nScore += 3;
}
// -- Mixed case letters, numbers, and characters
if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
{
nScore += 5;
}
return nScore;
}
// Runs password through check and then updates GUI
function runPassword(strPassword, strFieldID)
{
// Check password
var nScore = checkPassword(strPassword);
// Get controls
var ctlBar = document.getElementById(strFieldID + "_bar");
var ctlText = document.getElementById(strFieldID + "_text");
if (!ctlBar || !ctlText)
return;
// Set new width
ctlBar.style.width = (nScore*1.25>100)?100:nScore*1.25 + "%";
// Color and text
// -- Very Secure
/*if (nScore >= 90)
{
var strText = "Very Secure";
var strColor = "#0ca908";
}
// -- Secure
else if (nScore >= 80)
{
var strText = "Secure";
vstrColor = "#7ff67c";
}
// -- Very Strong
else
*/
if (nScore >= 80)
{
var strText = "Very Strong";
var strColor = "#008000";
}
// -- Strong
else if (nScore >= 60)
{
var strText = "Strong";
var strColor = "#006000";
}
// -- Average
else if (nScore >= 40)
{
var strText = "Average";
var strColor = "#e3cb00";
}
// -- Weak
else if (nScore >= 20)
{
var strText = "Weak";
var strColor = "#Fe3d1a";
}
// -- Very Weak
else
{
var strText = "Very Weak";
var strColor = "#e71a1a";
}
if(strPassword.length == 0)
{
ctlBar.style.backgroundColor = "";
ctlText.innerHTML = "";
}
else
{
ctlBar.style.backgroundColor = strColor;
ctlText.innerHTML = strText;
}
}
// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{
// Declare variables
var nCount = 0;
for (i = 0; i < strPassword.length; i++)
{
if (strCheck.indexOf(strPassword.charAt(i)) > -1)
{
nCount++;
}
}
return nCount;
}
You can customize by yourself according to your requirement.
In newer JavaScript standards like ES5 and ES6 you can just say
> Boolean(0) //false
> Boolean(null) //false
> Boolean(undefined) //false
all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say
if (Boolean(myvar)){
// Do something
}
here "null" or "empty string" or "undefined" will be handled efficiently.
-DBL_MAX
in ANSI C, which is defined in float.h.
Maybe something changed since 2011 but this worked for me:
$ date +"%Y%m%d"
20150330
No need for the -d
to get the same appearing result.
Keep in mind the actual fragmentation that occurs when DELETE+INSERT is issued opposed to a correctly implemented UPDATE will make great difference by time.
Thats why, for instance, REPLACE INTO that MySQL implements is discouraged as opposed to using the INSERT INTO ... ON DUPLICATE KEY UPDATE ... syntax.
Sometimes in Windows whitespaces in paths are not recognized correctly
If you have a path problem and path seems like
c:\Program Files\....
try changing it in an old DOS format like
"C:\Progra~1\...
You can use dir /x
to check correct syntax (third column)
C:\>dir /x
...
11.01.2008 15:47 <DIR> DOCUME~1 Documents and Settings
01.12.2006 09:10 <DIR> MYPROJ~1 My Projects
21.01.2011 14:08 <DIR> PROGRA~1 Program Files
...
In my pc JAVA_HOME is (and it works)
"C:\Progra~1\Java\jdk1.8.0_121"
Tested in Windows 10
Healpix solves a closely related problem (pixelating the sphere with equal area pixels):
http://healpix.sourceforge.net/
It's probably overkill, but maybe after looking at it you'll realize some of it's other nice properties are interesting to you. It's way more than just a function that outputs a point cloud.
I landed here trying to find it again; the name "healpix" doesn't exactly evoke spheres...
As said above you can find PHP error log in windows. In c:\xampp\apache\logs\error.log. You can easily display the last logs by tail -f .\error.log
You just need a loop that iterates the number of times given by n
and prints a space each time. This would do:
while (n--) {
std::cout << ' ';
}