I put this into a jQuery plugin to make it more modular (you supply the transparent gif):
$.fn.pngFix = function() {
if (!$.browser.msie || $.browser.version >= 9) { return $(this); }
return $(this).each(function() {
var img = $(this),
src = img.attr('src');
img.attr('src', '/images/general/transparent.gif')
.css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + src + "')");
});
};
Usage:
$('.my-selector').pngFix();
Note: It works also if your images are background images. Just apply the function on the div.
echo ($result ->vocation == 1) ? 'Sorcerer'
: ($result->vocation == 2) ? 'Druid'
: ($result->vocation == 3) ? 'Paladin'
....
;
It’s kind of ugly. You should stick with normal if
statements.
Match against /^\d+$/
. $
means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
Edit:
RobG wisely suggests the more succinct /\D/.test(z)
. This operation tests the inverse of what you want. It returns true
if the input has any non-numeric characters.
Simply omit the negating !
and use if(/\D/.test(z))
.
Nobody mentioned the limit on the size of the stack frame.
There are two places memory can be allocated:
Thus if you allocate an array dynamically (the limit is large and described in detail by other posts.
int* a1 = new int[SIZE]; // SIZE limited only by OS/Hardware
Alternatively if the array is allocated on the stack then you are limited by the size of the stack frame. N.B. vectors and other containers have a small presence in the stack but usually the bulk of the data will be on the heap.
int a2[SIZE]; // SIZE limited by COMPILER to the size of the stack frame
Code
import java.util.Scanner;
public class LoginMain {
public static void main(String[] args) {
String Username;
String Password;
Password = "123";
Username = "wisdom";
Scanner input1 = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Enter Password : ");
String password = input2.next();
if (username.equals(Username) && password.equals(Password)) {
System.out.println("Access Granted! Welcome!");
}
else if (username.equals(Username)) {
System.out.println("Invalid Password!");
} else if (password.equals(Password)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Invalid Username & Password!");
}
}
}
Use CSS: overflow:
.thumb {
width:230px;
height:230px;
overflow:hidden
}
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean
You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:
NSDictionary* userInfo = @{@"total": @(messageTotal)};
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];
On the receiving end you can access the userInfo dictionary as follows:
-(void) receiveTestNotification:(NSNotification*)notification
{
if ([notification.name isEqualToString:@"TestNotification"])
{
NSDictionary* userInfo = notification.userInfo;
NSNumber* total = (NSNumber*)userInfo[@"total"];
NSLog (@"Successfully received test notification! %i", total.intValue);
}
}
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
Go to system preferences, then "MySQL". Click on "Start MySQL Server".
Please see this sample implementation of filter
to understand how it works in Python 3:
def my_filter(function, iterable):
"""my_filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true."""
if function is None:
return (item for item in iterable if item)
return (item for item in iterable if function(item))
The following is an example of how you might use filter
or my_filter
generators:
>>> greetings = {'hello'}
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye'))
>>> print('\n'.join(spoken))
hello
It turns out that I needed to use gulp-rename
and also output the concatenated file first before 'uglification'. Here's the code:
var gulp = require('gulp'),
gp_concat = require('gulp-concat'),
gp_rename = require('gulp-rename'),
gp_uglify = require('gulp-uglify');
gulp.task('js-fef', function(){
return gulp.src(['file1.js', 'file2.js', 'file3.js'])
.pipe(gp_concat('concat.js'))
.pipe(gulp.dest('dist'))
.pipe(gp_rename('uglify.js'))
.pipe(gp_uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['js-fef'], function(){});
Coming from grunt
it was a little confusing at first but it makes sense now. I hope it helps the gulp
noobs.
And, if you need sourcemaps, here's the updated code:
var gulp = require('gulp'),
gp_concat = require('gulp-concat'),
gp_rename = require('gulp-rename'),
gp_uglify = require('gulp-uglify'),
gp_sourcemaps = require('gulp-sourcemaps');
gulp.task('js-fef', function(){
return gulp.src(['file1.js', 'file2.js', 'file3.js'])
.pipe(gp_sourcemaps.init())
.pipe(gp_concat('concat.js'))
.pipe(gulp.dest('dist'))
.pipe(gp_rename('uglify.js'))
.pipe(gp_uglify())
.pipe(gp_sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['js-fef'], function(){});
See gulp-sourcemaps for more on options and configuration.
I have the same issue, I solved the problem, just disabled
"BranchCache Service" in services.
Somehow windows updates, this service is triggered in startup, and uses 80 ports. When you check via netstat you could see the system is used this but couldnt understand which service is used.
You can change the value in the XML like this:
<Button
android:background="#FFFFFF"
../>
Here, you can add any other color, from the resources or hex.
Similarly, you can also change these values form the code like this:
demoButton.setBackgroundColor(Color.WHITE);
Another easy way is to make a drawable, customize the corners and shape according to your preference and set the background color and stroke of the drawable. For eg.
button_background.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dp" android:color="#ff207d94" />
<corners android:radius="5dp" />
<solid android:color="#FFFFFF" />
</shape>
And then set this shape as the background of your button.
<Button
android:background="@drawable/button_background.xml"
../>
Hope this helps, good luck!
What about cases where you want to reuse the name of a property, for example when throwing exception based on a property name, or handling a PropertyChanged
event. There are numerous cases where you would want to have the name of the property.
Take this example:
switch (e.PropertyName)
{
case nameof(SomeProperty):
{ break; }
// opposed to
case "SomeOtherProperty":
{ break; }
}
In the first case, renaming SomeProperty
will change the name of the property too, or it will break compilation. The last case doesn't.
This is a very useful way to keep your code compiling and bug free (sort-of).
(A very nice article from Eric Lippert why infoof
didn't make it, while nameof
did)
sys.dm_tran_locks contains the locking information of the sessions
If you want to know a specific table is locked or not, you can use the following query
SELECT
*
from
sys.dm_tran_locks
where
resource_associated_entity_id = object_id('schemaname.tablename')
if you are interested in finding both login name of the user and the query being run
SELECT
DB_NAME(resource_database_id)
, s.original_login_name
, s.status
, s.program_name
, s.host_name
, (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
,*
from
sys.dm_tran_locks dbl
JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
INNER JOIN sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
where
DB_NAME(dbl.resource_database_id) = 'dbname'
For more infomraton locking query
More infor about sys.dm_tran_locks
I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.
The problem has been explained previously so I will only reiterate: width doesn't take into account border and padding. One possible answer to this not discussed but which I have found helped me out a bunch is to wrap your inputs. Here's the code, and I'll explain how this helps in a second:
<table>
<tr>
<td><div style="overflow:hidden"><input style="width:100%" type="text" name="name" value="hello world" /></div></td>
</tr>
</table>
The DIV wrapping the INPUT has no padding nor does it have a border. This is the solution. A DIV will expand to its container's size, but it will also respect border and padding. Now, the INPUT will have no issue expanding to the size of its container since it is border-less and pad-less. Also note that the DIV has its overflow set to hidden. It seems that by default items can fall outside of their container with the default overflow of visible. This just ensures that the input stays inside its container and doesn't attempt to poke through.
I've tested this in Chrome and in Fire Fox. Both seem to respect this solution well.
UPDATE: Since I just got a random downvote, I would like to say that a better way to deal with overflow is with the CSS3 box-sizing attribute as described by pricco:
.myinput {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
}
This seems to be pretty well supported by the major browsers and isn't "hacky" like the overflow trick. There are, however, some minor issues on current browsers with this approach (see http://caniuse.com/#search=box-sizing Known Issues).
There are two ways to add the NOT NULL Columns to the table :
ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''
ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''
Using Python will be one easy way to achieve what you want.
I found one using Google.
"convert from json to csv using python" is an example.
app.js
let { func_name } = require('path_to_tools.js');
func_name(); //function calling
tools.js
let func_name = function() {
...
//function body
...
};
module.exports = { func_name };
Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.
Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)
If you want all of the values, use this:
dict_name_goes_here.values()
This rules are compatible whit all browser:
body {overflow: hidden; }
body::-webkit-scrollbar { width: 0 !important; }
body { overflow: -moz-scrollbars-none; }
body { -ms-overflow-style: none; }
Warning: For methods relying on JSON.parse
- Arrays and quote surrounded strings will pass too (ie. console.log(JSON.parse('[3]'), JSON.parse('"\uD800"'))
)
To avoid all non-object JSON primitives (boolean, null, array, number, string), I suggest using the following:
/* Validate a possible object ie. o = { "a": 2 } */
const isJSONObject = (o) =>
!!o && (typeof o === 'object') && !Array.isArray(o) &&
(() => { try { return Boolean(JSON.stringify(o)); } catch { return false } })()
/* Validate a possible JSON object represented as string ie. s = '{ "a": 3 }' */
function isJSONObjectString(s) {
try {
const o = JSON.parse(s);
return !!o && (typeof o === 'object') && !Array.isArray(o)
} catch {
return false
}
}
Code Explanation
Why not use the hasJsonStructure() answer?
Relying on toString()
is not a good idea. This is because different JavaScript Engines may return a different string representation. In general, methods which rely on this may fail in different environments or may be subject to fail later should the engine ever change the string result
Why is catching an exception not a hack?
It was brought up that catching an exception to determine something's validity is never the right way to go. This is generally good advice, but not always. In this case, exception catching is likely is the best route because it relies on the JavaScript engine's implementation of validating JSON data.
Relying on the JS engine offers the following advantages:
When given the opportunity to lean on the JavaScript engine, I'd suggest doing it. Particularly so in this case. Although it may feel hacky to catch an exception, you're really just handling two possible return states from an external method.
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
Use the source, Luke!
In CPython, range(...).__contains__
(a method wrapper) will eventually delegate to a simple calculation which checks if the value can possibly be in the range. The reason for the speed here is we're using mathematical reasoning about the bounds, rather than a direct iteration of the range object. To explain the logic used:
start
and stop
, andFor example, 994
is in range(4, 1000, 2)
because:
4 <= 994 < 1000
, and(994 - 4) % 2 == 0
.The full C code is included below, which is a bit more verbose because of memory management and reference counting details, but the basic idea is there:
static int
range_contains_long(rangeobject *r, PyObject *ob)
{
int cmp1, cmp2, cmp3;
PyObject *tmp1 = NULL;
PyObject *tmp2 = NULL;
PyObject *zero = NULL;
int result = -1;
zero = PyLong_FromLong(0);
if (zero == NULL) /* MemoryError in int(0) */
goto end;
/* Check if the value can possibly be in the range. */
cmp1 = PyObject_RichCompareBool(r->step, zero, Py_GT);
if (cmp1 == -1)
goto end;
if (cmp1 == 1) { /* positive steps: start <= ob < stop */
cmp2 = PyObject_RichCompareBool(r->start, ob, Py_LE);
cmp3 = PyObject_RichCompareBool(ob, r->stop, Py_LT);
}
else { /* negative steps: stop < ob <= start */
cmp2 = PyObject_RichCompareBool(ob, r->start, Py_LE);
cmp3 = PyObject_RichCompareBool(r->stop, ob, Py_LT);
}
if (cmp2 == -1 || cmp3 == -1) /* TypeError */
goto end;
if (cmp2 == 0 || cmp3 == 0) { /* ob outside of range */
result = 0;
goto end;
}
/* Check that the stride does not invalidate ob's membership. */
tmp1 = PyNumber_Subtract(ob, r->start);
if (tmp1 == NULL)
goto end;
tmp2 = PyNumber_Remainder(tmp1, r->step);
if (tmp2 == NULL)
goto end;
/* result = ((int(ob) - start) % step) == 0 */
result = PyObject_RichCompareBool(tmp2, zero, Py_EQ);
end:
Py_XDECREF(tmp1);
Py_XDECREF(tmp2);
Py_XDECREF(zero);
return result;
}
static int
range_contains(rangeobject *r, PyObject *ob)
{
if (PyLong_CheckExact(ob) || PyBool_Check(ob))
return range_contains_long(r, ob);
return (int)_PySequence_IterSearch((PyObject*)r, ob,
PY_ITERSEARCH_CONTAINS);
}
The "meat" of the idea is mentioned in the line:
/* result = ((int(ob) - start) % step) == 0 */
As a final note - look at the range_contains
function at the bottom of the code snippet. If the exact type check fails then we don't use the clever algorithm described, instead falling back to a dumb iteration search of the range using _PySequence_IterSearch
! You can check this behaviour in the interpreter (I'm using v3.5.0 here):
>>> x, r = 1000000000000000, range(1000000000000001)
>>> class MyInt(int):
... pass
...
>>> x_ = MyInt(x)
>>> x in r # calculates immediately :)
True
>>> x_ in r # iterates for ages.. :(
^\Quit (core dumped)
This is a solution. Later you can split by ":" and take the values of the array
/**
* Converts milliseconds to human readeable language separated by ":"
* Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
*/
function dhm(t){
var cd = 24 * 60 * 60 * 1000,
ch = 60 * 60 * 1000,
d = Math.floor(t / cd),
h = '0' + Math.floor( (t - d * cd) / ch),
m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
return [d, h.substr(-2), m.substr(-2)].join(':');
}
//Example
var delay = 190980000;
var fullTime = dhm(delay);
console.log(fullTime);
This should group an associative array Ejm Group By Country
function getGroupedArray($array, $keyFieldsToGroup) {
$newArray = array();
foreach ($array as $record)
$newArray = getRecursiveArray($record, $keyFieldsToGroup, $newArray);
return $newArray;
}
function getRecursiveArray($itemArray, $keys, $newArray) {
if (count($keys) > 1)
$newArray[$itemArray[$keys[0]]] = getRecursiveArray($itemArray, array_splice($keys, 1), $newArray[$itemArray[$keys[0]]]);
else
$newArray[$itemArray[$keys[0]]][] = $itemArray;
return $newArray;
}
$countries = array(array('Country'=>'USA', 'State'=>'California'),
array('Country'=>'USA', 'State'=>'Alabama'),
array('Country'=>'BRA', 'State'=>'Sao Paulo'));
$grouped = getGroupedArray($countries, array('Country'));
Another solution that might work for you is to reverse the relationship. So you would set the border for all list items. You would then use first-child to eliminate the border for the first item. The first-child is statically supported in all browsers (meaning it can't be added dynamically through other code, but first-child is a CSS2 selector, whereas last-child was added in the CSS3 specification)
Note: This only works the way you intended if you only have 2 items in the list like your example. Any 3rd item and on will have borders applied to them.
When doing;
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.
Your other example though;
a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
should work well if you just have the permission on a.txt
. You may want to use a raw (r
-prefixed) string though, to make sure your path does not contain any escape characters like \n
that will be translated to special characters.
a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
Screenshot:
SizedBox.fromSize(
size: Size(56, 56), // button width and height
child: ClipOval(
child: Material(
color: Colors.orange, // button color
child: InkWell(
splashColor: Colors.green, // splash color
onTap: () {}, // button pressed
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.call), // icon
Text("Call"), // text
],
),
),
),
),
)
A blog post that I found useful: Understanding JavaScript Prototypes
You can mess with the __proto__ property of the Object.
var fooJSON = jQuery.parseJSON({"a":4, "b": 3});
fooJSON.__proto__ = Foo.prototype;
This allows fooJSON to inherit the Foo prototype.
I don't think this works in IE, though... at least from what I've read.
I use method 3 because it's the most understandable for others (whenever you see an <a>
tag, you know it's a link) and when you are part of a team, you have to make simple things ;).
And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.
There is no standard location, however you can use the PackageManager to find out about packages and the ApplicationInfo class you can get from there has various information about a particular package: the path to its .apk, the path to its data directory, the path to a resource-only .apk (for forward locked apps), etc. Note that you may or may not have permission to read these directories depending on your relationship with the other app; however, all apps are able to read the resource .apk (which is also the real .apk for non-forward-locked app).
If you are just poking around in the shell, currently non-forward-locked apps are located in /data/app/.apk. The shell user can read a specific .apk, though it can't list the directory. In a future release the naming convention will be changed slightly, so don't count on it remaining the same, but if you get the path of the .apk from the package manager then you can use it in the shell.
To hide the element visually, but keep it in the html, you can use:
<div style='visibility:hidden; overflow:hidden; height:0; width:0;'>
[content]
</div>
or
<div style='visibility:hidden; overflow:hidden; position:absolute;'>
[content]
</div>
What may go wrong with display:none
? It removes the element completely from the html, so some functionalities may be broken if they need to access something in the hidden element.
I had similar problem - I want to replace picture on :hover but can't use BACKGRUND-IMAGE due to lack of Bootstrap's adaptive design.
If you like me only want to change the picture on :hover (but not insist of change SRC for the certain image tag) you can do something like this - it's CSS-only solution.
HTML:
<li>
<img src="/picts/doctors/SmallGray/Zharkova_smallgrey.jpg">
<img class="hoverPhoto" src="/picts/doctors/Small/Zharkova_small.jpg">
</li>
CSS:
li { position: relative; overflow: hidden; }
li img.hoverPhoto {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
opacity: 0;
}
li.hover img { /* it's optional - for nicer transition effect */
opacity: 0;
-web-kit-transition: opacity 1s ease;
-moz-transition: opacity 1s ease;li
-o-transition: opacity 1s ease;
transition: opacity 1s ease;
}
li.hover img.hoverPhoto { opacity: 1; }
If you want IE7-compatible code you may hide/show :HOVER image by positioning not by opacity.
I have same issue and only way how i am able to fix it is add bindingRedirect to app.confing how wrote @tripletdad99.
But if you have solution with more project is really suck update every project by hand (and also sometimes after update some nuget package you need to do it again). And it is reason why i wrote simple powershell script which if all app.configs.
param(
[string]$SourceDirectory,
[string]$Package,
[string]$OldVersion,
[string]$NewVersion
)
Write-Host "Start fixing app.config in $sourceDirectory"
Write-Host "$Package set oldVersion to $OldVersion and newVersion $NewVersion"
Write-Host "Search app.config files.."
[array]$files = get-childitem $sourceDirectory -Include app.config App.config -Recurse | select -expand FullName
foreach ($file in $files)
{
Write-Host $file
$xml = [xml](Get-Content $file)
$daNodes = $xml.configuration.runtime.assemblyBinding.dependentAssembly
foreach($node in $daNodes)
{
if($node.assemblyIdentity.name -eq $package)
{
$updateNode = $node.bindingRedirect
$updateNode.oldVersion = $OldVersion
$updateNode.newVersion =$NewVersion
Write-Host "Fix"
}
}
$xml.Save($file)
}
Write-Host "Done"
Example how to use:
./scripts/FixAppConfig.ps1 -SourceDirectory "C:\project-folder" -Package "System.Net.Http" -OldVersion "0.0.0.0-4.3.2.0" -NewVersion "4.0.0.0"
Probably it is not perfect and also it will be better if somebody link it to pre-build task.
You can use substring
function:
s.substring(0,s.length() - 2));
With the first 0
, you say to substring
that it has to start in the first character of your string and with the s.length() - 2
that it has to finish 2 characters before the String ends.
For more information about substring
function you can see here:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
I faced the same problem and .toString() worked for me. I'm using mongojs driver. Here was my question
An old question but it still shows up in Google results...
A very un-restrictive MIT Licensed C# / .NET library can be found at,
https://www.codeproject.com/articles/1107480/dsplib-fft-dft-fourier-transform-library-for-net
This library is fast as it parallel threads on multiple cores and is very complete and ready to use.
I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.
But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js
).
var config = {
// TODO: Add common Configuration
module: {},
};
var fooConfig = Object.assign({}, config, {
name: "a",
entry: "./a/app",
output: {
path: "./a",
filename: "bundle.js"
},
});
var barConfig = Object.assign({}, config,{
name: "b",
entry: "./b/app",
output: {
path: "./b",
filename: "bundle.js"
},
});
// Return Array of Configurations
module.exports = [
fooConfig, barConfig,
];
If you have common configuration among them, you could use the extend library or Object.assign
in ES6 or {...}
spread operator in ES7.
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b
prefix:
int foo = 0b1010;
If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
And then you can use it like this:
int foo = B(1010);
If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.
Proof:
The following code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
int main()
{
int foo = B(001100101);
printf("%d\n", foo);
return 0;
}
has been compiled using clang -o baz.S baz.c -Wall -O3 -S
, and it produced the following assembly:
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main: ## @main
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp2:
.cfi_def_cfa_offset 16
Ltmp3:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp4:
.cfi_def_cfa_register %rbp
leaq L_.str1(%rip), %rdi
movl $101, %esi ## <= This line!
xorb %al, %al
callq _printf
xorl %eax, %eax
popq %rbp
ret
.cfi_endproc
.section __TEXT,__cstring,cstring_literals
L_.str1: ## @.str1
.asciz "%d\n"
.subsections_via_symbols
So clang
completely eliminated the call to the function, and replaced its return value with 101
. Neat, huh?
The question was how to copy a folder from remote to local with scp
command.
$ scp -r userRemote@remoteIp:/path/remoteDir /path/localDir
But here is the better way for do it with sftp
- SSH File Transfer Protocol (also Secure File Transfer Protocol, or SFTP) is a network protocol that provides file access, file transfer, and file management over any reliable data stream.(wikipedia).
$ sftp user_remote@remote_ip
sftp> cd /path/to/remoteDir
sftp> get -r remoteDir
Fetching /path/to/remoteDir to localDir 100% 398 0.4KB/s 00:00
For help about sftp
command just type help
or ?
.
What if you do this (as was suggested earlier):
new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000
So you have a static field (it's also called "class variable" because it belongs to the class rather than to an instance of the class; in other words it's associated with the class rather than with any object) and you want to initialize it. So if you do NOT want to create an instance of this class and you want to manipulate this static field, you can do it in three ways:
1- Just initialize it when you declare the variable:
static int x = 3;
2- Have a static initializing block:
static int x;
static {
x=3;
}
3- Have a class method (static method) that accesses the class variable and initializes it: this is the alternative to the above static block; you can write a private static method:
public static int x=initializeX();
private static int initializeX(){
return 3;
}
Now why would you use static initializing block instead of static methods?
It's really up to what you need in your program. But you have to know that static initializing block is called once and the only advantage of the class method is that they can be reused later if you need to reinitialize the class variable.
let's say you have a complex array in your program. You initialize it (using for loop for example) and then the values in this array will change throughout the program but then at some point you want to reinitialize it (go back to the initial value). In this case you can call the private static method. In case you do not need in your program to reinitialize the values, you can just use the static block and no need for a static method since you're not gonna use it later in the program.
Note: the static blocks are called in the order they appear in the code.
Example 1:
class A{
public static int a =f();
// this is a static method
private static int f(){
return 3;
}
// this is a static block
static {
a=5;
}
public static void main(String args[]) {
// As I mentioned, you do not need to create an instance of the class to use the class variable
System.out.print(A.a); // this will print 5
}
}
Example 2:
class A{
static {
a=5;
}
public static int a =f();
private static int f(){
return 3;
}
public static void main(String args[]) {
System.out.print(A.a); // this will print 3
}
}
A variable cannot be both null
and undefined
at the same time. However, the direct answer to your question is:
if (variable != null)
One =
, not two.
There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null
and the other being undefined
, and the result is true
for ==
and false
for !=
. Thus if the value of the variable is undefined
, it's not != null
, and if it's not null, it's obviously not != null
.
Now, the case of an identifier not being defined at all, either as a var
or let
, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:
var isDefined = false;
try {
(variable);
isDefined = true;
}
catch (x) {}
I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window
property (in browser JavaScript):
var isJqueryAvailable = window.jQuery != null;
or
var isJqueryAvailable = "jQuery" in window;
There's another way to do this for layouts that doesn't have to put the navbar inside the container, and which doesn't require any CSS or Bootstrap overrides.
Simply place a div with the Bootstrap container
class around the navbar. This will center the links inside the navbar:
<nav class="navbar navbar-default">
<!-- here's where you put the container tag -->
<div class="container">
<div class="navbar-header">
<!-- header and collapsed icon here -->
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<!-- links here -->
</ul>
</div>
</div> <!-- close the container tag -->
</nav> <!-- close the nav tag -->
If you want the then align body content to the center navbar, you also put that body content in the Bootstrap container
tag.
<div class="container">
<! -- body content here -->
</div>
Not everyone can use this type of layout (some people need to nest the navbar itself inside the container
). Nonetheless, if you can do it, it's an easy way to get your navbar links and body centered.
You can see the results in this fullpage JSFiddle: http://jsfiddle.net/bdd9U/231/embedded/result/
Source: http://jsfiddle.net/bdd9U/229/
Pre-ES6
Always 2 bytes per character. UTF-16 is not allowed because the spec says "values must be 16-bit unsigned integers". Since UTF-16 strings can use 3 or 4 byte characters, it would violate 2 byte requirement. Crucially, while UTF-16 cannot be fully supported, the standard does require that the two byte characters used are valid UTF-16 characters. In other words, Pre-ES6 JavaScript strings support a subset of UTF-16 characters.
ES6 and later
2 bytes per character, or 5 or more bytes per character. The additional sizes come into play because ES6 (ECMAScript 6) adds support for Unicode code point escapes. Using a unicode escape looks like this: \u{1D306}
Practical notes
This doesn't relate to the internal implemention of a particular engine. For example, some engines use data structures and libraries with full UTF-16 support, but what they provide externally doesn't have to be full UTF-16 support. Also an engine may provide external UTF-16 support as well but is not mandated to do so.
For ES6, practically speaking characters will never be more than 5 bytes long (2 bytes for the escape point + 3 bytes for the Unicode code point) because the latest version of Unicode only has 136,755 possible characters, which fits easily into 3 bytes. However this is technically not limited by the standard so in principal a single character could use say, 4 bytes for the code point and 6 bytes total.
Most of the code examples here for calculating byte size don't seem to take into account ES6 Unicode code point escapes, so the results could be incorrect in some cases.
In my opinion, the easiest way to do is adding padding to your tag.
td {
padding: 10px 0
}
Hope this will help you! Cheer!
Isn't using $scope.$watch to reflect the changes of scope variable better?
First off, this actually is being raised in the next version to 8MB
or 16MB
... but I think to put this into perspective, Eliot from 10gen (who developed MongoDB) puts it best:
EDIT: The size has been officially 'raised' to 16MB
So, on your blog example, 4MB is actually a whole lot.. For example, the full uncompresses text of "War of the Worlds" is only 364k (html): http://www.gutenberg.org/etext/36
If your blog post is that long with that many comments, I for one am not going to read it :)
For trackbacks, if you dedicated 1MB to them, you could easily have more than 10k (probably closer to 20k)
So except for truly bizarre situations, it'll work great. And in the exception case or spam, I really don't think you'd want a 20mb object anyway. I think capping trackbacks as 15k or so makes a lot of sense no matter what for performance. Or at least special casing if it ever happens.
-Eliot
I think you'd be pretty hard pressed to reach the limit ... and over time, if you upgrade ... you'll have to worry less and less.
The main point of the limit is so you don't use up all the RAM on your server (as you need to load all MB
s of the document into RAM when you query it.)
So the limit is some % of normal usable RAM on a common system ... which will keep growing year on year.
Note on Storing Files in MongoDB
If you need to store documents (or files) larger than 16MB
you can use the GridFS API which will automatically break up the data into segments and stream them back to you (thus avoiding the issue with size limits/RAM.)
Instead of storing a file in a single document, GridFS divides the file into parts, or chunks, and stores each chunk as a separate document.
GridFS uses two collections to store files. One collection stores the file chunks, and the other stores file metadata.
You can use this method to store images, files, videos, etc in the database much as you might in a SQL database. I have used this to even store multi gigabyte video files.
This works:
<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />
$('#button').click(function() {
alert($('#foo option:selected').text());
alert($('#foo option:selected').val());
});
There are many solutions for the problem. This worked for me
Right click on Service -> Properties -> Log on as system account.
Use read
with a heredoc as shown below:
read -d '' sql << EOF
select c1, c2 from foo
where c1='something'
EOF
echo "$sql"
Simple workaround:
All, or nearly all css file can be also interpreted as if it would be scss. It also enables to import them inside a block. Rename the css to scss, and import it so.
In my actual configuration I do the following:
First I copy the .css file into a temporary one, this time with .scss extension. Grunt example config:
copy: {
dev: {
files: [
{
src: "node_modules/some_module/some_precompiled.css",
dest: "target/resources/some_module_styles.scss"
}
]
}
}
Then you can import the .scss file from your parent scss (in my example, it is even imported into a block):
my-selector {
@import "target/resources/some_module_styles.scss";
...other rules...
}
Note: this could be dangerous, because it will effectively result that the css will be parsed multiple times. Check your original css for that it contains any scss-interpretable artifact (it is improbable, but if it happen, the result will be hard to debug and dangerous).
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
map()
doesn't return a list, it returns a map
object.
You need to call list(map)
if you want it to be a list again.
Even better,
from itertools import imap
payIntList = list(imap(int, payList))
Won't take up a bunch of memory creating an intermediate object, it will just pass the ints
out as it creates them.
Also, you can do if choice.lower() == 'n':
so you don't have to do it twice.
Python supports +=
: you can do payIntList[i] += 1000
and numElements += 1
if you want.
If you really want to be tricky:
from itertools import count
for numElements in count(1):
payList.append(raw_input("Enter the pay amount: "))
if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
break
and / or
for payInt in payIntList:
payInt += 1000
print payInt
Also, four spaces is the standard indent amount in Python.
The error regarding the file extension has been handled, you either use BMP
(without the dot) or pass the output name with the extension already. Now to handle the error you need to properly modify your data in the frequency domain to be saved as an integer image, PIL
is telling you that it doesn't accept float data to save as BMP.
Here is a suggestion (with other minor modifications, like using fftshift
and numpy.array
instead of numpy.asarray
) for doing the conversion for proper visualization:
import sys
import numpy
from PIL import Image
img = Image.open(sys.argv[1]).convert('L')
im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))
visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())
result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')
I was able to solve the problem in my react native project by simply adding
configurations {
all*.exclude group: 'com.android.support', module: 'support-compat'
all*.exclude group: 'com.android.support', module: 'support-core-ui'
}
at the end of my android\app\build.gradle file
Momentjs.com has good documentation on how to manipulate the date/time in relation to the current moment. Since Momentjs is required for the Datetimepicker, might as well use it.
var startDefault = moment().startof('day').add(1, 'minutes');
$('#startdatetime-from').datetimepicker({
defaultDate: startDefault,
language: 'en',
format: 'yyyy-MM-dd hh:mm'
});
Multiprogramming - A computer running more than one program at a time (like running Excel and Firefox simultaneously)
Multiprocessing - A computer using more than one CPU at a time
Multiprogramming - More than one task/program/job/process can reside into the main memory at one point of time. This ability of the OS is called multiprogramming.
Multitasking: More than one task/program/job/process can reside into the same CPU at one point of time. This ability of the OS is called multitasking.
Multiusers System - a computer system in which multiple terminals connect to a host computer that handles processing tasks.
You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");
What I usually do, is to store the full string into a variable first, like so:
<?php
$img_id = 'data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAY...';
?>
Then, where I want either JS to do something with that variable:
<script type="text/javascript">
document.getElementById("img_id").backgroundImage="url('<?php echo $img_id; ?>')";
</script>
You could reference the same variable via PHP directly using something like:
<img src="<?php echo $img_id; ?>">
Works for me ;)
Using typescript, I use a custom interface that only applies to my function. Example use case.
handleChange(event: { target: HTMLInputElement; }) {
this.setState({ value: event.target.value });
}
In this case, the handleChange will receive an object with target field that is of type HTMLInputElement.
Later in my code I can use
<input type='text' value={this.state.value} onChange={this.handleChange} />
A cleaner approach would be to put the interface to a separate file.
interface HandleNameChangeInterface {
target: HTMLInputElement;
}
then later use the following function definition:
handleChange(event: HandleNameChangeInterface) {
this.setState({ value: event.target.value });
}
In my usecase, it's expressly defined that the only caller to handleChange is an HTML element type of input text.
I would vote against display: inline-block
since its not supported across browsers, IE < 8 specifically.
.wrapper {
width:500px; /* Adjust to a total width of both .left and .right */
margin: 0 auto;
}
.left {
float: left;
width: 49%; /* Not 50% because of 1px border. */
border: 1px solid #000;
}
.right {
float: right;
width: 49%; /* Not 50% because of 1px border. */
border: 1px solid #F00;
}
<div class="wrapper">
<div class="left">Div 1</div>
<div class="right">Div 2</div>
</div>
EDIT: If no spacing between the cells is desired just change both .left
and .right
to use float: left;
uint16_t
is guaranteed to be a unsigned integer that is 16 bits large
unsigned short int
is guaranteed to be a unsigned short integer
, where short integer
is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer
is 16 bits large.
Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler
Minimum Type Limits
Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.
Type Minimum Range
signed char -127 to +127 unsigned char 0 to 255 short int -32767 to +32767 unsigned short int 0 to 65535
With Dedexer, you can disassemble the .dex
file into dalvik bytecode (.ddx
).
Decompiling towards Java isn't possible as far as I know.
You can read about dalvik bytecode here.
var idPost=document.getElementById("status").innerHTML;
The 'status' element does not exist in your webpage.
So document.getElementById("status") return null. While you can not use innerHTML property of NULL.
You should add a condition like this:
if(document.getElementById("status") != null){
var idPost=document.getElementById("status").innerHTML;
}
Hope this answer can help you. :)
It seems that you need to pass a flag "-l, --log-file"
https://github.com/elastic/kibana/issues/3407
Usage: kibana [options]
Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.
Options:
-h, --help output usage information
-V, --version output the version number
-e, --elasticsearch <uri> Elasticsearch instance
-c, --config <path> Path to the config file
-p, --port <port> The port to bind to
-q, --quiet Turns off logging
-H, --host <host> The host to bind to
-l, --log-file <path> The file to log to
--plugins <path> Path to scan for plugins
If you use the init script to run as a service, maybe you will need to customize it.
Using location.go(url)
is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree()
.
Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute})
but without reloading the component, it can be rewritten as:
const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString()
this.location.go(url);
df = df.fillna('')
or just
df.fillna('', inplace=True)
This will fill na's (e.g. NaN's) with ''
.
If you want to fill a single column, you can use:
df.column1 = df.column1.fillna('')
One can use df['column1']
instead of df.column1
.
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
double d = 28786.079999999998;
String str = String.format("%1.2f", d);
d = Double.valueOf(str);
Yes, you can use what's known as :nth-child
selectors.
In this case you would use:
li:nth-child(3n) {
// Styling for every third element here.
}
:nth-child(3n):
3(0) = 0
3(1) = 3
3(2) = 6
3(3) = 9
3(4) = 12
:nth-child()
is compatible in Chrome, Firefox, and IE9+.
For a work around to use :nth-child()
amongst other pseudo-classes/attribute selectors in IE6 through to IE8, see this link.
import org.apache.commons.lang3.StringUtils;
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
StringUtils.removeEnd(path, ".null");
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf"
BETTER I UPGRADED com.android.support:appcompat-v7:23.1.0
as @Ton said downgrade compile 'com.android.support:design:23.1.0'
BUT Why not to upgrade com.android.support:appcompat-v7:23.1.1
Final upgraded worked for me enjoy
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
So why to use older library. I think is now better to use both design and compact upgraded.
If you decide to use ggplot2
, you can set transparency of overlapping points using the alpha
argument.
e.g.
library(ggplot2)
ggplot(diamonds, aes(carat, price)) + geom_point(alpha = 1/40)
Using Bootstrap 3.x using text-right
works perfectly:
<td class="text-right">
text aligned
</td>
You need to put your main code on the OnStart
method.
This other SO answer of mine might help.
You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.
EDIT:
Please see also the documentation available here for the OnStart
method at the MSDN where one can read this:
Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.
As noted in this linked question, setting listeners for viewHolders should be done in onCreateViewHolder. That said, the implementation below was originally aimed at multiple selection, but I threw a hack in the snippet to force single selection.(*1)
// an array of selected items (Integer indices)
private final ArrayList<Integer> selected = new ArrayList<>();
// items coming into view
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// each time an item comes into view, its position is checked
// against "selected" indices
if (!selected.contains(position)){
// view not selected
holder.parent.setBackgroundColor(Color.LTGRAY);
}
else
// view is selected
holder.parent.setBackgroundColor(Color.CYAN);
}
// selecting items
@Override
public boolean onLongClick(View v) {
// select (set color) immediately.
v.setBackgroundColor(Color.CYAN);
// (*1)
// forcing single selection here...
if (selected.isEmpty()){
selected.add(position); // (done - see note)
}else {
int oldSelected = selected.get(0);
selected.clear(); // (*1)... and here.
selected.add(position);
// note: We do not notify that an item has been selected
// because that work is done here. We instead send
// notifications for items which have been deselected.
notifyItemChanged(oldSelected);
}
return false;
}
you can use MediaQuery with the current context of your widget and get width or height like this
double width = MediaQuery.of(context).size.width
double height = MediaQuery.of(context).size.height
after that, you can multiply it with the percentage you want
Random randomGenerator = new Random();
int i = randomGenerator.nextInt(256);
System.out.println((char)i);
Should take care of what you want, assuming you consider '0,'1','2'.. as characters.
To make the project transport, deployment made easy. need to compressed into one file. JAR (java archive) group of .class files
WAR (web archive) - each war represents one web application - use only web related technologies like servlet, jsps can be used. - can run on Tomcat server - web app developed by web related technologies only jsp servlet html js - info representation only no transactions.
EAR (enterprise archive) - each ear represents one enterprise application - we can use anything from j2ee like ejb, jms can happily be used. - can run on Glassfish like server not on Tomcat server. - enterprise app devloped by any technology anything from j2ee like all web app plus ejbs jms etc. - does transactions with info representation. eg. Bank app, Telecom app
There is no builtin function, but you can easily achieve it by calling the functions min()
and max()
appropriately.
// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);
You can use this, pithy. :D
TextBox1.Focus();
TextBox1.Select(0, TextBox1.Text.Length);
You could also use tools provided by the base JRE:
String msg = "<message>HELLO!</message>";
DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(msg.getBytes()));
System.out.println(parse.getFirstChild().getTextContent());
Generally you can achieve the same effect by using normal blocking IO and multiplexing several IO operations using select(2)
, poll(2)
or some other system calls available on your system.
See The C10K problem for the comparison of approaches to scalable IO multiplexing.
This may be very old. But for those whose looking for a quick code.
public String handleEscapeCharacter( String str ) {
String[] escapeCharacters = { ">", "<", "&", """, "'" };
String[] onReadableCharacter = {">", "<", "&", "\"\"", "'"};
for (int i = 0; i < escapeCharacters.length; i++) {
str = str.replace(escapeCharacters[i], onReadableCharacter[i]);
} return str;
}
That handles escape characters, you can add characters and symbols on their respective arrays.
-Cheers
As a temporary tweak ( not permanent )
On Mac you would need to create your own shortcuts ..
Its easy. my set:
CMD + Wheel-up for increase font size
CMD + Wheel-down for decreasing font size
Prefernces => Keymap => Increase Font size/decrease Font size/Reset Font size
Good luck,'.
If you are using RxJS 6.0.0:
import { from } from 'rxjs';
const observable = from(promise);
If you only want the mean of the weight
column, select the column (which is a Series) and call .mean()
:
In [479]: df
Out[479]:
ID birthyear weight
0 619040 1962 0.123123
1 600161 1963 0.981742
2 25602033 1963 1.312312
3 624870 1987 0.942120
In [480]: df["weight"].mean()
Out[480]: 0.83982437500000007
if you did change the httpd.conf file located under conf_files folder, don't use windows notepad, you need a unix text editor, try TED pad, after making any changes to your httpd.conf file save it. ps: if you use a dos/windows editor you will end up with an "Error in Apache file changed" message. so do be careful.... Salam
Like so many of you, I've been struggling with this for a while. The solution ultimately had to do with the div containing the UL. All suggestions on altering padding, width, etc. of the UL had no effect, but the following did.
It's all about the margin:0 auto;
on the containing div. I hope this helps some people, and thanks to everyone else who already suggested this in combination with other things.
.divNav
{
width: 99%;
text-align:center;
margin:0 auto;
}
.divNav ul
{
display:inline-block;
list-style:none;
zoom: 1;
}
.divNav ul li
{
float:left;
margin-right: .8em;
padding: 0;
}
.divNav a, #divNav a:visited
{
width: 7.5em;
display: block;
border: 1px solid #000;
border-bottom:none;
padding: 5px;
background-color:#F90;
text-decoration: none;
color:#FFF;
text-align: center;
font-family:Verdana, Geneva, sans-serif;
font-size:1em;
}
All of these are good answers but I think there's more to explain why None
is useful.
Imagine you collecting RSVPs to a wedding. You want to record whether each person will attend. If they are attending, you set person.attending = True
. If they are not attending you set person.attending = False
. If you have not received any RSVP, then person.attending = None
. That way you can distinguish between no information - None
- and a negative answer.
I used deleteDir() as follows:
post {
always {
deleteDir() /* clean up our workspace */
}
}
However, I then had to also run a Success or Failure AFTER always but you cannot order the post conditions. The current order is always, changed, aborted, failure, success and then unstable.
However, there is a very useful post condition, cleanup which always runs last, see https://jenkins.io/doc/book/pipeline/syntax/
So in the end my post was as follows :
post {
always {
}
success{
}
failure {
}
cleanup{
deleteDir()
}
}
Hopefully this may be helpful for some corner cases
According to the Java Virtual Machine Specification (Java SE 8), JVM §4.3.2. Field Descriptors:
FieldType term | Type | Interpretation -------------- | --------- | -------------- L ClassName ; | reference | an instance of class ClassName [ | reference | one array dimension ... | ... | ...
the expression [Ljava.lang.String;@45a877
means this is an array ( [
) of class java.lang.String ( Ljava.lang.String;
). And @45a877
is the address where the String object is stored in memory.
Would the Python termcolor module do? This would be a rough equivalent for some uses.
from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
The example is right from this post, which has a lot more. Here is a part of the example from docs
import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')
A specific requirement was to set the color, and presumably other terminal attributes, so that all following prints are that way. While I stated in the original post that this is possible with this module I now don't think so. See the last section for a way to do that.
However, most of the time we print short segments of text in color, a line or two. So the interface in these examples may be a better fit than to 'turn on' a color, print, and then turn it off. (Like in the Perl example shown.) Perhaphs you can add optional argument(s) to your print function for coloring the output as well, and in the function use module's functions to color the text. This also makes it easier to resolve occasional conflicts between formatting and coloring. Just a thought.
Here is a basic approach to set the terminal so that all following prints are rendered with a given color, attributes, or mode.
Once an appropriate ANSI sequence is sent to the terminal, all following text is rendered that way. Thus if we want all text printed to this terminal in the future to be bright/bold red, print ESC[
followed by the codes for "bright" attribute (1) and red color (31), followed by m
# print "\033[1;31m" # this would emit a new line as well
import sys
sys.stdout.write("\033[1;31m")
print "All following prints will be red ..."
To turn off any previously set attributes use 0 for attribute, \033[0;35m
(magenta).
To suppress a new line in python 3 use print('...', end="")
. The rest of the job is about packaging this for modular use (and for easier digestion).
File colors.py
RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
REVERSE = "\033[;7m"
I recommend a quick read through some references on codes. Colors and attributes can be combined and one can put together a nice list in this package. A script
import sys
from colors import *
sys.stdout.write(RED)
print "All following prints rendered in red, until changed"
sys.stdout.write(REVERSE + CYAN)
print "From now on change to cyan, in reverse mode"
print "NOTE: 'CYAN + REVERSE' wouldn't work"
sys.stdout.write(RESET)
print "'REVERSE' and similar modes need be reset explicitly"
print "For color alone this is not needed; just change to new color"
print "All normal prints after 'RESET' above."
If the constant use of sys.stdout.write()
is a bother it can be be wrapped in a tiny function, or the package turned into a class with methods that set terminal behavior (print ANSI codes).
Some of the above is more of a suggestion to look it up, like combining reverse mode and color. (This is available in the Perl module used in the question, and is also sensitive to order and similar.)
A convenient list of escape codes is surprisingly hard to find, while there are many references on terminal behavior and how to control it. The Wiki page on ANSI escape codes has all information but requires a little work to bring it together. Pages on Bash prompt have a lot of specific useful information. Here is another page with straight tables of codes. There is much more out there.
This can be used alongside a module like termocolor
.
it's simple , and it's really worked for me .
run you wamp server => click right mouse button => and click on "put online"
then open your cmd as an administrateur , and pass in this commande word
ipconfig => and press enter
then lot of adresses show-up , then you have just to take the first one , it's look like this example: Adresse IPv4. . . . . . . . . . . . . .: 192.168.67.190
well done ! , that's the adresse, that you will use to cennecte to your wampserver in local.
html{
height:100%;
}
.bg-img {
background: url(image.jpg) no-repeat center top;
background-size: cover;
height:100vh;
}
For me it's the Valid OAuth Redirect URIs in Facebook Login Settings. The 191 error is gone once I updated the correct redirect URI.
Example:
Model:
public class MyViewModel
{
[Required]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content("Thanks", "text/html");
}
}
View:
@model AppName.Models.MyViewModel
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<div id="result"></div>
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
<input type="submit" value="OK" />
}
and here's a better (in my perspective) example:
View:
@model AppName.Models.MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>
<div id="result"></div>
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
<input type="submit" value="OK" />
}
index.js
:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
which can be further enhanced with the jQuery form plugin.
If you have a MUTABLE collection:
val list = mutableListOf(1, 2, 3)
list += 4
If you have an IMMUTABLE collection:
var list = listOf(1, 2, 3)
list += 4
note that I use val
for the mutable list to emphasize that the object is always the same, but its content changes.
In case of the immutable list, you have to make it var
. A new object is created by the +=
operator with the additional value.
Here is a thing I made for myself to clear out how things work. I guess others too can find this concrete example useful:
doit().then(function() { log('Now finally done!') });_x000D_
log('---- But notice where this ends up!');_x000D_
_x000D_
// For pedagogical reasons I originally wrote the following doit()-function so that _x000D_
// it was clear that it is a promise. That way wasn't really a normal way to do _x000D_
// it though, and therefore Slikts edited my answer. I therefore now want to remind _x000D_
// you here that the return value of the following function is a promise, because _x000D_
// it is an async function (every async function returns a promise). _x000D_
async function doit() {_x000D_
log('Calling someTimeConsumingThing');_x000D_
await someTimeConsumingThing();_x000D_
log('Ready with someTimeConsumingThing');_x000D_
}_x000D_
_x000D_
function someTimeConsumingThing() {_x000D_
return new Promise(function(resolve,reject) {_x000D_
setTimeout(resolve, 2000);_x000D_
})_x000D_
}_x000D_
_x000D_
function log(txt) {_x000D_
document.getElementById('msg').innerHTML += txt + '<br>'_x000D_
}
_x000D_
<div id='msg'></div>
_x000D_
Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource
property, not its DataContext
.
<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}" AutoGenerateColumns="False" CanUserResizeColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list
collection. The DataGrid is derived from ItemsControl
, which relies on its ItemsSource
property to define the collection it binds its rows to. Hence, if list
isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list}
and ItemsSource={Binding list}
on the DataGrid...)
metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:
<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>
In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.
Thanks & Regards Vengat Maran
The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization
header with the Bearer
authentication scheme.
This scheme is described by the RFC6750.
Example:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ
If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.
Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.
Unlike the custom JWT
scheme you mention in your question, the Bearer
one is registered at the IANA.
Concerning the Basic
and Digest
authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.
Division is performed using the /
operator:
result = a / b;
Modulo division is done using the %
operator:
result = a % b;
Static import is used to import static fields / method of a class instead of:
package test;
import org.example.Foo;
class A {
B b = Foo.B_INSTANCE;
}
You can write :
package test;
import static org.example.Foo.B_INSTANCE;
class A {
B b = B_INSTANCE;
}
It is useful if you are often used a constant from another class in your code and if the static import is not ambiguous.
Btw, in your example "import static org.example.Myclass;" won't work : import is for class, import static is for static members of a class.
The general methodology would be to iterate through the ArrayList
, and insert the values into the HashMap
. An example is as follows:
HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
productMap.put(product.getProductCode(), product);
}
This works, too.
<input style="width:300px; height:55px; font-size:50px;" />
A CSS stylesheet looks better though, and can easily be used over multiple pages.
If everything is fine with BIOS option I just forced disabling and enabling all HyperV features and this solved my issue --cmd Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All --restart Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V –All
Hi,I think you can use child_process module and curl command.
const cp = require('child_process');
let download = async function(uri, filename){
let command = `curl -o ${filename} '${uri}'`;
let result = cp.execSync(command);
};
async function test() {
await download('http://zhangwenning.top/20181221001417.png', './20181221001417.png')
}
test()
In addition,when you want download large?multiple files,you can use cluster module to use more cpu cores.
Also check if you have installed the Mongo as a windows service and if its running. That's also important. There might port conflict because of that.
Simple. The GNU time
utility has an option for that.
But you have to ensure that you are not using your shell's builtin time
command, at least the bash
builtin does not provide that option! That's why you need to give the full path of the time
utility:
/usr/bin/time -o time.txt sleep 1
In Python 3 there is an exit()
function:
elif choice == "q":
exit()
If you are a beginner, it is better you first go through some basic tutorials and after that learn about naming conventions. I have gone through the following to learn Angular, some of which are very effective.
Tutorials :
Details of application structure and naming conventions can be found in a variety of places. I've gone through 100's of sites and I think these are among the best:
something along this?
function dump(x, indent) {
var indent = indent || '';
var s = '';
if (Array.isArray(x)) {
s += '[';
for (var i=0; i<x.length; i++) {
s += dump(x[i], indent)
if (i < x.length-1) s += ', ';
}
s +=']';
} else if (x === null) {
s = 'NULL';
} else switch(typeof x) {
case 'undefined':
s += 'UNDEFINED';
break;
case 'object':
s += "{ ";
var first = true;
for (var p in x) {
if (!first) s += indent + ' ';
s += p + ': ';
s += dump(x[p], indent + ' ');
s += "\n"
first = false;
}
s += '}';
break;
case 'boolean':
s += (x) ? 'TRUE' : 'FALSE';
break;
case 'number':
s += x;
break;
case 'string':
s += '"' + x + '"';
break;
case 'function':
s += '<FUNCTION>';
break;
default:
s += x;
break;
}
return s;
}
Looks like the parent view had a style for a 3rd party library that was causing the EditText to be white.
android:theme="@style/com_mixpanel_android_SurveyActivityTheme"
Once I removed this everything worked fine.
Step 1:
The object locator supposed to be used here is XPath. So derive the XPath for those two checkboxes.
String housingmoves="//label[contains(text(),'housingmoves')]/preceding-sibling::input";
String season_country_homes="//label[contains(text(),'Seaside & Country Homes')]/preceding-sibling::input";
Step 2:
Perform a click on the checkboxes
driver.findElement(By.xpath(housingmoves)).click();
driver.findElement(By.xpath(season_country_homes)).click();
i wrote a litte wrapper function on my own...
onResize = function(fn) {
if(!fn || typeof fn != 'function')
return 0;
var args = Array.prototype.slice.call(arguments, 1);
onResize.fnArr = onResize.fnArr || [];
onResize.fnArr.push([fn, args]);
onResize.loop = function() {
$.each(onResize.fnArr, function(index, fnWithArgs) {
fnWithArgs[0].apply(undefined, fnWithArgs[1]);
});
};
$(window).on('resize', function(e) {
window.clearTimeout(onResize.timeout);
onResize.timeout = window.setTimeout("onResize.loop();", 300);
});
};
Here is the usage:
var testFn = function(arg1, arg2) {
console.log('[testFn] arg1: '+arg1);
console.log('[testFn] arg2: '+arg2);
};
// document ready
$(function() {
onResize(testFn, 'argument1', 'argument2');
});
You can use regular grep like this:
tail -f admin.log | grep -v "Nopaging the limit is\|keyword to remove is"
if you are getting id from url try
$id = (isset($_GET['id']) ? $_GET['id'] : '');
if getting from form you need to use POST
method cause your form has method="post"
$id = (isset($_POST['id']) ? $_POST['id'] : '');
For php notices use isset()
or empty()
to check values exist or not or initialize variable first with blank or a value
$id= '';
You should use contains not matches
if(nom.contains("."))
System.out.println("OK");
else
System.out.println("Bad");
$("video").prop('muted', true); //mute
AND
$("video").prop('muted', false); //unmute
See all events here
(side note: use attr
if in jQuery < 1.6)
You can use below code to get all the privileges list from all users.
select * from dba_sys_privs
One very interesting web framework with commercial deployment is Scalatra, inspired by Ruby's Sinatra. Here's an InfoQ article about it.
For those the above answer does not work, here is another possible solution to look at.
Issue: On installing npm os-service package i was getting below error error MSB4019: The imported project "d:\M icrosoft.Cpp.Default.props" was not found. Confirm that the path in the declaration is correct
Even the installation of build tools or VS 2015 did not work for me. So I tried installing below directly via PowerShell (as admin)
https://chocolatey.org/packages/visualcpp-build-tools/14.0.25420.1 Command: choco install visualcpp-build-tools --version 14.0.25420.1
Once this was installed, set an environment variable VCTargetsPath=C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140
Then installation of the package worked perfectly fine after these.
grep -r -e string directory
-r
is for recursive; -e
is optional but its argument specifies the regex to search for. Interestingly, POSIX grep
is not required to support -r
(or -R
), but I'm practically certain that System V in practice they (almost) all do. Some versions of grep
did, sogrep
support -R
as well as (or conceivably instead of) -r
; AFAICT, it means the same thing.
For protobuf 2.5, use the dependency:
"com.googlecode.protobuf-java-format" % "protobuf-java-format" % "1.2"
Then use the code:
com.googlecode.protobuf.format.JsonFormat.merge(json, builder)
com.googlecode.protobuf.format.JsonFormat.printToString(proto)
if echo "$var" | egrep -q '^\-?[0-9]+$'; then
echo "$var is an integer"
else
echo "$var is not an integer"
fi
tests (with var=2 etc.):
2 is an integer
-2 is an integer
2.5 is not an integer
2b is not an integer
if echo "$var" | egrep -q '^\-?[0-9]*\.?[0-9]+$'; then
echo "$var is a number"
else
echo "$var is not a number"
fi
tests (with var=2 etc.):
2 is a number
-2 is a number
-2.6 is a number
-2.c6 is not a number
2. is not a number
2.0 is a number
Depending on your rights, you need sudo at beginning.
Although having the parameters in the path has some advantages, there are, IMO, some outweighing factors.
Not all characters needed for a search query are permitted in a URL. Most punctuation and Unicode characters would need to be URL encoded as a query string parameter. I'm wrestling with the same problem. I would like to use XPath in the URL, but not all XPath syntax is compatible with a URI path. So for simple paths, /cars/doors/driver/lock/combination
would be appropriate to locate the 'combination
' element in the driver's door XML document. But /car/doors[id='driver' and lock/combination='1234']
is not so friendly.
There is a difference between filtering a resource based on one of its attributes and specifying a resource.
For example, since
/cars/colors
returns a list of all colors for all cars (the resource returned is a collection of color objects)
/cars/colors/red,blue,green
would return a list of color objects that are red, blue or green, not a collection of cars.
To return cars, the path would be
/cars?color=red,blue,green
or /cars/search?color=red,blue,green
Parameters in the path are more difficult to read because name/value pairs are not isolated from the rest of the path, which is not name/value pairs.
One last comment. I prefer /garages/yyy/cars
(always plural) to /garage/yyy/cars
(perhaps it was a typo in the original answer) because it avoids changing the path between singular and plural. For words with an added 's', the change is not so bad, but changing /person/yyy/friends
to /people/yyy
seems cumbersome.
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
What frameworks do you use?
We use a mix of the logging application block, and a custom logging helper that works around the .Net framework bits. The LAB is configured to output fairly extensive log files included seperate general trace files for service method entry/exit and specific error files for unexpected issues. The configuration includes date/time, thread, pId etc. for debug assistance as well as the full exception detail and stack (in the case of an unexpected exception).
The custom logging helper makes use of the Trace.Correlation and is particularly handy in the context of logging in WF. For example we have a state machine that invokes a series of sequential workflows. At each of these invoke activities we log the start (using StartLogicalOperation) and then at the end we stop the logical operation with a gereric return event handler.
This has proven useful a few times when attempting to debug failures in complex business sequences as it allows us to determine things like If/Else branch decisions etc. more quickly based on the activity execution sequence.
What log outputs do you use?
We use text files and XML files. Text files are configured through the app block but we've got XML outputs as well from our WF service. This enables us to capture the runtime events (persistence etc.) as well as generic business type exceptions. The text files are rolling logs that are rolled by day and size (I believe total size of 1MB is a rollover point).
What tools to you use for viewing the logs?
We are using Notepad and WCF Service Trace Viewer depending on which output group we're looking at. The WCF Service Trace Viewer is really really handy if you've got your output setup correctly and can make reading the output much simpler. That said, if I know roughly where the error is anyway - just reading a well annotated text file is good as well.
The logs are sent to a single directory which is then split into sub-dirs based on the source service. The root dir is exposed via a website which has it's access controlled by a support user group. This allows us to take a look at production logs without having to put in requests and go through lengthy red tape processes for production data.
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
There is a significant problem with some of the answers posted so far: unicode()
decodes from the default encoding, which is often ASCII; in fact, unicode()
tries to make "sense" of the bytes it is given by converting them into characters. Thus, the following code, which is essentially what is recommended by previous answers, fails on my machine:
# -*- coding: utf-8 -*-
author = 'éric'
print '{0}'.format(unicode(author))
gives:
Traceback (most recent call last):
File "test.py", line 3, in <module>
print '{0}'.format(unicode(author))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
The failure comes from the fact that author
does not contain only ASCII bytes (i.e. with values in [0; 127]), and unicode()
decodes from ASCII by default (on many machines).
A robust solution is to explicitly give the encoding used in your fields; taking UTF-8 as an example:
u'{0} in {1}'.format(unicode(self.author, 'utf-8'), unicode(self.publication, 'utf-8'))
(or without the initial u
, depending on whether you want a Unicode result or a byte string).
At this point, one might want to consider having the author
and publication
fields be Unicode strings, instead of decoding them during formatting.
You have to import 'CommonModule' in the module where you are using these in-built directives like ngFor,ngIf etc.
import { CommonModule } from "@angular/common";
@NgModule({
imports: [
CommonModule
]
})
export class ProductModule { }
For child-parent communication you should pass a function setting the state from parent to child, like this
class Parent extends React.Component {_x000D_
constructor(props) {_x000D_
super(props)_x000D_
_x000D_
this.handler = this.handler.bind(this)_x000D_
}_x000D_
_x000D_
handler() {_x000D_
this.setState({_x000D_
someVar: 'some value'_x000D_
})_x000D_
}_x000D_
_x000D_
render() {_x000D_
return <Child handler = {this.handler} />_x000D_
}_x000D_
}_x000D_
_x000D_
class Child extends React.Component {_x000D_
render() {_x000D_
return <Button onClick = {this.props.handler}/ >_x000D_
}_x000D_
}
_x000D_
This way the child can update the parent's state with the call of a function passed with props.
But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.
One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.
First, we check to see if the String is doubled quoted, and if so, remove them. You can skip the conditional if in fact you know it's double quoted.
if (string.length() >= 2 && string.charAt(0) == '"' && string.charAt(string.length() - 1) == '"')
{
string = string.substring(1, string.length() - 1);
}
Your data class doesn't match the JSON object. Use this instead:
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Also, you don't have to instantiate the class to get its type for deserialization:
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
you must have record in table or array record in database.
example:
SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).
So basically, from bottom to top
Linux
Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx
PHP-FPM + APC
ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.
It will be better to Create a New role, then grant execute, select ... etc permissions to this role and finally assign users to this role.
Create role
CREATE ROLE [db_SomeExecutor]
GO
Grant Permission to this role
GRANT EXECUTE TO db_SomeExecutor
GRANT INSERT TO db_SomeExecutor
to Add users database>security> > roles > databaseroles>Properties > Add ( bottom right ) you can search AD users and add then
OR
EXEC sp_addrolemember 'db_SomeExecutor', 'domainName\UserName'
Please refer this post
in 2019 I need to write minified jquery plugins so I need it too this alias and so testing these examples and others ,from other sources,I found a way without copy in the memory of whe entire object ,but creating only a reference. I tested this already with firefox and watching task manager's tab memory on firefox before. The code is:
var {p: d} ={p: document};
console.log(d.body);
You can specify the connection timeout within the SQL connection string, when you connect to the database, like so:
"Data Source=localhost;Initial Catalog=database;Connect Timeout=15"
On the server level, use MSSQLMS to view the server properties, and on the Connections page you can specify the default query timeout.
I'm not quite sure that queries keep on running after the client connection has closed. Queries should not take that long either, MSSQL can handle large databases, I've worked with GB's of data on it before. Run a performance profile on the queries, prehaps some well-placed indexes could speed it up, or rewriting the query could too.
Update: According to this list, SQL timeouts happen when waiting for attention acknowledgement from server:
Suppose you execute a command, then the command times out. When this happens the SqlClient driver sends a special 8 byte packet to the server called an attention packet. This tells the server to stop executing the current command. When we send the attention packet, we have to wait for the attention acknowledgement from the server and this can in theory take a long time and time out. You can also send this packet by calling SqlCommand.Cancel on an asynchronous SqlCommand object. This one is a special case where we use a 5 second timeout. In most cases you will never hit this one, the server is usually very responsive to attention packets because these are handled very low in the network layer.
So it seems that after the client connection times out, a signal is sent to the server to cancel the running query too.
It is unfortunately not supported in older versions of MSTest. Apparently there is an extensibility model and you can implement it yourself. Another option would be to use data-driven tests.
My personal opinion would be to just stick with NUnit though...
As of Visual Studio 2012, update 1, MSTest has a similar feature. See McAden's answer.
void WinErrorCodeToString(DWORD ErrorCode, string& Message)
{
char* locbuffer = NULL;
DWORD count = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, ErrorCode,
0, (LPSTR)&locbuffer, 0, nullptr);
if (locbuffer)
{
if (count)
{
int c;
int back = 0;
//
// strip any trailing "\r\n"s and replace by a single "\n"
//
while (((c = *CharPrevA(locbuffer, locbuffer + count)) == '\r') ||
(c == '\n')) {
count--;
back++;
}
if (back) {
locbuffer[count++] = '\n';
locbuffer[count] = '\0';
}
Message = "Error: ";
Message += locbuffer;
}
LocalFree(locbuffer);
}
else
{
Message = "Unknown error code: " + to_string(ErrorCode);
}
}
If you need a name on your pin, you can also use:
http://maps.google.com/?q=MY%20LOCATION@lat,long
Programmatically in Swift 5 with Xcode 10.2
Building on top of @La masse's solution, but using autolayout to support rotation
Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)
label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()
If setting frame.width dynamically using UIScreen:
extension UIScreen { // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
class func absoluteWidth() -> CGFloat {
var width: CGFloat
if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
width = self.main.bounds.height // Landscape
} else {
width = self.main.bounds.width // Portrait
}
return width
}
}
Here's a modification of the accepted answer to provide more functionality.
RangeCollection.cs:
public class RangeCollection<T> : ObservableCollection<T>
{
#region Members
/// <summary>
/// Occurs when a single item is added.
/// </summary>
public event EventHandler<ItemAddedEventArgs<T>> ItemAdded;
/// <summary>
/// Occurs when a single item is inserted.
/// </summary>
public event EventHandler<ItemInsertedEventArgs<T>> ItemInserted;
/// <summary>
/// Occurs when a single item is removed.
/// </summary>
public event EventHandler<ItemRemovedEventArgs<T>> ItemRemoved;
/// <summary>
/// Occurs when a single item is replaced.
/// </summary>
public event EventHandler<ItemReplacedEventArgs<T>> ItemReplaced;
/// <summary>
/// Occurs when items are added to this.
/// </summary>
public event EventHandler<ItemsAddedEventArgs<T>> ItemsAdded;
/// <summary>
/// Occurs when items are removed from this.
/// </summary>
public event EventHandler<ItemsRemovedEventArgs<T>> ItemsRemoved;
/// <summary>
/// Occurs when items are replaced within this.
/// </summary>
public event EventHandler<ItemsReplacedEventArgs<T>> ItemsReplaced;
/// <summary>
/// Occurs when entire collection is cleared.
/// </summary>
public event EventHandler<ItemsClearedEventArgs<T>> ItemsCleared;
/// <summary>
/// Occurs when entire collection is replaced.
/// </summary>
public event EventHandler<CollectionReplacedEventArgs<T>> CollectionReplaced;
#endregion
#region Helper Methods
/// <summary>
/// Throws exception if any of the specified objects are null.
/// </summary>
private void Check(params T[] Items)
{
foreach (T Item in Items)
{
if (Item == null)
{
throw new ArgumentNullException("Item cannot be null.");
}
}
}
private void Check(IEnumerable<T> Items)
{
if (Items == null) throw new ArgumentNullException("Items cannot be null.");
}
private void Check(IEnumerable<IEnumerable<T>> Items)
{
if (Items == null) throw new ArgumentNullException("Items cannot be null.");
}
private void RaiseChanged(NotifyCollectionChangedAction Action)
{
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion
#region Bulk Methods
/// <summary>
/// Adds the elements of the specified collection to the end of this.
/// </summary>
public void AddRange(IEnumerable<T> NewItems)
{
this.Check(NewItems);
foreach (var i in NewItems) this.Items.Add(i);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnItemsAdded(new ItemsAddedEventArgs<T>(NewItems));
}
/// <summary>
/// Adds variable IEnumerable<T> to this.
/// </summary>
/// <param name="List"></param>
public void AddRange(params IEnumerable<T>[] NewItems)
{
this.Check(NewItems);
foreach (IEnumerable<T> Items in NewItems) foreach (T Item in Items) this.Items.Add(Item);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
//TO-DO: Raise OnItemsAdded with combined IEnumerable<T>.
}
/// <summary>
/// Removes the first occurence of each item in the specified collection.
/// </summary>
public void Remove(IEnumerable<T> OldItems)
{
this.Check(OldItems);
foreach (var i in OldItems) Items.Remove(i);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
OnItemsRemoved(new ItemsRemovedEventArgs<T>(OldItems));
}
/// <summary>
/// Removes all occurences of each item in the specified collection.
/// </summary>
/// <param name="itemsToRemove"></param>
public void RemoveAll(IEnumerable<T> OldItems)
{
this.Check(OldItems);
var set = new HashSet<T>(OldItems);
var list = this as List<T>;
int i = 0;
while (i < this.Count) if (set.Contains(this[i])) this.RemoveAt(i); else i++;
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
OnItemsRemoved(new ItemsRemovedEventArgs<T>(OldItems));
}
/// <summary>
/// Replaces all occurences of a single item with specified item.
/// </summary>
public void ReplaceAll(T Old, T New)
{
this.Check(Old, New);
this.Replace(Old, New, false);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnItemReplaced(new ItemReplacedEventArgs<T>(Old, New));
}
/// <summary>
/// Clears this and adds specified collection.
/// </summary>
public void ReplaceCollection(IEnumerable<T> NewItems, bool SupressEvent = false)
{
this.Check(NewItems);
IEnumerable<T> OldItems = new List<T>(this.Items);
this.Items.Clear();
foreach (T Item in NewItems) this.Items.Add(Item);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnReplaced(new CollectionReplacedEventArgs<T>(OldItems, NewItems));
}
private void Replace(T Old, T New, bool BreakFirst)
{
List<T> Cloned = new List<T>(this.Items);
int i = 0;
foreach (T Item in Cloned)
{
if (Item.Equals(Old))
{
this.Items.Remove(Item);
this.Items.Insert(i, New);
if (BreakFirst) break;
}
i++;
}
}
/// <summary>
/// Replaces the first occurence of a single item with specified item.
/// </summary>
public void Replace(T Old, T New)
{
this.Check(Old, New);
this.Replace(Old, New, true);
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnItemReplaced(new ItemReplacedEventArgs<T>(Old, New));
}
#endregion
#region New Methods
/// <summary>
/// Removes a single item.
/// </summary>
/// <param name="Item"></param>
public new void Remove(T Item)
{
this.Check(Item);
base.Remove(Item);
OnItemRemoved(new ItemRemovedEventArgs<T>(Item));
}
/// <summary>
/// Removes a single item at specified index.
/// </summary>
/// <param name="i"></param>
public new void RemoveAt(int i)
{
T OldItem = this.Items[i]; //This will throw first if null
base.RemoveAt(i);
OnItemRemoved(new ItemRemovedEventArgs<T>(OldItem));
}
/// <summary>
/// Clears this.
/// </summary>
public new void Clear()
{
IEnumerable<T> OldItems = new List<T>(this.Items);
this.Items.Clear();
this.RaiseChanged(NotifyCollectionChangedAction.Reset);
this.OnCleared(new ItemsClearedEventArgs<T>(OldItems));
}
/// <summary>
/// Adds a single item to end of this.
/// </summary>
/// <param name="t"></param>
public new void Add(T Item)
{
this.Check(Item);
base.Add(Item);
this.OnItemAdded(new ItemAddedEventArgs<T>(Item));
}
/// <summary>
/// Inserts a single item at specified index.
/// </summary>
/// <param name="i"></param>
/// <param name="t"></param>
public new void Insert(int i, T Item)
{
this.Check(Item);
base.Insert(i, Item);
this.OnItemInserted(new ItemInsertedEventArgs<T>(Item, i));
}
/// <summary>
/// Returns list of T.ToString().
/// </summary>
/// <returns></returns>
public new IEnumerable<string> ToString()
{
foreach (T Item in this) yield return Item.ToString();
}
#endregion
#region Event Methods
private void OnItemAdded(ItemAddedEventArgs<T> i)
{
if (this.ItemAdded != null) this.ItemAdded(this, new ItemAddedEventArgs<T>(i.NewItem));
}
private void OnItemInserted(ItemInsertedEventArgs<T> i)
{
if (this.ItemInserted != null) this.ItemInserted(this, new ItemInsertedEventArgs<T>(i.NewItem, i.Index));
}
private void OnItemRemoved(ItemRemovedEventArgs<T> i)
{
if (this.ItemRemoved != null) this.ItemRemoved(this, new ItemRemovedEventArgs<T>(i.OldItem));
}
private void OnItemReplaced(ItemReplacedEventArgs<T> i)
{
if (this.ItemReplaced != null) this.ItemReplaced(this, new ItemReplacedEventArgs<T>(i.OldItem, i.NewItem));
}
private void OnItemsAdded(ItemsAddedEventArgs<T> i)
{
if (this.ItemsAdded != null) this.ItemsAdded(this, new ItemsAddedEventArgs<T>(i.NewItems));
}
private void OnItemsRemoved(ItemsRemovedEventArgs<T> i)
{
if (this.ItemsRemoved != null) this.ItemsRemoved(this, new ItemsRemovedEventArgs<T>(i.OldItems));
}
private void OnItemsReplaced(ItemsReplacedEventArgs<T> i)
{
if (this.ItemsReplaced != null) this.ItemsReplaced(this, new ItemsReplacedEventArgs<T>(i.OldItems, i.NewItems));
}
private void OnCleared(ItemsClearedEventArgs<T> i)
{
if (this.ItemsCleared != null) this.ItemsCleared(this, new ItemsClearedEventArgs<T>(i.OldItems));
}
private void OnReplaced(CollectionReplacedEventArgs<T> i)
{
if (this.CollectionReplaced != null) this.CollectionReplaced(this, new CollectionReplacedEventArgs<T>(i.OldItems, i.NewItems));
}
#endregion
#region RangeCollection
/// <summary>
/// Initializes a new instance.
/// </summary>
public RangeCollection() : base() { }
/// <summary>
/// Initializes a new instance from specified enumerable.
/// </summary>
public RangeCollection(IEnumerable<T> Collection) : base(Collection) { }
/// <summary>
/// Initializes a new instance from specified list.
/// </summary>
public RangeCollection(List<T> List) : base(List) { }
/// <summary>
/// Initializes a new instance with variable T.
/// </summary>
public RangeCollection(params T[] Items) : base()
{
this.AddRange(Items);
}
/// <summary>
/// Initializes a new instance with variable enumerable.
/// </summary>
public RangeCollection(params IEnumerable<T>[] Items) : base()
{
this.AddRange(Items);
}
#endregion
}
Events Classes:
public class CollectionReplacedEventArgs<T> : ReplacedEventArgs<T>
{
public CollectionReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New) : base(Old, New) { }
}
public class ItemAddedEventArgs<T> : EventArgs
{
public T NewItem;
public ItemAddedEventArgs(T t)
{
this.NewItem = t;
}
}
public class ItemInsertedEventArgs<T> : EventArgs
{
public int Index;
public T NewItem;
public ItemInsertedEventArgs(T t, int i)
{
this.NewItem = t;
this.Index = i;
}
}
public class ItemRemovedEventArgs<T> : EventArgs
{
public T OldItem;
public ItemRemovedEventArgs(T t)
{
this.OldItem = t;
}
}
public class ItemReplacedEventArgs<T> : EventArgs
{
public T OldItem;
public T NewItem;
public ItemReplacedEventArgs(T Old, T New)
{
this.OldItem = Old;
this.NewItem = New;
}
}
public class ItemsAddedEventArgs<T> : EventArgs
{
public IEnumerable<T> NewItems;
public ItemsAddedEventArgs(IEnumerable<T> t)
{
this.NewItems = t;
}
}
public class ItemsClearedEventArgs<T> : RemovedEventArgs<T>
{
public ItemsClearedEventArgs(IEnumerable<T> Old) : base(Old) { }
}
public class ItemsRemovedEventArgs<T> : RemovedEventArgs<T>
{
public ItemsRemovedEventArgs(IEnumerable<T> Old) : base(Old) { }
}
public class ItemsReplacedEventArgs<T> : ReplacedEventArgs<T>
{
public ItemsReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New) : base(Old, New) { }
}
public class RemovedEventArgs<T> : EventArgs
{
public IEnumerable<T> OldItems;
public RemovedEventArgs(IEnumerable<T> Old)
{
this.OldItems = Old;
}
}
public class ReplacedEventArgs<T> : EventArgs
{
public IEnumerable<T> OldItems;
public IEnumerable<T> NewItems;
public ReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New)
{
this.OldItems = Old;
this.NewItems = New;
}
}
Note: I did not manually raise OnCollectionChanged
in the base methods because it appears only to be possible to create a CollectionChangedEventArgs
using the Reset
action. If you try to raise OnCollectionChanged
using Reset
for a single item change, your items control will appear to flicker, which is something you want to avoid.
Alternatively, cv2.merge()
can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1)
into (height, width, 3)
To address your problem
I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.
This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
Example
We create a color image with dimensions (200,200,3)
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
Next we convert it to grayscale and create another image using cv2.merge()
with three gray channels
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1)
and the three channel grayscale image with shape (200,200,3)
(right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
Full code
import cv2
import numpy as np
# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])
# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()
The code below reads for any text files available in the directory which contains the script we are running. Then it opens every text file and stores the words of the text line into a list. After store the words we print each word line by line
import os, fnmatch
listOfFiles = os.listdir('.')
pattern = "*.txt"
store = []
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
_fileName = open(entry,"r")
if _fileName.mode == "r":
content = _fileName.read()
contentList = content.split(" ")
for i in contentList:
if i != '\n' and i != "\r\n":
store.append(i)
for i in store:
print(i)
This should do the trick:
mapper.readValue(fileReader, MyClass.class);
I say should because I'm using that with a String
, not a BufferedReader
but it should still work.
Here's my code:
String inputString = // I grab my string here
MySessionClass sessionObject;
try {
ObjectMapper objectMapper = new ObjectMapper();
sessionObject = objectMapper.readValue(inputString, MySessionClass.class);
Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)
You can also define a custom deserializer when you instantiate the ObjectMapper
:
http://wiki.fasterxml.com/JacksonHowToCustomDeserializers
Edit:
I just remembered something else. If your object coming in has more properties than the POJO
has and you just want to ignore the extras you'll want to set this:
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Or you'll get an error that it can't find the property to set into.
Right click folder -> Click Tortoise SVN -> Check for modification
Use:
import os
print os.sep
to see how separator looks on a current OS.
In your code you can use:
import os
path = os.path.join('folder_name', 'file_name')
Have you tried: http://flori.github.com/json/?
Failing that, you could just parse it out? If it's only arrays you're interested in, something to split the above out will be quite simple.
The dynamic
keyword was added, together with many other new features of C# 4.0, to make it simpler to talk to code that lives in or comes from other runtimes, that has different APIs.
Take an example.
If you have a COM object, like the Word.Application
object, and want to open a document, the method to do that comes with no less than 15 parameters, most of which are optional.
To call this method, you would need something like this (I'm simplifying, this is not actual code):
object missing = System.Reflection.Missing.Value;
object fileName = "C:\\test.docx";
object readOnly = true;
wordApplication.Documents.Open(ref fileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing);
Note all those arguments? You need to pass those since C# before version 4.0 did not have a notion of optional arguments. In C# 4.0, COM APIs have been made easier to work with by introducing:
ref
optional for COM APIsThe new syntax for the above call would be:
wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);
See how much easier it looks, how much more readable it becomes?
Let's break that apart:
named argument, can skip the rest
|
v
wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);
^ ^
| |
notice no ref keyword, can pass
actual parameter values instead
The magic is that the C# compiler will now inject the necessary code, and work with new classes in the runtime, to do almost the exact same thing that you did before, but the syntax has been hidden from you, now you can focus on the what, and not so much on the how. Anders Hejlsberg is fond of saying that you have to invoke different "incantations", which is a sort of pun on the magic of the whole thing, where you typically have to wave your hand(s) and say some magic words in the right order to get a certain type of spell going. The old API way of talking to COM objects was a lot of that, you needed to jump through a lot of hoops in order to coax the compiler to compile the code for you.
Things break down in C# before version 4.0 even more if you try to talk to a COM object that you don't have an interface or class for, all you have is an IDispatch
reference.
If you don't know what it is, IDispatch
is basically reflection for COM objects. With an IDispatch
interface you can ask the object "what is the id number for the method known as Save", and build up arrays of a certain type containing the argument values, and finally call an Invoke
method on the IDispatch
interface to call the method, passing all the information you've managed to scrounge together.
The above Save method could look like this (this is definitely not the right code):
string[] methodNames = new[] { "Open" };
Guid IID = ...
int methodId = wordApplication.GetIDsOfNames(IID, methodNames, methodNames.Length, lcid, dispid);
SafeArray args = new SafeArray(new[] { fileName, missing, missing, .... });
wordApplication.Invoke(methodId, ... args, ...);
All this for just opening a document.
VB had optional arguments and support for most of this out of the box a long time ago, so this C# code:
wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);
is basically just C# catching up to VB in terms of expressiveness, but doing it the right way, by making it extendable, and not just for COM. Of course this is also available for VB.NET or any other language built on top of the .NET runtime.
You can find more information about the IDispatch
interface on Wikipedia: IDispatch if you want to read more about it. It's really gory stuff.
However, what if you wanted to talk to a Python object? There's a different API for that than the one used for COM objects, and since Python objects are dynamic in nature as well, you need to resort to reflection magic to find the right methods to call, their parameters, etc. but not the .NET reflection, something written for Python, pretty much like the IDispatch code above, just altogether different.
And for Ruby? A different API still.
JavaScript? Same deal, different API for that as well.
The dynamic keyword consists of two things:
dynamic
dynamic
keyword requires, and maps the calls to the right way of doing things. The API is even documented, so if you have objects that comes from a runtime not covered, you can add it.The dynamic
keyword is not, however, meant to replace any existing .NET-only code. Sure, you can do it, but it was not added for that reason, and the authors of the C# programming language with Anders Hejlsberg in the front, has been most adamant that they still regard C# as a strongly typed language, and will not sacrifice that principle.
This means that although you can write code like this:
dynamic x = 10;
dynamic y = 3.14;
dynamic z = "test";
dynamic k = true;
dynamic l = x + y * z - k;
and have it compile, it was not meant as a sort of magic-lets-figure-out-what-you-meant-at-runtime type of system.
The whole purpose was to make it easier to talk to other types of objects.
There's plenty of material on the internet about the keyword, proponents, opponents, discussions, rants, praise, etc.
I suggest you start with the following links and then google for more:
I would try to give them all display: block;
attribute and using float: left;
.
You can then set width
and/or height
as you like. You can even specify some vertical-alignment rules.
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products WHERE id = 1");
For the record, the file Microsoft.Cpp.Default.props
can modify the env var VCTargetsPath
and make subsequent usages of that var incorrect.
I had that problem and solved it by setting VCTargetsPath10
and VCTargetsPath11
to the same value than VCTargetsPath
.
This should be adapted according to the VS version you are using.
Adding bootstrap current version 4 to angular:
1/ First you have to install those:
npm install jquery --save
npm install popper.js --save
npm install bootstrap --save
2/ Then add the needed script files to scripts in angular.json:
"scripts": [
"node_modules/jquery/dist/jquery.slim.js",
"node_modules/popper.js/dist/umd/popper.js",
"node_modules/bootstrap/dist/js/bootstrap.js"
],
3/Finally add the Bootstrap CSS to the styles array in angular.json:
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.css",
"src/styles.css"
],`
It turns it into a bytes
literal (or str
in 2.x), and is valid for 2.6+.
The r
prefix causes backslashes to be "uninterpreted" (not ignored, and the difference does matter).
I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!
This is my working example:
Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
' in duplicated formatting rules that in turn will significantly slow down
' the spreadsheet.
' This macro is designed to reset all formatting rules to default.
' ----------------------------------------------------------------------------------------
On Error GoTo ErrHandler
' Make sure we are positioned in the correct sheet
WS_PROMO.Select
' Disable Events
Application.EnableEvents = False
' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete
' CREATE ALL THE CONDITIONAL FORMATTING RULES:
' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
.Font.Color = -16776961
.StopIfTrue = False
End With
' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
.Font.Color = -16744448
.StopIfTrue = False
End With
' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
.Font.Bold = True
.Font.Color = -16776961
.StopIfTrue = False
End With
' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
.Font.Bold = True
.Font.Color = -10092544
.StopIfTrue = False
End With
' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
.Font.Color = -16383844
.Interior.Color = 13551615
.StopIfTrue = False
End With
' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
.Font.Bold = True
.Interior.Color = 13434879
.StopIfTrue = False
End With
' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")
ErrHandler:
Application.EnableEvents = False
End Sub
GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2
Git does not track empty directories. See the Git FAQ for more explanation. The suggested workaround is to put a .gitignore
file in the empty directory. I do not like that solution, because the .gitignore
is "hidden" by Unix convention. Also there is no explanation why the directories are empty.
I suggest to put a README file in the empty directory explaining why the directory is empty and why it needs to be tracked in Git. With the README file in place, as far as Git is concerned, the directory is no longer empty.
The real question is why do you need the empty directory in git? Usually you have some sort of build script that can create the empty directory before compiling/running. If not then make one. That is a far better solution than putting empty directories in git.
So you have some reason why you need an empty directory in git. Put that reason in the README file. That way other developers (and future you) know why the empty directory needs to be there. You will also know that you can remove the empty directory when the problem requiring the empty directory has been solved.
To list every empty directory use the following command:
find -name .git -prune -o -type d -empty -print
To create placeholder READMEs in every empty directory:
find -name .git -prune -o -type d -empty -exec sh -c \
"echo this directory needs to be empty because reasons > {}/README.emptydir" \;
To ignore everything in the directory except the README file put the following lines in your .gitignore
:
path/to/emptydir/*
!path/to/emptydir/README.emptydir
path/to/otheremptydir/*
!path/to/otheremptydir/README.emptydir
Alternatively, you could just exclude every README file from being ignored:
path/to/emptydir/*
path/to/otheremptydir/*
!README.emptydir
To list every README after they are already created:
find -name README.emptydir
I'm not sure you really want to do what you say you want to do, but it's not for me to reason why!
You cannot add properties to a class after it has been JITed.
The closest you could get would be to dynamically create a subtype with Reflection.Emit and copy the existing fields over, but you'd have to update all references to the the object yourself.
You also wouldn't be able to access those properties at compile time.
Something like:
public class Dynamic
{
public Dynamic Add<T>(string key, T value)
{
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly"), AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Dynamic.dll");
TypeBuilder typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString());
typeBuilder.SetParent(this.GetType());
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(key, PropertyAttributes.None, typeof(T), Type.EmptyTypes);
MethodBuilder getMethodBuilder = typeBuilder.DefineMethod("get_" + key, MethodAttributes.Public, CallingConventions.HasThis, typeof(T), Type.EmptyTypes);
ILGenerator getter = getMethodBuilder.GetILGenerator();
getter.Emit(OpCodes.Ldarg_0);
getter.Emit(OpCodes.Ldstr, key);
getter.Emit(OpCodes.Callvirt, typeof(Dynamic).GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(typeof(T)));
getter.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getMethodBuilder);
Type type = typeBuilder.CreateType();
Dynamic child = (Dynamic)Activator.CreateInstance(type);
child.dictionary = this.dictionary;
dictionary.Add(key, value);
return child;
}
protected T Get<T>(string key)
{
return (T)dictionary[key];
}
private Dictionary<string, object> dictionary = new Dictionary<string,object>();
}
I don't have VS installed on this machine so let me know if there are any massive bugs (well... other than the massive performance problems, but I didn't write the specification!)
Now you can use it:
Dynamic d = new Dynamic();
d = d.Add("MyProperty", 42);
Console.WriteLine(d.GetType().GetProperty("MyProperty").GetValue(d, null));
You could also use it like a normal property in a language that supports late binding (for example, VB.NET)
Try this
Install
npm install primeng --save
Import
import {FileUploadModule} from 'primeng/primeng';
Html
<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
accept="image/*" auto="auto"></p-fileUpload>
In case you just need one (first) value to retrieve from xml:
public static String getTagValue(String xml, String tagName){
return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}
In case you want to parse whole xml document use JSoup:
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
for (Element e : doc.select("Request")) {
System.out.println(e);
}
It's also possible to pre-allocate large enough memory size. Here is a simple stack implementation: the program is supposed to output 3 and 5.
class Stk {
static public final int STKSIZ = 256;
public int[] info = new int[STKSIZ];
public int sp = 0; // stack pointer
public void push(int value) {
info[sp++] = value;
}
}
class App {
public static void main(String[] args) {
Stk stk = new Stk();
stk.push(3);
stk.push(5);
System.out.println(stk.info[0]);
System.out.println(stk.info[1]);
}
}
if you need copy local file to server (specify port )
scp -P 3838 /the/source/file [email protected]:/destination/file
npm install
installs the depedendencies in your package.json config.npm run build
runs the script "build" and created a script which runs your application - let's say server.jsnpm start
runs the "start" script which will then be "node server.js"It's difficult to tell exactly what the issue was but basically if you look at your scripts configuration, I would guess that "build" uses some kind of build tool to create your application while "start" assumes the build has been done but then fails if the file is not there.
You are probably using bower or grunt - I seem to remember that a typical grunt application will have defined those scripts as well as a "clean" script to delete the last build.
Build tools tend to create a file in a bin/, dist/, or build/ folder which the start script then calls - e.g. "node build/server.js". When your npm start
fails, it is probably because you called npm clean
or similar to delete the latest build so your application file is not present causing npm start to fail.
npm build's source code - to touch on the discussion in this question - is in github for you to have a look at if you like. If you run npm build
directly and you have a "build" script defined, it will exit with an error asking you to call your build script as npm run-script build
so it's not the same as npm run script
.
I'm not quite sure what npm build
does, but it seems to be related to postinstall and packaging scripts in dependencies. I assume that this might be making sure that any CLI build scripts's or native libraries required by dependencies are built for the specific environment after downloading the package. This will be why link and install call this script.
Please try this code:-
$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo "$result";
The PHP solution, in backend:
$string = `UPPERCASE`
$lowercase = strtolower($string);
echo ucwords($lowercase);
ArrayList<String[]> action = new ArrayList<String[]>();
Don't need String[2]
;
You can use a tool I wrote that bypasses the limit.
It saves the Tweets in a JSON format.
I had this problem too. I used the disableSelection()
method of jQuery UI on a parent DIV which contained my input fields. In Chrome the input fields were not affected but in Firefox the inputs (and textareas as well) did not get focused on clicking. The strange thing here was, that the click event on these inputs worked.
The solution was to remove the disableSelection()
method for the parent DIV.
For the benefit of Swift 3 beginners:
Here is a code sample to verify if a file named "database.sqlite" exists in application document directory:
func findIfSqliteDBExists(){
let docsDir : URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dbPath : URL = docsDir.appendingPathComponent("database.sqlite")
let strDBPath : String = dbPath.path
let fileManager : FileManager = FileManager.default
if fileManager.fileExists(atPath:strDBPath){
print("An sqlite database exists at this path :: \(strDBPath)")
}else{
print("SQLite NOT Found at :: \(strDBPath)")
}
}
On Windows, I have found that the important thing is to start Eclipse from the command line rather than from the Start Menu or a shortcut, provided that the native DLL is in a directory in your PATH. Apparently, this ensures that the proper directory is on the path.
If you don't want to use external libs, then one solution is to recreate the reload method from python 2 for python 3 as below. Use this in the top of the module (assumes python 3.4+).
import sys
if(sys.version_info.major>=3):
def reload(MODULE):
import importlib
importlib.reload(MODULE)
BTW reload is very much required if you use python files as config files and want to avoid restarts of the application.....
Install these 2 packages
<packages>
<package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
<package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>
Helper function
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelToCsv
{
public class ExcelFileHelper
{
public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
{
using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
IExcelDataReader reader = null;
if (excelFilePath.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (excelFilePath.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
if (reader == null)
return false;
var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
UseHeaderRow = false
}
});
var csvContent = string.Empty;
int row_no = 0;
while (row_no < ds.Tables[0].Rows.Count)
{
var arr = new List<string>();
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
}
row_no++;
csvContent += string.Join(",", arr) + "\n";
}
StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
csv.Write(csvContent);
csv.Close();
return true;
}
}
}
}
Usage :
var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);
Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).
Assuming you want the text in the centre of the bitmap, you can do this:
// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");
// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);
// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);
// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing).
// One exception is that path gradient brushes do not obey the smoothing mode.
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;
// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);
// Flush all graphics changes to the bitmap
g.Flush();
// Now save or use the bitmap
image.Image = bmp;
Note that in general, Mockito does allow throwing checked exceptions so long as the exception is declared in the message signature. For instance, given
class BarException extends Exception {
// this is a checked exception
}
interface Foo {
Bar frob() throws BarException
}
it's legal to write:
Foo foo = mock(Foo.class);
when(foo.frob()).thenThrow(BarException.class)
However, if you throw a checked exception not declared in the method signature, e.g.
class QuxException extends Exception {
// a different checked exception
}
Foo foo = mock(Foo.class);
when(foo.frob()).thenThrow(QuxException.class)
Mockito will fail at runtime with the somewhat misleading, generic message:
Checked exception is invalid for this method!
Invalid: QuxException
This may lead you to believe that checked exceptions in general are unsupported, but in fact Mockito is only trying to tell you that this checked exception isn't valid for this method.
There is one way to make an immutable array in Java:
final String[] IMMUTABLE = new String[0];
Arrays with 0 elements (obviously) cannot be mutated.
This can actually come in handy if you are using the List.toArray
method to convert a List
to an array. Since even an empty array takes up some memory, you can save that memory allocation by creating a constant empty array, and always passing it to the toArray
method. That method will allocate a new array if the array you pass doesn't have enough space, but if it does (the list is empty), it will return the array you passed, allowing you to reuse that array any time you call toArray
on an empty List
.
final static String[] EMPTY_STRING_ARRAY = new String[0];
List<String> emptyList = new ArrayList<String>();
return emptyList.toArray(EMPTY_STRING_ARRAY); // returns EMPTY_STRING_ARRAY
There is a jquery print area. I've been using it for some time now.
$(".printMe").click(function(){
$("#outprint").printArea({ mode: 'popup', popClose: true });
});
First step is to save all open notebooks. And then think about shutting down your running Jupyter Notebook. You can use this simple command:
$ jupyter notebook stop
Shutting down server on port 8888 ...
Which also takes the port number as argument and you can shut down the jupyter notebook gracefully.
For eg:
jupyter notebook stop 8889
Shutting down server on port 8889 ...
Additionally to know your current jupyter instance running, check below command:
shell> jupyter notebook list
Currently running servers:
http://localhost:8888/?token=ef12021898c435f865ec706de98632 :: /Users/username/jupyter-notebooks [/code]
Are you using Forms authentication?
Forms authentication uses it own value for timeout (30 min. by default). A forms authentication timeout will send the user to the login page with the session still active. This may look like the behavior your app gives when session times out making it easy to confuse one with the other.
<system.web>
<authentication mode="Forms">
<forms timeout="50"/>
</authentication>
<sessionState timeout="60" />
</system.web>
Setting the forms timeout to something less than the session timeout can give the user a window in which to log back in without losing any session data.
You don't tend to execute the make file itself, rather you execute make
, giving it the make file as an argument:
make -f pax.mk
If your make file is actually one of the standard names (like makefile
or Makefile
), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make
man page to see which takes precedence).
In the SQL Server, try these steps:
Server Object
.Linked Servers
.Providers
.Microsoft.ACE.OLEDB.12.0
and click Properties
.This solution also prevents the addition of a trailing comma.
var filenames = String.Join(
", ",
Directory.GetFiles(@"c:\", "*.txt")
.Select(filename =>
Path.GetFileNameWithoutExtension(filename)));
I dislike the DirectoryInfo, FileInfo for this scenario.
DirectoryInfo and FileInfo collect more data about the folder and the files than is needed so they take more time and memory than necessary.
I would take those directions to mean:
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
var obj = { //note you don't use = in an object definition
"name": name,
"totalScore": totalScore,
"gamesPlayed": gamesPlayed
}
return obj;
}
You should use val
instead of value
.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('input[name="testing"]').val('Work!');
});
</script>
If you're in local machine then use this command
/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
For remote machine, use below one
/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
if you want to access table cell
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));
If you want to access nested table cell -
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));
For more details visit this Tutorial
This is the way to execute remote script with passing to it some arguments (arg1 arg2):
curl -s http://server/path/script.sh | bash /dev/stdin arg1 arg2
Is your SQL Server in 'mixed mode authentication' ? This is necessary to login with a SQL server account instead of a Windows login.
You can verify this by checking the properties of the server and then SECURITY, it should be in 'SQL Server and Windows Authentication Mode'
This problem occurs if the user tries to log in with credentials that cannot be validated. This problem can occur in the following scenarios:
Scenario 1: The login may be a SQL Server login but the server only accepts Windows Authentication.
Scenario 2: You are trying to connect by using SQL Server Authentication but the login used does not exist on SQL Server.
Scenario 3: The login may use Windows Authentication but the login is an unrecognized Windows principal. An unrecognized Windows principal means that Windows can't verify the login. This might be because the Windows login is from an untrusted domain.
It's also possible the user put in incorrect information.
Starting with C# 8.0, you can use the ??= operator to replace the code of the form
if (variable is null)
{
variable = expression;
}
with the following code:
variable ??= expression;
More information is here
I wanted to create a MarkdownPreviewer in react as part of a project in freecodecamp. So I was desperately searching for newline characters for markdown. After trying many suggestions. I finally used \n and it worked.