all: program
program.o: program.h headers.h
is enough. the rest is implicit
I'm surprised no one here has mentioned the html cell magic option. from the docs (IPython, but same for Jupyter)
%%html
Render the cell as a block of HTML
One way would be to convert both strings to upper or lower:
test $(echo "string" | /bin/tr '[:upper:]' '[:lower:]') = $(echo "String" | /bin/tr '[:upper:]' '[:lower:]') && echo same || echo different
Another way would be to use grep:
echo "string" | grep -qi '^String$' && echo same || echo different
In Support Library 27.1.0 and later, Google has introduced new methods requireContext()
and requireActivity()
methods.
Eg:ContextCompat.getColor(requireContext(), R.color.soft_gray)
More info here
Short-hand to convert python date/datetime to Epoch (without microseconds)
int(current_date.strftime("%s")) # 2020-01-14 ---> 1578956400
int(current_datetime.strftime("%s")) # 2020-01-14 16:59:30.251176 -----> 1579017570
This would require knowledge of a backend website language.
Fortunately, Python's Flask Library is a suitable backend language for the project at hand.
Check out this answer from another thread.
Just another bit. in some case i found no result on all_tab_privs! i found it indeed on dba_tab_privs. I think so that this last table is better to check for any grant available on an object (in case of impact analysis). The statement becomes:
select * from dba_tab_privs where table_name = 'sequence_name';
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I have connection string Server=(localdb)\v11.0;Integrated Security=true;Database=DB1;
and even a .NET 3.5 program connects and execute SQL successfully.
But many people say .NET 4.0.2 or 4.5 is required.
The answer by Vijey has a bit of a problem when you're using react-redux for state management and some of the parent components are 'connected' to the redux store. The activeClassName is applied to Link only when the page is refreshed, and is not dynamically applied as the current route changes.
This is to do with the react-redux's connect function, as it suppresses context updates. To disable suppression of context updates, you can set pure: false
when calling the connect()
method like this:
//your component which has the custom NavLink as its child.
//(this component may be the any component from the list of
//parents and grandparents) eg., header
function mapStateToProps(state) {
return { someprops: state.someprops }
}
export default connect(mapStateToProps, null, null, {
pure: false
})(Header);
Check the issue here: reactjs#470
Check pure: false
documentation here: docs
Based on above answers I created the following API
/*
* .addClassSVG(className)
* Adds the specified class(es) to each of the set of matched SVG elements.
*/
$.fn.addClassSVG = function(className){
$(this).attr('class', function(index, existingClassNames) {
return ((existingClassNames !== undefined) ? (existingClassNames + ' ') : '') + className;
});
return this;
};
/*
* .removeClassSVG(className)
* Removes the specified class to each of the set of matched SVG elements.
*/
$.fn.removeClassSVG = function(className){
$(this).attr('class', function(index, existingClassNames) {
var re = new RegExp('\\b' + className + '\\b', 'g');
return existingClassNames.replace(re, '');
});
return this;
};
When you are selecting INTO a variable and there are no records returned you should get a NO DATA FOUND error. I believe the correct way to write the above code would be to wrap the SELECT statement with it's own BEGIN/EXCEPTION/END block. Example:
...
v_final_grade NUMBER;
v_letter_grade CHAR(1);
BEGIN
BEGIN
SELECT final_grade
INTO v_final_grade
FROM enrollment
WHERE student_id = v_student_id
AND section_id = v_section_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_final_grade := NULL;
END;
CASE -- outer CASE
WHEN v_final_grade IS NULL THEN
...
To work off the answer above (https://stackoverflow.com/a/44860918/2011818), you can also send the objects inline the "To" inside the Link object.
<Route path="/foo/:fooId" component={foo} / >
<Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>
this.props.match.params.fooId //newb
this.props.location.sampleParam //"Hello"
this.props.location.sampleParam2 //"World!"
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
Note: this doen't sanitize arrays:
import { isPlainObject } from 'lodash';
export const sanitize = (obj: {}) => {
if (isPlainObject(obj)) {
const sanitizedObj = {};
for (const key in obj) {
if (obj[key]) {
sanitizedObj[key] = sanitize(obj[key]);
}
}
return sanitizedObj;
} else {
return obj;
}
};
Test:
describe('sanitize', () => {
it('should keep an object if there are no empty fields', () => {
expect(sanitize({})).toEqual({});
expect(sanitize({ foo: 'bar' })).toEqual({ foo: 'bar' });
expect(sanitize({ content: { foo: 'bar' } })).toEqual({
content: { foo: 'bar' },
});
});
it('should remove empty fields from top level', () => {
expect(sanitize({ foo: '', bar: 'baz' })).toEqual({ bar: 'baz' });
expect(sanitize({ foo: null, bar: 'baz' })).toEqual({ bar: 'baz' });
expect(sanitize({ foo: undefined, bar: 'baz' })).toEqual({ bar: 'baz' });
});
it('should remove nested empty fields', () => {
expect(sanitize({ content: { foo: '', bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
expect(sanitize({ content: { foo: null, bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
expect(sanitize({ content: { foo: undefined, bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
});
});
Safest way will be to output or return the scope_identity() within the procedure inserting the row, and then retrieve the row based on that ID. Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.
Any technique of asking for the maximum value / top 1 suffers a race condition where 2 people adding at the same time, would then get the same ID back when they looked for the highest ID.
it is not working in the Powershell and should use CMD in my case
As a type that contains children, I'm using:
type ChildrenContainer = Pick<JSX.IntrinsicElements["div"], "children">
This children container type is generic enough to support all the different cases and also aligned with the ReactJS API.
So, for your example it would be something like:
const layout = ({ children }: ChildrenContainer) => (
<Aux>
<div>Toolbar, SideDrawer, Backdrop</div>
<main>
{children}
</main>
<Aux/>
)
i just created a lightweight keyboard handler to follow keyboard frame.
Usage:
self.keyboardHandler = [EDKeyboardHandler new];
[self.keyboardHandler listenWithBlock:^(KeyboardInfo *model)
{
//adjust view positions according to keyboard position here
}];
and the KeyboardInfo model has the following properties:
typedef enum : NSUInteger {
KeyboardStatusDidShow,
KeyboardStatusWillShow,
KeyboardStatusDidHide,
KeyboardStatusWillHide,
} KeyboardStatus;
@interface KeyboardInfo:NSObject
@property (nonatomic,readonly) NSTimeInterval animationDuration;
@property (nonatomic,readonly) CGRect keyboardFrame;
@property (nonatomic,readonly) NSInteger animationCurve;
@property (nonatomic,readonly) KeyboardStatus status;
@end
check GitHub project for details and cocoaPods integration.
List comprehension works well, and looping through with enumerate can save you some memory (b/c the operation's essentially being done in place).
There's also functional programming. See usage of map:
>>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1]
>>> map(lambda x: x if x != 4 else 'sss', a)
[1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]
If you're already using jQuery, you could try this:
$(window).bind("load", function() {
// code here
});
It's part of the Oracle analytic functions.
Ouath just makes the Google instance null, hence it you out of Google. Now that's how the architecture is made. Logging out of Google, if you Logout of your app is a dirty work, but can't help if the requirement stipulates the same. Hence add the following to your signOut() function. My project was an Angular 6 app:
document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost:4200";
Here localhost:4200 is the URL of my app. If your login page is xyz.com then input that.
Convert interface{}
into any type.
Syntax:
result := interface.(datatype)
Example:
var employee interface{} = []string{"Jhon", "Arya"}
result := employee.([]string) //result type is []string.
Recently ran into the same problem, struggled for a bit, found this topic but no answers were correct for me.
My issue was that when I removed main window from my WPF project (it does not have a main window), I forgot to remove StartupUri
from App.xaml
. I guess this exception can happen if you have a mistake in StartupUri
, so in case if anybody is struggling with this - check your StartupUri
in App.xaml
.
You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user
.
Now, you can access every property of the user. For example, you can access the username like that : app.user.username
.
Warning, if the user is not logged, the app.user
is null.
If you want to check if the user is logged, you can use the is_granted
twig function. For example, if you want to check if the user has ROLE_ADMIN
, you just have to do is_granted("ROLE_ADMIN")
.
So, in every of your pages you can do :
{% if is_granted("ROLE") %}
Hi {{ app.user.username }}
{% endif %}
I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github
sample output:
shm attach process list, group by shm key
##################################################################
0x2d5feab4: /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c: /home/curu/playd
0x77da6cfe: /home/curu/mem_dumper /home/curu/playd /home/curu/scand
##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]: 0x2d5feab4 0x77da6cfe
/home/curu/playd [3]: 0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]: 0x77da6cfe
I see that at least you're not providing the same path as others in file_paths.xml. So please make sure you provide the exact the same package name or path in 3 places including:
android:authorities
attribute in manifestpath
attribute in file_paths.xmlauthority
argument when calling FileProvider.getUriForFile().Another workaround is to sort the spreadsheet with the character data at the top, thereby causing Excel to see the column as string, and importing everything as such.
It looks as if you are using the URL.toString
result as the argument to the FileReader
constructor. URL.toString
is a bit broken, and instead you should generally use url.toURI().toString()
. In any case, the string is not a file path.
Instead, you should either:
URL
to ServicesLoader
and let it call openStream
or similar.Class.getResourceAsStream
and just pass the stream over, possibly inside an InputSource
. (Remember to check for nulls as the API is a bit messy.)Here's a reusable way of doing it (it's typescript but you can adapt it to js):
export function waitFor<T>(signal: Observable<any>) {
return (source: Observable<T>) =>
new Observable<T>(observer =>
signal.pipe(first())
.subscribe(_ =>
source.subscribe(observer)
)
);
}
and you can use it like any operator:
var two = someOtherObservable.pipe(waitFor(one), take(1));
It's basically an operator that defers the subscribe on the source observable until the signal observable emits the first event.
Try this
var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
type: 'POST',
url: '/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
You need to use the FormData API and set the jQuery.ajax
's processData
and contentType
to false
.
Usually this means that your schema and mapping files are not in synch and there is a renamed or missing column someplace.
Edit: Be a Red ninja:
!!array.reduce(function(a, b){ return (a === b) ? a : NaN; });
Results:
var array = ["a", "a", "a"] => result: "true"
var array = ["a", "b", "a"] => result: "false"
var array = ["false", ""] => result: "false"
var array = ["false", false] => result: "false"
var array = ["false", "false"] => result: "true"
var array = [NaN, NaN] => result: "false"
Warning:
var array = [] => result: TypeError thrown
This is because we do not pass an initialValue. So, you may wish to check array.length
first.
mkdir -p /dir/to/the/file
touch /dir/to/the/file/thefile.ending
@Martin Devillers solution works fine. For completeness, providing the steps below:
src/main/resource
In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.
<wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
<wsdlLocation>/mydir/my.wsdl</wsdlLocation>
Then in your java code(with no-arg constructor):
MyPort myPort = new MyPortService().getMyPort();
Here is the full code generation part in pom file, with fluent api in generated code.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.5</version>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>wsdl-to-java-generator</id>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<xjcArgs>
<xjcArg>-Xfluent-api</xjcArg>
</xjcArgs>
<keep>true</keep>
<wsdlDirectory>src/main/resources/package</wsdlDirectory>
<wsdlLocation>/package/my.wsdl</wsdlLocation>
<sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
<packageName>full.package.here</packageName>
</configuration>
</execution>
</executions>
If you'd like to use base graphics, you may have a look at this. An extract:
You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.
None?
I mean, other than removing it from the layout entirely with display: none
, I'm pretty sure that's it.
Are you facing a particular situation in which position: absolute
is not a viable solution?
I suggest using a directive on a link. Here is the fiddle.
But its not perfect yet. Watch out for the hashbangs ;)
Here is the javascript for directive:
angular.module('link', []).
directive('activeLink', ['$location', function(location) {
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
var clazz = attrs.activeLink;
var path = attrs.href;
path = path.substring(1); //hack because path does not return including hashbang
scope.location = location;
scope.$watch('location.path()', function(newPath) {
if (path === newPath) {
element.addClass(clazz);
} else {
element.removeClass(clazz);
}
});
}
};
}]);
and here is how it would be used in html:
<div ng-app="link">
<a href="#/one" active-link="active">One</a>
<a href="#/two" active-link="active">One</a>
<a href="#" active-link="active">home</a>
</div>
afterwards styling with css:
.active{ color:red; }
If you want to redirect on url instead of activity from your adapter class then pass context of with startactivity.
btnInstall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(link));
intent.setData(Uri.parse(link));
context.startActivity(intent);
}
});
You can use a attribute called placeholder=""
Here's a demo:
<html>
<body>
// try this out!
<input placeholder="This is my placeholder"/>
</body>
</html>
To open a file in git, with windows you will type explorer .
, notice the space between explorer and the dot. On mac you can open it with open .
, and in Linux with nautilus .
, notice the period at the end of each one.
System.Environment.TickCount and the System.Diagnostics.Stopwatch class are two that work well for finer resolution and straightforward usage.
See Also:
int a = srand(time(NULL));
The prototype for srand
is void srand(unsigned int)
(provided you included <stdlib.h>
).
This means it returns nothing ... but you're using the value it returns (???) to assign, by initialization, to a
.
Edit: this is what you need to do:
#include <stdlib.h> /* srand(), rand() */
#include <time.h> /* time() */
#define ARRAY_SIZE 1024
void getdata(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = rand();
}
}
int main(void)
{
int arr[ARRAY_SIZE];
srand(time(0));
getdata(arr, ARRAY_SIZE);
/* ... */
}
If you're developing for Android there is TextUtils class which may help you:
import android.text.TextUtils;
It is really helps a lot to check equality of Strings.
For example if you need to check Strings s1, s2 equality (which may be nulls) you may use instead of
if( (s1 != null && !s1.equals(s2)) || (s1 == null && s2 != null) )
{ ... }
this simple method:
if( !TextUtils.equals(s1, s2) )
{ ... }
As for initial question - for replacement it's easier to use s1.replace().
There might be a semicolon or bracket missing a line before your pasted line.
It seems fine to me; every string is allowed as an array index.
You may use 'inf' like this:
import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf
From the Security
point of view we can use this practical example:
DBCursor makeConnection(String IP,String PORT,String USER,String PASS,String TABLE) {
// if strings were mutable IP,PORT,USER,PASS can be changed by validate function
Boolean validated = validate(IP,PORT,USER,PASS);
// here we are not sure if IP, PORT, USER, PASS changed or not ??
if (validated) {
DBConnection conn = doConnection(IP,PORT,USER,PASS);
}
// rest of the code goes here ....
}
For anyone wondering where the settings for apps from the Microsoft Store are, they are either in WindowsApps, which is very locked down, but you can get there by opening your app and then opening the file path with Task-Manager.
But it's more likely that they are saved in C:\Users\[USERNAME]\AppData\Local\Packages\[NUMBERS][COMPANY].[APPLICATION]_[RANDOMDATA]\LocalCache\Local\[COMPANY]\[APPLICATION].exe_Url_[RANDOMDATA]\[VERSION]\user.config.
Both the data import function (here: read.csv()
) as well as a global option offer you to say stringsAsFactors=FALSE
which should fix this.
Call the perl binary, in search and replace per line mode ( the -pi
) by running the perl code ( the -e
) in the single quotes, which iterates over the keys of the special %ENV
hash containing the exported variable names as keys and the exported variable values as the keys' values and for each iteration simple replace a string containing a $<<key>>
with its <<value>>
.
perl -pi -e 'foreach $key(sort keys %ENV){ s/\$$key/$ENV{$key}/g}' file
Caveat: An additional logic handling is required for cases in which two or more vars start with the same string ...
Type "id" on terminal to see the available user ids you can give, Then simply type
"sudo chown -R idname /data/db"
This worked out for me! Hope this resolves your issue.
$.ajax({
type:'POST',
url: 'ajaxRequest.php',
data:{
userEmail : userEmail
},
success:function(data){
if(data == "error"){
$('#ShowError').show().text("Email dosen't Match ");
$('#ShowSuccess').hide();
}
else{
$('#ShowSuccess').show().text(data);
}
}
});
Because its google first answer ...
For version 3
$ mongo
MongoDB shell version: 3.0.2
connecting to: test
> use myDb
switched to db
> db.setLogLevel(1)
http://docs.mongodb.org/manual/reference/method/db.setLogLevel/
I know this is an old post but as MisterZimbu stated, the color
property is defining the values of other properties, as the border-color
and, with CSS3, of currentColor
.
currentColor
is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).
Example:
.element {_x000D_
color: green;_x000D_
background: red;_x000D_
display: block;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
border: solid 10px;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 100px;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
background: currentColor;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 100px;_x000D_
margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
<div class="innerElement1"></div>_x000D_
<div class="innerElement2"></div>_x000D_
</div>
_x000D_
The problem got resolved when I edited the file /etc/bashrc
with same contents as in /etc/profiles
and in /etc/profiles.d/limits.sh
and did a re-login.
I have not been able to find a Firefox option equivalent of --disable-web-security or an addon that does that for me. I really needed it for some testing scenarios where modifying the web server was not possible. What did help was to use Fiddler to auto-modify web responses so that they have the correct headers and CORS is no longer an issue.
The steps are:
Open fiddler.
If on https go to menu Tools -> Options -> Https and tick the Capture & Decrypt https options
Go to menu Rules -> Customize rules. Modify the OnBeforeResponseFunction so that it looks like the following, then save:
static function OnBeforeResponse(oSession: Session) {
//....
oSession.oResponse.headers.Remove("Access-Control-Allow-Origin");
oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
//...
}
This will make every web response to have the Access-Control-Allow-Origin: * header.
This still won't work as the OPTIONS preflight will pass through and cause the request to block before our above rule gets the chance to modify the headers. So to fix this, in the fiddler main window, on the right hand side there's an AutoResponder tab. Add a new rule and response: METHOD:OPTIONS https://yoursite.com/ with auto response: *CORSPreflightAllow and tick the boxes: "Enable Rules" and "Unmatched requests passthrough".
See picture below for reference:
Well, it depends. If the byte-code is translated into machine-code (and not just JIT) (I mean if you execute the program) and if your program uses many allocations/deallocations it could be faster because the GC algorithm just need one pass (theoretically) through the whole memory once, but normal malloc/realloc/free C/C++ calls causes an overhead on every call (call-overhead, data-structure overhead, cache misses ;) ).
So it is theoretically possible (also for other GC languages).
I don't really see the extreme disadvantage of not to be able to use metaprogramming with C# for the most applications, because the most programmers don't use it anyway.
Another big advantage is that the SQL, like the LINQ "extension", provides opportunities for the compiler to optimize calls to databases (in other words, the compiler could compile the whole LINQ to one "blob" binary where the called functions are inlined or for your use optimized, but I'm speculating here).
To complete Sunit's answer, you can use a selector, not to the text string but to the textColorHint. You must add this attribute on your editText:
android:textColorHint="@color/text_hint_selector"
And your text_hint_selector should be:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="@android:color/transparent" />
<item android:color="@color/hint_color" />
</selector>
Try this (edited):
ctx.Database.ExecuteSqlCommand(sql, new SqlParameter("FirstName", firstName),
new SqlParameter("Id", id));
Previous idea was wrong.
First way:
etPassword.post(() -> {
etPassword.requestFocus();
InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
manager.showSoftInput(etPassword, InputMethodManager.SHOW_IMPLICIT);
});
Second way:
In Manifest:
<activity
android:name=".activities.LoginActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible"/>
In code:
etPassword.requestFocus();
In C++0x you have
for(string str: strarr) { ... }
But till then use ordinary for loop.
Here is my function for convert a second
,millisecond
to day,hour,minute,second
public static String millisecondToFullTime(long millisecond) {
return timeUnitToFullTime(millisecond, TimeUnit.MILLISECONDS);
}
public static String secondToFullTime(long second) {
return timeUnitToFullTime(second, TimeUnit.SECONDS);
}
public static String timeUnitToFullTime(long time, TimeUnit timeUnit) {
long day = timeUnit.toDays(time);
long hour = timeUnit.toHours(time) % 24;
long minute = timeUnit.toMinutes(time) % 60;
long second = timeUnit.toSeconds(time) % 60;
if (day > 0) {
return String.format("%dday %02d:%02d:%02d", day, hour, minute, second);
} else if (hour > 0) {
return String.format("%d:%02d:%02d", hour, minute, second);
} else if (minute > 0) {
return String.format("%d:%02d", minute, second);
} else {
return String.format("%02d", second);
}
}
Testing
public static void main(String[] args) {
System.out.println("60 => " + secondToFullTime(60));
System.out.println("101 => " + secondToFullTime(101));
System.out.println("601 => " + secondToFullTime(601));
System.out.println("7601 => " + secondToFullTime(7601));
System.out.println("36001 => " + secondToFullTime(36001));
System.out.println("86401 => " + secondToFullTime(86401));
}
Output
60 => 1:00
101 => 1:41
601 => 10:01
7601 => 2:06:41
36001 => 10:00:01
86401 => 1day 00:00:01
Hope it help
You could use cut
df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf),
labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))
set.seed(24)
df <- data.frame(value= sample(0:2500, 100, replace=TRUE))
You have to get the csrf token..
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
After doing same issue is rise ,Just Add this meta tag< meta name="csrf-token" content="{{ csrf_token() }}" >
After this also the error arise ,you can check the Ajax error. Then Also check the Ajax error
$.ajax({
url: 'some_unknown_page.html',
success: function (response) {
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
},
});
You can't get the number of rows returned in a ResultSet without iterating through it. And why would you return a ResultSet without iterating through it? There'd be no point in executing the query in the first place.
A better solution would be to separate persistence from view. Create a separate Data Access Object that handles all the database queries for you. Let it get the values to be displayed in the JTable
, load them into a data structure, and then return it to the UI for display. The UI will have all the information it needs then.
Something along the lines of this?
<asp:TextBox id="txtUsername" runat="server" />
<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Field not valid!"
ControlToValidate="txtUsername"
ValidationExpression="[0-9a-zA-Z]{6,}" />
This line helps to write a file from an Array or String.
new PrintWriter(outputPath) { write(ArrayName.mkString("")); close }
If you are looking inside dockerfile while creating image, add this line:
RUN apk add --update yourPackageName
After checking catalina.sh (for windows use the .bat versions of everything mentioned below)
# Do not set the variables in this script. Instead put them into a script
# setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
Also this
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc
So create a setenv.sh under CATALINA_BASE/bin (same dir where the catalina.sh resides). Edit the file and set the arguments to CATALINA_OPTS
For e.g. the file would look like this if you wanted to change the heap size
CATALINA_OPTS=-Xmx512m
Or in your case since you're using windows setenv.bat would be
set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
To clear the added options later just delete setenv.bat/sh
Curl gives this error when there is no reply from a server, since it is an error for HTTP not to respond anything to a request.
I suspect the problem you have is that there is some piece of network infrastructure, like a firewall or a proxy, between you and the host in question. Getting this to work, therefore, will require you to discuss the issue with the people responsible for that hardware.
While many of the answers produce useful results, I think the hustle of maintaining a complex script for this task is not worth it. This is mainly because most distros use different cron daemons.
$ \cat ~jaroslav/bin/ls-crons
#!/bin/bash
getent passwd | awk -F: '{ print $1 }' | xargs -I% sh -c 'crontab -l -u % | sed "/^$/d; /^#/d; s/^/% /"' 2>/dev/null
echo
cat /etc/crontab /etc/anacrontab 2>/dev/null | sed '/^$/d; /^#/d;'
echo
run-parts --list /etc/cron.hourly;
run-parts --list /etc/cron.daily;
run-parts --list /etc/cron.weekly;
run-parts --list /etc/cron.monthly;
$ sudo ls-cron
$ sudo ~jaroslav/bin/ls-crons
jaroslav */5 * * * * mv ~/java_error_in_PHPSTORM* ~/tmp 2>/dev/null
jaroslav 5 */24 * * * ~/bin/Find-home-files
jaroslav * 7 * * * cp /T/fortrabbit/ssh-config/fapps.tsv /home/jaroslav/reference/fortrabbit/fapps
jaroslav */8 1 * * * make -C /T/fortrabbit/ssh-config discover-apps # >/dev/null
jaroslav */7 * * * * getmail -r jazzoslav -r fortrabbit 2>/dev/null
jaroslav */1 * * * * /home/jaroslav/bin/checkmail
jaroslav * 9-18 * * * getmail -r fortrabbit 2>/dev/null
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
RANDOM_DELAY=45
START_HOURS_RANGE=3-22
1 5 cron.daily nice run-parts /etc/cron.daily
7 25 cron.weekly nice run-parts /etc/cron.weekly
@monthly 45 cron.monthly nice run-parts /etc/cron.monthly
/etc/cron.hourly/0anacron
/etc/cron.daily/logrotate
/etc/cron.daily/man-db
/etc/cron.daily/mlocate
/etc/cron.weekly/mdadm
/etc/cron.weekly/pfl
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
/etc/cron.hourly/btrfs-quota-cleanup
/etc/cron.hourly/ntpdate-debian
/etc/cron.daily/apport
/etc/cron.daily/apt-compat
/etc/cron.daily/apt-show-versions
/etc/cron.daily/aptitude
/etc/cron.daily/bsdmainutils
/etc/cron.daily/dpkg
/etc/cron.daily/logrotate
/etc/cron.daily/man-db
/etc/cron.daily/mlocate
/etc/cron.daily/passwd
/etc/cron.daily/popularity-contest
/etc/cron.daily/ubuntu-advantage-tools
/etc/cron.daily/update-notifier-common
/etc/cron.daily/upstart
/etc/cron.weekly/apt-xapian-index
/etc/cron.weekly/man-db
/etc/cron.weekly/update-notifier-common
Ubuntu:
Gentoo:
As mentioned elsewhere, you can just iterate over the array and it will produce all results in order across all dimensions. However, if you want to know the indices as well, then how about using this - http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
then doing something like:
var dimensionLengthRanges = Enumerable.Range(0, myArray.Rank).Select(x => Enumerable.Range(0, myArray.GetLength(x)));
var indicesCombinations = dimensionLengthRanges.CartesianProduct();
foreach (var indices in indicesCombinations)
{
Console.WriteLine("[{0}] = {1}", string.Join(",", indices), myArray.GetValue(indices.ToArray()));
}
mysql -uroot -psecret mysql < mydatabase.sql
To answer the first:
UPDATE Orders SET Quantity = Quantity + 1 WHERE ...
To answer the second:
There are several ways to do this. Since you did not specify a database, I will assume MySQL.
INSERT INTO table SET x=1, y=2 ON DUPLICATE KEY UPDATE x=x+1, y=y+2
REPLACE INTO table SET x=1, y=2
They both can handle your question. However, the first syntax allows for more flexibility to update the record rather than just replace it (as the second one does).
Keep in mind that for both to exist, there has to be a UNIQUE key defined...
Verify that Postgres is running using:
ps -ef | grep postgres
root@959dca34cc6d:/var/lib/edb# ps -ef|grep postgres
enterpr+ 476 1 0 06:38 ? 00:00:00 /usr/lib/edb-as/11/bin/edb-postgres -D /var/lib/edb-as/11/main2 -c config_file=/etc/edb-as/11/main2/postgresql.conf
Check for data directory and postgresql.conf
.
In my case data directory in -D
was different than that in postgresql.conf
So I changed the data directory in postgresql.conf
and it worked.
You could do this
Assembly asm = Assembly.GetExecutingAssembly();
string path = System.IO.Path.GetDirectoryName(asm.Location);
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
Is it possible to simulate abstract base class in JavaScript?
Certainly. There are about a thousand ways to implement class/instance systems in JavaScript. Here is one:
// Classes magic. Define a new class with var C= Object.subclass(isabstract),
// add class members to C.prototype,
// provide optional C.prototype._init() method to initialise from constructor args,
// call base class methods using Base.prototype.call(this, ...).
//
Function.prototype.subclass= function(isabstract) {
if (isabstract) {
var c= new Function(
'if (arguments[0]!==Function.prototype.subclass.FLAG) throw(\'Abstract class may not be constructed\'); '
);
} else {
var c= new Function(
'if (!(this instanceof arguments.callee)) throw(\'Constructor called without "new"\'); '+
'if (arguments[0]!==Function.prototype.subclass.FLAG && this._init) this._init.apply(this, arguments); '
);
}
if (this!==Object)
c.prototype= new this(Function.prototype.subclass.FLAG);
return c;
}
Function.prototype.subclass.FLAG= new Object();
var cat = new Animal('cat');
That's not really an abstract base class of course. Do you mean something like:
var Animal= Object.subclass(true); // is abstract
Animal.prototype.say= function() {
window.alert(this._noise);
};
// concrete classes
var Cat= Animal.subclass();
Cat.prototype._noise= 'meow';
var Dog= Animal.subclass();
Dog.prototype._noise= 'bark';
// usage
var mycat= new Cat();
mycat.say(); // meow!
var mygiraffe= new Animal(); // error!
How about some Regex?
I wrote this for a text a file, but I believe this could work for you
(In case your text file contains line starting exactly with the "matched" ones below - simply adapt your Regex)
private static List<string> fileUploadRequestParser(Stream stream)
{
//-----------------------------111111111111111
//Content-Disposition: form-data; name="file"; filename="data.txt"
//Content-Type: text/plain
//...
//...
//-----------------------------111111111111111
//Content-Disposition: form-data; name="submit"
//Submit
//-----------------------------111111111111111--
List<String> lstLines = new List<string>();
TextReader textReader = new StreamReader(stream);
string sLine = textReader.ReadLine();
Regex regex = new Regex("(^-+)|(^content-)|(^$)|(^submit)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
while (sLine != null)
{
if (!regex.Match(sLine).Success)
{
lstLines.Add(sLine);
}
sLine = textReader.ReadLine();
}
return lstLines;
}
As you see, that's actually a natural error ..
A typical construct for reading from an Unpickler object would be like this ..
try:
data = unpickler.load()
except EOFError:
data = list() # or whatever you want
EOFError is simply raised, because it was reading an empty file, it just meant End of File ..
just tested doing this and it seems to work in firefox & IE
<html>
<head>
<script type="text/javascript">
function alertFilename()
{
var thefile = document.getElementById('thefile');
alert(thefile.value);
}
</script>
</head>
<body>
<form>
<input type="file" id="thefile" onchange="alertFilename()" />
<input type="button" onclick="alertFilename()" value="alert" />
</form>
</body>
</html>
Also remember that it must be:
#include "stdafx.h"
#include <iostream>
and not the other way around
#include <iostream>
#include "stdafx.h"
studying the above answers almost worked for me ... but I still had a problem that I could 'fling' the view on 2.1 (seemed to be fixed with 2.2 & 2.3).
here is my final solution
public class MyWebView extends WebView
{
private boolean bAllowScroll = true;
@SuppressWarnings("unused") // it is used, just java is dumb
private long downtime;
public MyWebView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void setAllowScroll(int allowScroll)
{
bAllowScroll = allowScroll!=0;
if (!bAllowScroll)
super.scrollTo(0,0);
setHorizontalScrollBarEnabled(bAllowScroll);
setVerticalScrollBarEnabled(bAllowScroll);
}
@Override
public boolean onTouchEvent(MotionEvent ev)
{
switch (ev.getAction())
{
case MotionEvent.ACTION_DOWN:
if (!bAllowScroll)
downtime = ev.getEventTime();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (!bAllowScroll)
{
try {
Field fmNumSamples = ev.getClass().getDeclaredField("mNumSamples");
fmNumSamples.setAccessible(true);
Field fmTimeSamples = ev.getClass().getDeclaredField("mTimeSamples");
fmTimeSamples.setAccessible(true);
long newTimeSamples[] = new long[fmNumSamples.getInt(ev)];
newTimeSamples[0] = ev.getEventTime()+250;
fmTimeSamples.set(ev,newTimeSamples);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
return super.onTouchEvent(ev);
}
@Override
public void flingScroll(int vx, int vy)
{
if (bAllowScroll)
super.flingScroll(vx,vy);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt)
{
if (bAllowScroll)
super.onScrollChanged(l, t, oldl, oldt);
else if (l!=0 || t!=0)
super.scrollTo(0,0);
}
@Override
public void scrollTo(int x, int y)
{
if (bAllowScroll)
super.scrollTo(x,y);
}
@Override
public void scrollBy(int x, int y)
{
if (bAllowScroll)
super.scrollBy(x,y);
}
}
Here's a cross-browser less mixin for using CSS's calc
with any property:
.calc(@prop; @val) {
@{prop}: calc(~'@{val}');
@{prop}: -moz-calc(~'@{val}');
@{prop}: -webkit-calc(~'@{val}');
@{prop}: -o-calc(~'@{val}');
}
Example usage:
.calc(width; "100% - 200px");
And the CSS that's output:
width: calc(100% - 200px);
width: -moz-calc(100% - 200px);
width: -webkit-calc(100% - 200px);
width: -o-calc(100% - 200px);
A codepen of this example: http://codepen.io/patrickberkeley/pen/zobdp
To use both is a nice answer; it's not a question of either or.
The advantage of using both is that the CSS will hide the element immediately when the page loads. The jQuery .hide will flash the element for a quarter of a second then hide it.
In the case when we want to have the element not shown when the page loads we can use CSS and set display:none & use the jQuery .hide(). If we plan to toggle the element we can use jQuery toggle.
I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)
case "$1" in
0|1) xinput set-prop 12 "Device Enabled" $1 ;;
*) echo "This script requires a 1 or 0 as first parameter." ;;
esac
No hack or js needed. Just apply the following rule to your root element:
min-height: 100%;
height: auto;
It will automatically choose the bigger one from the two as its height, which means if the content is longer than the browser, it will be the height of the content, otherwise, the height of the browser. This is standard css.
@S.Lott: You inspired me to write a timeit app.
I figured it would also vary based on the number of partitions (number of iterators within the container list) -- your comment didn't mention how many partitions there were of the thirty items. This plot is flattening a thousand items in every run, with varying number of partitions. The items are evenly distributed among the partitions.
Code (Python 2.6):
#!/usr/bin/env python2.6
"""Usage: %prog item_count"""
from __future__ import print_function
import collections
import itertools
import operator
from timeit import Timer
import sys
import matplotlib.pyplot as pyplot
def itertools_flatten(iter_lst):
return list(itertools.chain(*iter_lst))
def itertools_iterable_flatten(iter_iter):
return list(itertools.chain.from_iterable(iter_iter))
def reduce_flatten(iter_lst):
return reduce(operator.add, map(list, iter_lst))
def reduce_lambda_flatten(iter_lst):
return reduce(operator.add, map(lambda x: list(x), [i for i in iter_lst]))
def comprehension_flatten(iter_lst):
return list(item for iter_ in iter_lst for item in iter_)
METHODS = ['itertools', 'itertools_iterable', 'reduce', 'reduce_lambda',
'comprehension']
def _time_test_assert(iter_lst):
"""Make sure all methods produce an equivalent value.
:raise AssertionError: On any non-equivalent value."""
callables = (globals()[method + '_flatten'] for method in METHODS)
results = [callable(iter_lst) for callable in callables]
if not all(result == results[0] for result in results[1:]):
raise AssertionError
def time_test(partition_count, item_count_per_partition, test_count=10000):
"""Run flatten methods on a list of :param:`partition_count` iterables.
Normalize results over :param:`test_count` runs.
:return: Mapping from method to (normalized) microseconds per pass.
"""
iter_lst = [[dict()] * item_count_per_partition] * partition_count
print('Partition count: ', partition_count)
print('Items per partition:', item_count_per_partition)
_time_test_assert(iter_lst)
test_str = 'flatten(%r)' % iter_lst
result_by_method = {}
for method in METHODS:
setup_str = 'from test import %s_flatten as flatten' % method
t = Timer(test_str, setup_str)
per_pass = test_count * t.timeit(number=test_count) / test_count
print('%20s: %.2f usec/pass' % (method, per_pass))
result_by_method[method] = per_pass
return result_by_method
if __name__ == '__main__':
if len(sys.argv) != 2:
raise ValueError('Need a number of items to flatten')
item_count = int(sys.argv[1])
partition_counts = []
pass_times_by_method = collections.defaultdict(list)
for partition_count in xrange(1, item_count):
if item_count % partition_count != 0:
continue
items_per_partition = item_count / partition_count
result_by_method = time_test(partition_count, items_per_partition)
partition_counts.append(partition_count)
for method, result in result_by_method.iteritems():
pass_times_by_method[method].append(result)
for method, pass_times in pass_times_by_method.iteritems():
pyplot.plot(partition_counts, pass_times, label=method)
pyplot.legend()
pyplot.title('Flattening Comparison for %d Items' % item_count)
pyplot.xlabel('Number of Partitions')
pyplot.ylabel('Microseconds')
pyplot.show()
Edit: Decided to make it community wiki.
Note: METHODS
should probably be accumulated with a decorator, but I figure it'd be easier for people to read this way.
Hey please add code in your project,it is easy and i think will solve your problem.
int count = 10;
private void timer1_Tick(object sender, EventArgs e)
{
count--;
if (count != 0 && count > 0)
{
label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
}
else
{
label1.Text = "game over";
}
}
private void Form1_Load(object sender, EventArgs e)
{
timer1 = new System.Windows.Forms.Timer();
timer1.Interval = 1;
timer1.Tick += new EventHandler(timer1_Tick);
}
The best way to do this in my opinion is to use python's itertools
package.
>>>import itertools
>>>l1 = [1,2,3]
>>>l2 = [10,20,30]
>>>[l*2 for l in itertools.chain(*[l1,l2])]
[2, 4, 6, 20, 40, 60]
Check out this metadata extractor. It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.
EDIT metadata-extractor supports .NET too. It's a very fast and simple library for accessing metadata from images and videos.
It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ...
var directories = ImageMetadataReader.ReadMetadata(imagePath);
// print out all metadata
foreach (var directory in directories)
foreach (var tag in directory.Tags)
Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}");
// access the date time
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime);
It's available via NuGet and the code's on GitHub.
There is also at least one library for doing native threading from within Node.js: node-webworker-threads
https://github.com/audreyt/node-webworker-threads
This basically implements the Web Worker browser API for node.js.
For any Single File Component users, here is how I set up global variable(s)
Declare your variable(s) in somewhere variable.js
const shallWeUseVuex = false;
Export it in variable.js
module.exports = { shallWeUseVuex : shallWeUseVuex };
Require
and assign it in your vue file
export default {
data() {
return {
shallWeUseVuex: require('../../variable.js')
};
}
}
Ref: https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch
In a generic sense an webservice IS a API over HTTP. They often utilize JSON or XML, but there are some other approaches as well.
The missing piece for me was this:
xmlns:tools="http://schemas.android.com/tools"
for example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.your.appid">
To create a library:
File > New Module
select Android Library
To use the library add it as a dependancy:
File > Project Structure > Modules > Dependencies
Then add the module (android library) as a module dependency.
Run your project. It will work.
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
It depends how long the function is. The longer the function, the greater the chance that someone modifying it in future will write data
thinking that it means the global. In fact, it means the local, but because the function is so long, it's not obvious to them that there exists a local with that name.
For your example function, I think that shadowing the global is not bad at all.
To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.
if the IIS Manager doesn't open that means you need to install it.
So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7
Inspired by Michal B. answer. If you use bootstrap..
label.btn {_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
label.btn input {_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
label.btn span {_x000D_
text-align: center;_x000D_
padding: 6px 12px;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
label.btn input:checked+span {_x000D_
background-color: rgb(80, 110, 228);_x000D_
color: #fff;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<div>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>One</span></label>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Two</span></label>_x000D_
<label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Three</span></label>_x000D_
</div>
_x000D_
try this out :)
public static HashMap HashMapFrom(String s){
HashMap base = new HashMap(); //result
int dismiss = 0; //dismiss tracker
StringBuilder tmpVal = new StringBuilder(); //each val holder
StringBuilder tmpKey = new StringBuilder(); //each key holder
for (String next:s.split("")){ //each of vale
if(dismiss==0){ //if not writing value
if (next.equals("=")) //start writing value
dismiss=1; //update tracker
else
tmpKey.append(next); //writing key
} else {
if (next.equals("{")) //if it's value so need to dismiss
dismiss++;
else if (next.equals("}")) //value closed so need to focus
dismiss--;
else if (next.equals(",") //declaration ends
&& dismiss==1) {
//by the way you have to create something to correct the type
Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
base.put(tmpKey.toString(),ObjVal);//declaring
tmpKey = new StringBuilder();
tmpVal = new StringBuilder();
dismiss--;
continue; //next :)
}
tmpVal.append(next); //writing value
}
}
Object objVal = object.valueOf(tmpVal.toString()); //same as here
base.put(tmpKey.toString(), objVal); //leftovers
return base;
}
examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}
I also faced the same problem, and get the columns name and its types. Then cast(col_Name as Char) from table name. From this way i get the problem as '0000-00-00 00:00:00' then I Update as valid date and time the error gets away for my case.
With PHP you just can handle server-side stuff. What you can do is print this in your iframe:
parent.window.location.reload();
Instead you will receive callback on onRequestPermissionsResult()
as PERMISSION_DENIED when you request permission again while falling in false condition of shouldShowRequestPermissionRationale()
From Android doc:
When the system asks the user to grant a permission, the user has the option of telling the system not to ask for that permission again. In that case, any time an app uses requestPermissions()
to ask for that permission again, the system immediately denies the request. The system calls your onRequestPermissionsResult()
callback method and passes PERMISSION_DENIED
, the same way it would if the user had explicitly rejected your request again. This means that when you call requestPermissions()
, you cannot assume that any direct interaction with the user has taken place.
while this system does use a for loop, It uses US english and is fast, accurate, and expandable(you can add infinite values to the "th" var and they will be included).
This function grabs the 3 groups of numbers backwards so it can get the number groups where a ,
would normally separate them in the numeric form. Then each group of three numbers is added to an array with the word form of just the 3 numbers(ex: one hundred twenty three). It then takes that new array list, and reverses it again, while adding the th
var of the same index to the end of the string.
var ones = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var tens = ['', '', 'twenty ','thirty ','forty ','fifty ', 'sixty ','seventy ','eighty ','ninety ', 'hundred '];
var th = ['', 'thousand ','million ','billion ', 'trillion '];
function numberToWord(number){
var text = "";
var size = number.length;
var textList = [];
var textListCount = 0;
//get each 3 digit numbers
for(var i = number.length-1; i >= 0; i -= 3){
//get 3 digit group
var num = 0;
if(number[(i-2)]){num += number[(i-2)];}
if(number[(i-1)]){num += number[(i-1)];}
if(number[i]){num += number[i];}
//remove any extra 0's from begining of number
num = Math.floor(num).toString();
if(num.length == 1 || num < 20){
//if one digit or less than 20
textList[textListCount] = ones[num];
}else if(num.length == 2){
//if 2 digits and greater than 20
textList[textListCount] = tens[num[0]]+ones[num[1]];
}else if(num.length == 3){
//if 3 digits
textList[textListCount] = ones[num[0]]+tens[10]+tens[num[1]]+ones[num[2]];
}
textListCount++;
}
//add the list of 3 digit groups to the string
for(var i = textList.length-1; i >= 0; i--){
if(textList[i] !== ''){text += textList[i]+th[i];} //skip if the number was 0
}
return text;
}
I have the same problem and the solution was uncheck the "use ports 80 and 443" on skype advanced configuration!
Building on the brilliant logic / code from mathematix and scottyc, I submit:
DECLARE @a INT, @b INT, @c INT = 0
WHILE @c < 100
BEGIN
SET @c += 1
SET @a = ROUND(RAND()*100,0)-50
SET @b = ROUND(RAND()*100,0)-50
SELECT @a AS a, @b AS b,
@a - ( ABS(@a-@b) + (@a-@b) ) / 2 AS MINab,
@a + ( ABS(@b-@a) + (@b-@a) ) / 2 AS MAXab,
CASE WHEN (@a <= @b AND @a = @a - ( ABS(@a-@b) + (@a-@b) ) / 2)
OR (@a >= @b AND @a = @a + ( ABS(@b-@a) + (@b-@a) ) / 2)
THEN 'Success' ELSE 'Failure' END AS Status
END
Although the jump from scottyc's MIN function to the MAX function should have been obvious to me, it wasn't, so I've solved for it and included it here: SELECT @a + ( ABS(@b-@a) + (@b-@a) ) / 2. The randomly generated numbers, while not proof, should at least convince skeptics that both formulae are correct.
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3
is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
Try to test and initialize your arrays before you use them :
if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;
If $catagory[$i]
doesn't exist, you create (Uninitialized) one ... that's all ;
=> PHP try to read on your table in the address $i
, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string.
So you code is not very clean, it takes you some resources that down you server's performance (just a very little).
Take care about your MySQL tables default values
if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;
or
if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;
Set args = Wscript.Arguments
For Each arg In args
Wscript.Echo arg
Next
From a command prompt, run the script like this:
CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"
Will give results like this:
1
2
A
B
Arg with spaces
There's actually a very little known class in the BCL for this purpose exactly: CommaDelimitedStringCollectionConverter. It serves as a middle ground of sorts between having a ConfigurationElementCollection
(as in Richard's answer) and parsing the string yourself (as in Adam's answer).
For example, you could write the following configuration section:
public class MySection : ConfigurationSection
{
[ConfigurationProperty("MyStrings")]
[TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
public CommaDelimitedStringCollection MyStrings
{
get { return (CommaDelimitedStringCollection)base["MyStrings"]; }
}
}
You could then have an app.config that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="foo" type="ConsoleApplication1.MySection, ConsoleApplication1"/>
</configSections>
<foo MyStrings="a,b,c,hello,world"/>
</configuration>
Finally, your code would look like this:
var section = (MySection)ConfigurationManager.GetSection("foo");
foreach (var s in section.MyStrings)
Console.WriteLine(s); //for example
It works, this is a problem with the tool used: normalized CSS by jsFiddle is causing the problem by hiding you the default of browsers...
See http://jsfiddle.net/XvdX9/5/
EDIT:
normalize.css stylesheet from jsFiddle adds the instruction border-collapse: collapse
to all tables and it renders them completely differently in CSS2.1:
Differences between the 2 models can be seen in this other fiddle: http://jsfiddle.net/XvdX9/11/ (with some transparencies on cells and an enormous border-radius on the top-left one, in order to see what happens on table vs its cells)
In the same CSS2.1 page about HTML tables, there are also explanations about what browsers should/could do with empty-cells in the separated borders model, the difference between border-style: none
and border-style: hidden
in the collapsing borders model, how width is calculated and which border should display if both table, row and cell elements define 3 different styles on the same border.
You can't. If you add a member variable of type T to the class (you don't even have to initialise it), you could use that to recover the type.
it should be :
$_SERVER['REQUEST_URI'];
Take a look at : Get the full URL in PHP
This works for Oracle and SQL Server (you might be able to get it to work on another RDBMS):
select sum(case when a is null then 1 else 0 end) count_nulls
, count(a) count_not_nulls
from us;
Or:
select count(*) - count(a), count(a) from us;
The best way for getting input string is:
$value = filter_input(INPUT_POST, 'value');
This one-liner is almost equivalent to:
if (!isset($_POST['value'])) {
$value = null;
} elseif (is_array($_POST['value'])) {
$value = false;
} else {
$value = $_POST['value'];
}
If you absolutely want string value, just like:
$value = (string)filter_input(INPUT_POST, 'value');
When you are using curl
sometimes give you 403 (access forbidden)
Solved by adding this line to emulate browser.
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
Hope this help someone.
I think this would be best explained by the following picture:
To initialize the above, one would type:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
As JoshC said, the class .sr-only
is used to visually hide the information used for screen readers only. But not only to hide labels. You might consider hiding various other elements such as "skip to main content" link, icons which have an alternative texts etc.
BTW. you can also use .sr-only sr-only-focusable
if you need the element to become visible when focused e.g. "skip to main content"
If you want make your website even more accessible I recommend to start here:
Why?
According to the World Health Organization, 285 million people have vision impairments. So making a website accessible is important.
IMPORTANT: Avoid treating disabled users differently. Generally speaking try to avoid developing a different content for different groups of users. Instead try to make accessible the existing content so that it simply works out-of-the-box and for all not specifically targeting e.g. screen readers. In other words don't try to reinvent the wheel. Otherwise the resulting accessibility will often be worse than if there was nothing developed at all. We developers should not assume how those users will use our website. So be very careful when you need to develop such solutions. Obviously a "skip link" is a good example of such content if it's made visible when focused. But there many bad examples too. Such would be hiding from a screen reader a "zoom" button on the map assuming that it has no relevance to blind users. But surprisingly, a zoom function indeed is used among blind users! They like to download images like many other users do (even in high resolution), for sending them to somebody else or for using them in some other context. Source - Read more @ADG: Bad ARIA practices
There are a few issues here that aren't covered by any of the other answers.
First, id
only returns:
the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same
id()
value.
In CPython, this happens to be the pointer to the PyObject
that represents the object in the interpreter, which is the same thing that object.__repr__
displays. But this is just an implementation detail of CPython, not something that's true of Python in general. Jython doesn't deal in pointers, it deals in Java references (which the JVM of course probably represents as pointers, but you can't see those—and wouldn't want to, because the GC is allowed to move them around). PyPy lets different types have different kinds of id
, but the most general is just an index into a table of objects you've called id
on, which is obviously not going to be a pointer. I'm not sure about IronPython, but I'd suspect it's more like Jython than like CPython in this regard. So, in most Python implementations, there's no way to get whatever showed up in that repr
, and no use if you did.
But what if you only care about CPython? That's a pretty common case, after all.
Well, first, you may notice that id
is an integer;* if you want that 0x2aba1c0cf890
string instead of the number 46978822895760
, you're going to have to format it yourself. Under the covers, I believe object.__repr__
is ultimately using printf
's %p
format, which you don't have from Python… but you can always do this:
format(id(spam), '#010x' if sys.maxsize.bit_length() <= 32 else '#18x')
* In 3.x, it's an int
. In 2.x, it's an int
if that's big enough to hold a pointer—which is may not be because of signed number issues on some platforms—and a long
otherwise.
Is there anything you can do with these pointers besides print them out? Sure (again, assuming you only care about CPython).
All of the C API functions take a pointer to a PyObject
or a related type. For those related types, you can just call PyFoo_Check
to make sure it really is a Foo
object, then cast with (PyFoo *)p
. So, if you're writing a C extension, the id
is exactly what you need.
What if you're writing pure Python code? You can call the exact same functions with pythonapi
from ctypes
.
Finally, a few of the other answers have brought up ctypes.addressof
. That isn't relevant here. This only works for ctypes
objects like c_int32
(and maybe a few memory-buffer-like objects, like those provided by numpy
). And, even there, it isn't giving you the address of the c_int32
value, it's giving you the address of the C-level int32
that the c_int32
wraps up.
That being said, more often than not, if you really think you need the address of something, you didn't want a native Python object in the first place, you wanted a ctypes
object.
What onetrickpony
posted is okay, but if you want to have a more general solution, you can just use the code below.
Instead of selecting just the id
of the anchor, you can make it bit more standard-like and just selecting the attribute name
of the <a>
-Tag. This will save you from writing an extra id
tag. Just add the smoothscroll class to the navbar element.
What changed
1) $('#nav ul li a[href^="#"]')
to $('#nav.smoothscroll ul li a[href^="#"]')
2) $(this.hash)
to $('a[name="' + this.hash.replace('#', '') + '"]')
Final Code
/* Enable smooth scrolling on all links with anchors */
$('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});
Use a CipherOutputStream
or CipherInputStream
with a Cipher
and your FileInputStream
/ FileOutputStream
.
I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding")
for creating the Cipher
class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.
Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.
If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.
Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes()
but use String.getBytes(StandardCharsets.UTF_8)
.
To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.
Be warned that CipherInputStream
may not report BadPaddingException
, this includes BadPaddingException
generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.
import numpy as np
import pandas as pd
import scipy.sparse as sparse
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)
yields
0 1 2 newcol
0 1 2 3 [0, 1, 0]
1 4 5 6 [0, 0, 1]
2 7 8 9 [1, 0, 0]
Based on what I understand from the latest git documentation, the synopsis is:
git branch -u upstream-branch local-branch
git branch --set-upstream-to=upstream-branch local-branch
This usage seems to be a bit different than urschrei's answer, as in his the synopsis is:
git branch local-branch -u upstream-branch
git branch local-branch --set-upstream-to=upstream-branch
I'm guessing they changed the documentation again?
Lets go through basic definition of typedef. typedef use to define an alias to an existing data type either it is user defined or inbuilt.
typedef <data_type> <alias>;
for example
typedef int scores;
scores team1 = 99;
Confusion here is with the self referential structure, due to a member of same data type which is not define earlier. So In standard way you can write your code as :-
//View 1
typedef struct{ bool isParent; struct Cell* child;} Cell;
//View 2
typedef struct{
bool isParent;
struct Cell* child;
} Cell;
//Other Available ways, define stucture and create typedef
struct Cell {
bool isParent;
struct Cell* child;
};
typedef struct Cell Cell;
But last option increase some extra lines and words with usually we don't want to do (we are so lazy you know ;) ) . So prefer View 2.
try: window.document......
var body = window.document.getElementsByTagName("body")[0];
Full Example (Python 3):
For Python 2.x look into Note below
import re
mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)
Prints:
['cat', 'wildcat', 'thundercat']
Note:
For Python 2.x developers, filter
returns a list already. In Python 3.x filter
was changed to return an iterator so it has to be converted to list
(in order to see it printed out nicely).
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
SELECT * FROM (SELECT * FROM tb1 ORDER BY signin DESC) GROUP BY id;
There's an excellent plugin called ApplySyntax (previously DetectSyntax) that provides certain other niceties for file-syntax matching. allows regex expressions etc.
Accepted answer throws a java.lang.StackOverflowError
when calling the setParent
or addChild
methods.
Here's a slightly simpler implementation without those bugs:
public class MyTreeNode<T>{
private T data = null;
private List<MyTreeNode> children = new ArrayList<>();
private MyTreeNode parent = null;
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode child) {
child.setParent(this);
this.children.add(child);
}
public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<>(data);
this.addChild(newChild);
}
public void addChildren(List<MyTreeNode> children) {
for(MyTreeNode t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public List<MyTreeNode> getChildren() {
return children;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
private void setParent(MyTreeNode parent) {
this.parent = parent;
}
public MyTreeNode getParent() {
return parent;
}
}
Some examples:
MyTreeNode<String> root = new MyTreeNode<>("Root");
MyTreeNode<String> child1 = new MyTreeNode<>("Child1");
child1.addChild("Grandchild1");
child1.addChild("Grandchild2");
MyTreeNode<String> child2 = new MyTreeNode<>("Child2");
child2.addChild("Grandchild3");
root.addChild(child1);
root.addChild(child2);
root.addChild("Child3");
root.addChildren(Arrays.asList(
new MyTreeNode<>("Child4"),
new MyTreeNode<>("Child5"),
new MyTreeNode<>("Child6")
));
for(MyTreeNode node : root.getChildren()) {
System.out.println(node.getData());
}
I think the easiest way is through the collections module.
import collections
FinanceCtaCteM = collections.namedtuple('FinanceCtaCte', 'forma_pago doc_pago get_total')
def get_total(): return 98989898
financtacteobj = FinanceCtaCteM(forma_pago='CONTADO', doc_pago='EFECTIVO',
get_total=get_total)
print financtacteobj.get_total()
print financtacteobj.forma_pago
print financtacteobj.doc_pago
Might help some else - I came here because I missed putting two // after http:. This is what I had:
http:/abc.my.domain.com:55555/update
My experience is that today a lot of developers use async/await
as a default for controllers.
My suggestion would be, use it only when you know it will help you.
The reason is, as Stephen Cleary and others already mentioned, it can introduce performance issues, rather than resolving them, and it will help you only in a specific scenario:
setTimeout(expression, timeout);
runs the code/function once after the timeout.
setInterval(expression, timeout);
runs the code/function in intervals, with the length of the timeout between them.
Example:
var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.
setTimeout(alert, 1000); // Will alert once, after a second.
use this one
int number = (int) Double.parseDouble(s);
You're looking for the OpenFileDialog
class.
For example:
Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
Using dialog As New OpenFileDialog
If dialog.ShowDialog() <> DialogResult.OK Then Return
File.Copy(dialog.FileName, newPath)
End Using
End Sub
In case someone is feverishly googling to solve the bouncing images carousel thing, this helped me:
.fusion-carousel .fusion-carousel-item img {
width: auto;
height: 146px;
max-height: 146px;
object-fit: contain;
}
This should format a field in an SQL query:
SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
If you want a string mm/dd/yyyy
instead of the datetime
object, you can use strftime
(string format time):
>>> dt.datetime.today().strftime("%m/%d/%Y")
# ^ note parentheses
'02/12/2014'
In SQL Server 2012 and above, you don't need to create a link. You can execute directly
SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET
I don't know whether previous versions of SQL Server work as well
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
Here is a working example for strict json parsing with gson library:
public static JsonElement parseStrict(String json) {
// throws on almost any non-valid json
return new Gson().getAdapter(JsonElement.class).fromJson(json);
}
See also my other detailed answer in How to check if JSON is valid in Java using GSON with more info and extended test case with various non-valid examples.
At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.
Thats why it always -ve.
Using 2nd signature of $.fn.removeClass
:
// Considering:
var $el = $('<div class=" foo-1 a b foo-2 c foo"/>');
function makeRemoveClassHandler(regex) {
return function (index, classes) {
return classes.split(/\s+/).filter(function (el) {return regex.test(el);}).join(' ');
}
}
$el.removeClass(makeRemoveClassHandler(/^foo-/));
//> [<div class=?"a b c foo">?</div>?]
My code to solve this problem:
private void sendMail()
{
//This list can be a parameter of metothd
List<MailAddress> lst = new List<MailAddress>();
lst.Add(new MailAddress("[email protected]"));
lst.Add(new MailAddress("[email protected]"));
lst.Add(new MailAddress("[email protected]"));
lst.Add(new MailAddress("[email protected]"));
try
{
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "10.15.130.28"; //or SMTP name
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
objeto_mail.From = new MailAddress("[email protected]");
//add each email adress
foreach (MailAddress m in lst)
{
objeto_mail.To.Add(m);
}
objeto_mail.Subject = "Sending mail test";
objeto_mail.Body = "Functional test for automatic mail :-)";
client.Send(objeto_mail);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Though this might be too late to comment but here's the working code for problems such as yours.
<div id="player">
<audio autoplay hidden>
<source src="link/to/file/file.mp3" type="audio/mpeg">
If you're reading this, audio isn't supported.
</audio>
</div>
Yes, though you have to turn on TLS 1.2 manually at System.Net.ServicePointManager.SecurityProtocol
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; // comparable to modern browsers
var response = WebRequest.Create("https://www.howsmyssl.com/").GetResponse();
var body = new StreamReader(response.GetResponseStream()).ReadToEnd();
Your client is using TLS 1.2, the most modern version of the encryption protocol
Out the box, WebRequest will use TLS 1.0 or SSL 3.
Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.
You can remove this by adding !important to your outline.
button{
outline: none !important;
}
Your concatenation syntax is correct.
Most likely the callback function isn't even being called. You can test that by putting an alert()
, console.log()
or debugger
line in that function.
If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()
handler after $.post()
to find out what the error is, e.g.:
$.post('ajaxskeleton.php', {
red: text
}, function(){
$('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(arguments);
});
The answer here is not clear, so I wanted to add more detail.
Using the link provided above, I performed the following step.
In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.
This information is available at the link the OP posted in the Answer.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
It's the ternary form of the if-else operator. The above statement basically reads like this:
if ($add_review) then {
return FALSE; //$add_review evaluated as True
} else {
return $arg //$add_review evaluated as False
}
See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/
It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.
see this link:
http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server
somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...
If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.
Try something like
"Line 1" & Environment.NewLine & "Line 2"
If you don't want to type, you can create the statements with this:
USE Databasename
SELECT 'DROP TABLE [' + name + '];'
FROM sys.tables
Then copy and paste into a new SSMS window to run it.
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
You should use append to add to the list. But also here are few code tips:
I would use dict.setdefault
or defaultdict
to avoid having to specify the empty list in the dictionary definition.
If you use prev
to to filter out duplicated values you can simplfy the code using groupby
from itertools
Your code with the amendments looks as follows:
import itertools
def make_drug_dictionary(data):
drug_dictionary = {}
for key, row in itertools.groupby(data, lambda x: x[11]):
drug_dictionary.setdefault(key,[]).append(row[?])
return drug_dictionary
If you don't know how groupby works just check this example:
>>> list(key for key, val in itertools.groupby('aaabbccddeefaa'))
['a', 'b', 'c', 'd', 'e', 'f', 'a']
you have enlosed start_date
with single quote causing it to become string, use backtick
instead
SELECT * FROM `la_schedule` WHERE `start_date` > '2012-11-18';
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>
You can use CSS3 transition
Some good links:
http://css-tricks.com/different-transitions-for-hover-on-hover-off/
http://www.alistapart.com/articles/understanding-css3-transitions/
Yes you have the syntax error. If you want to get your Javascript errors and printing statements in your logcat you must implement the onConsoleMessage(ConsoleMessage cm)
method in your WebChromeClient. It gives the complete stack traces like Web console(Inspect element). Here is the method.
public boolean onConsoleMessage(ConsoleMessage cm)
{
Log.d("Message", cm.message() + " -- From line "
+ cm.lineNumber() + " of "
+ cm.sourceId() );
return true;
}
After implementation you will get your Javascript errors and print statements (console.log
) on your logcat.
A simple way of reading variables from a text file using the standard library:
# Get vars from conf file
var = {}
with open("myvars.conf") as conf:
for line in conf:
if ":" in line:
name, value = line.split(":")
var[name] = str(value).rstrip()
globals().update(var)
A procedure can't return a table as such. However you can select from a table in a procedure and direct it into a table (or table variable) like this:
create procedure p_x
as
begin
declare @t table(col1 varchar(10), col2 float, col3 float, col4 float)
insert @t values('a', 1,1,1)
insert @t values('b', 2,2,2)
select * from @t
end
go
declare @t table(col1 varchar(10), col2 float, col3 float, col4 float)
insert @t
exec p_x
select * from @t
ALLOWED_HOSTS is NOT the only issue, for me I had to make a 404.html and put it in the base level of my templates (not app level) - Also, you can make a 404 view and add a 404handler url but I think thats optional. 404.html fixed it
in mainproject.urls
handler404 = 'app.views.custom_404'
in app.views
def custom_404(request):
return render(request, '404.html', {}, status=404)
then make a templates/404.html template
got this from another S/O post that I cannot find it
EDIT
also, I get 500 errors when I serve assets with whitenoise. Could not figure that out for the life of me, error was ValueError from whitenoise not being able to find an asset that I also could not find, had to go with default django serving for now
There may be a better solution, but this is what came to mind:
var value = $("#yourInput").val();
$("#yourInput").on('keyup change click', function () {
if(this.value !== value) {
value = this.value;
//Do stuff
}
});
Here's a working example.
It simply binds an event handler to the keyup
, change
and click
events. It checks whether or not the value has changed, and if so, stores the current value so it can check again next time. The check is required to deal with the click
event.
Most of these answers involve the math, decimal and/or numpy imports or output values as strings. Here is a simple solution in base python that handles both large and small numbers and outputs a float:
def sig_fig_round(number, digits=3):
power = "{:e}".format(number).split('e')[1]
return round(number, -(int(power) - digits))
Jscript is a .NET language similar to C#, with the same capabilities and access to all the .NET functions.
JavaScript is run on the ASP Classic server. Use Classic ASP to run the same JavaScript that you have on the Client (excluding HTML5 capabilities). I only have one set of code this way for most of my code.
I run .ASPX JScript when I require Image and Binary File functions, (among many others) that are not in Classic ASP. This code is unique for the server, but extremely powerful.
I needed to move data from a sql server compact database to sqlite, so using sql server 2008 you can right click on the table and select 'Script Table To' and then 'Data to Inserts'. Copy the insert statements remove the 'GO' statements and it executed successfully when applied to the sqlite database using the 'DB Browser for Sqlite' app.
Try this one:
#!/bin/bash
find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
Execute it with the path to the directory where it should start scanning recursively (it supports filenames with spaces).
If there are lots of files it may take a while before it returns anything. Performance can be improved if we use xargs
instead:
#!/bin/bash
find $1 -type f -print0 | xargs -0 stat --format '%Y :%y %n' | sort -nr | cut -d: -f2- | head
which is a bit faster.
For me this solution works perfectly fine...
HTML
<h2 class="strikethough"><span>Testing Text</span></h2>
CSS
.strikethough {
width:100%;
text-align:left;
border-bottom: 1px solid #bcbcbc;
overflow: inherit;
margin:0px 0 30px;
font-size: 16px;
color:#757575;
}
.strikethough span {
background:#fff;
padding:0 20px 0px 0px;
position: relative;
top: 10px;
}
You need both a value and a field to assign it to. The value is TableField + 1
, so the assignment is:
SET TableField = TableField + 1
It's also worth referencing this Bluebird promises library wiki page that shows how to manage the arguments
object into array in a way that makes the function optimizable under V8 JavaScript engine:
function doesntLeakArguments() {
var args = new Array(arguments.length);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
return args;
}
This method is used in favor of var args = [].slice.call(arguments);
. The author also shows how a build step can help reduce the verbosity.
you can use the new push/pop state functions in the history manipulation API.
In my case, I was getting this error message only in Production but not when run locally, even though my application's binaries were identical.
In my application, I'm using a custom DbModelStore
so that the runtime-generated EDMX is saved to disk and loaded from disk on startup (instead of regenerating it from scratch) to reduce application startup time - and due to a bug in my code I wasn't invalidating the EDMX file on-disk - so Production was using an older version of the EDMX file from disk that referenced an older version of my application's types from before I renamed the type-name in the exception error message.
Deleting the cache file and restarting the application fixed it.
How about using the official instructions from the nodejs site:
For v7:
curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs
For v6:
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
For v4:
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs
I've tested these from Windows bash (via subsystem for Linux - 14.04) and raspbian (ARM Debian based). Running sudo apt-get install -y nodejs
without first running the setup script will result in you getting node 0.10.
If you are planning on installing native npm modules requiring build, also run:
sudo apt install -y build-essential
Note: this is the recommended path for any Debian based distro across all architectures.
Newtonsoft.JSON
is a good solution for these kind of situations. Also Newtonsof.JSON
is faster than others, such as JavaScriptSerializer
, DataContractJsonSerializer
.
In this sample, you can the following:
var jsonData = JObject.Parse("your JSON data here");
Then you can cast jsonData to JArray
, and you can use a for
loop to get data at each iteration.
Also, I want to add something:
for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
var data = jsonData[i - 1];
}
Working with dynamic object and using Newtonsoft serialize is a good choice.
python manage.py createsuperuser
will create another superuser, you will be able to log into admin and rememder your username.To give a normal user privileges, open a shell with python manage.py shell
and try:
from django.contrib.auth.models import User
user = User.objects.get(username='normaluser')
user.is_superuser = True
user.save()
With jQuery
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
http://api.jquery.com/event.which/
jQuery('#input').on('keydown', function(e) {
if( e.which == 8 || e.which == 46 ) return false;
});
Use Observable pattern. You can put Observable value (not Subject) into Input parameter and manage it from parent component. You do not need callback function.
See example: https://stackoverflow.com/a/49662611/4604351
You don't need the class reference for the li
s. Instead of having CSS like
li.top-level-nav { color:black; }
you can write
ul#sidebar > li { color:black; }
This will apply the styling only to li
s that immediately descend from the sidebar ul
.
I use this subtle alias:
alias vim='gnome-terminal -- vim'
-x is deprecated now. We need to use -- instead
aliases can and can't process piped stdin...
Here we create 3 lines of output
$ echo -e "line 1\nline 2\nline 3"
line 1
line 2
line 3
We then pipe the output to stdin of the sed command to put them all on one line
$ echo -e "line 1\nline 2\nline 3" | sed -e ":a;N;\$!ba ;s?\n? ?g"
line 1 line 2 line 3
If we define an alias of the same sed command
$ alias oline='sed -e ":a;N;\$!ba ;s?\n? ?g"'
We can pipe the output to the stdin of the alias and it behaves exactly the same
$ echo -e "line 1\nline 2\nline 3" | oline
line 1 line 2 line 3
The problem arises when we try to define the alias as a function
$ alias oline='function _oline(){ sed -e ":a;N;\$!ba ;s?\n? ?g";}_oline'
Defining the alias as a funstion breaks the pipe
$ echo -e "line 1\nline 2\nline 3" | oline
>
I too faced the above problem with phyton 3 while setting up python for machine learning.
I followed the below steps :-
Install python-2.7.13.msi
• set PATH=C:\Python27
• set PATH=C:\Python27\Scripts
Go to http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
Downloaded:- -- numpy-1.13.1+mkl-cp27-cp27m-win32.whl
--scipy-0.18.0-cp27-cp27m-win32.whl
Installing numpy: pip install numpy-1.13.1+mkl-cp27-cp27m-win32.whl
Installing scipy: pip install scipy-0.18.0-cp27-cp27m-win32.whl
You can test the correctness using below cmds:-
>>> import numpy
>>> import scipy
>>> import sklearn
>>> numpy.version.version
'1.13.1'
>>> scipy.version.version
'0.19.1'
>>>
In Java 7 you can do this:
String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());
There is more info here: http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
You need to load the helper before loading the view somewhere in your controller.
But I think here you want to use the function site_url()
Before you load your view, basically anywhere inside the method in your controller, add this to your code :
$this->load->helper('url');
Then use the function site_url()
.
PHP can be frustrating for this reason. The answers above using global
did not work for me, and it took me awhile to figure out the proper use of use
.
This is correct:
$functionName = function($stuff) use ($globalVar) {
//do stuff
}
$output = $functionName($stuff);
$otherOutput = $functionName($otherStuff);
This is incorrect:
function functionName($stuff) use ($globalVar) {
//do stuff
}
$output = functionName($stuff);
$otherOutput = functionName($otherStuff);
Using your specific example:
$data = 'My data';
$menugen = function() use ($data) {
echo "[" . $data . "]";
}
$menugen();
You need to include iostream
#include <iostream>
using namespace std;
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".
save and open in excel, try refresh data and excel will be monit about parameters.
Use font
property of UILabel
:
label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
or use default system font
to bold text:
label.font = UIFont.boldSystemFont(ofSize: 16.0)
Either something like this:
"abc" + str(9)
or
"abs{0}".format(9)
or
"abs%d" % (9,)
awk '{ sub("[^a-zA-Z0-9\"!@#$%^&*|_\[](){}", ""); print }' MYinputfile.txt > pipe_out_to_CONVERTED_FILE.txt
If you use "Git for Windows"
>cd c:\Program Files\Git\etc\ssh\
add to ssh_config following:
AddKeysToAgent yes
IdentityFile ~/.ssh/id_rsa
IdentityFile ~/.ssh/id_rsa_test
ps. you need ssh version >= 7.2 (date of release 2016-02-28)
In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.
Division of two numbers using bitwise operators.
#include <stdio.h>
int remainder, divisor;
int division(int tempdividend, int tempdivisor) {
int quotient = 1;
if (tempdivisor == tempdividend) {
remainder = 0;
return 1;
} else if (tempdividend < tempdivisor) {
remainder = tempdividend;
return 0;
}
do{
tempdivisor = tempdivisor << 1;
quotient = quotient << 1;
} while (tempdivisor <= tempdividend);
/* Call division recursively */
quotient = quotient + division(tempdividend - tempdivisor, divisor);
return quotient;
}
int main() {
int dividend;
printf ("\nEnter the Dividend: ");
scanf("%d", ÷nd);
printf("\nEnter the Divisor: ");
scanf("%d", &divisor);
printf("\n%d / %d: quotient = %d", dividend, divisor, division(dividend, divisor));
printf("\n%d / %d: remainder = %d", dividend, divisor, remainder);
getch();
}
The simplest way would be to add the pull-left
class to your dropdown-submenu
<li class="dropdown-submenu pull-left">
jsfiddle: DEMO
If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:
# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
# dimensions of our images
img_width, img_height = 320, 240
# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes
# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)
# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)
# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]