I know its quite late but for anyone looking to do it from now on, I hope this answer proves of some help. If you have CodeRush Express
(free version, and a 'must have') installed, it offers a simple way to change a project wide namespace. You just place your cursor on the namespace that you want to change and it shall display a smart tag
(a little blue box) underneath namespace
string. You can either click that box or press Ctrl + keys to see the Rename
option. Select it and then type in the new name for the project wide namespace, click Apply
and select what places in your project you'd want it to change, in the new dialog and OK
it. Done! :-)
This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.
The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO
, rather than ...ON_ZERO
. (There have been occasional discussions about whether this is a confusing name.)
You should read the expression like this:
sizeof(struct { int: -!!(e); }))
(e)
: Compute expression e
.
!!(e)
: Logically negate twice: 0
if e == 0
; otherwise 1
.
-!!(e)
: Numerically negate the expression from step 2: 0
if it was 0
; otherwise -1
.
struct{int: -!!(0);} --> struct{int: 0;}
: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.
struct{int: -!!(1);} --> struct{int: -1;}
: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.
So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof
that field, so we get a size_t
with the appropriate width (which will be zero in the case where e
is zero).
Some people have asked: Why not just use an assert
?
keithmo's answer here has a good response:
These macros implement a compile-time test, while assert() is a run-time test.
Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.
try this for sql server
CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS
INSERT INTO yourDestinationTable
(col1, col2 , col3, user_id, user_name)
SELECT
'a' , default , null, user_id, user_name
FROM inserted
go
PyLibTiff worked better for me than PIL, which as of December 2020 still doesn't support color images with more than 8 bits per color.
from libtiff import TIFF
tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the currect TIFF directory as a numpy array
image = tif.read_image()
# read all images in a TIFF file:
for image in tif.iter_images():
pass
tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)
You can install PyLibTiff with
pip3 install numpy libtiff
The readme of PyLibTiff also mentions the tifffile
library but I haven't tried it.
Another Way which worked for me is:
After dettaching before you attach
-> go to the .mdf file -> right click & select properties on the file -> security tab -> Check Group or usernames:
for your name\account (optional) and for "NT SERVICE\MSSQLSERVER"(NB)
List item
-> if not there than click on edit button -> click on add button
and enter\search NT SERVICE\MSSQLSERVER
-> click on OK -> give full rights -> apply then ok
then ok again do this for .ldf file too.
then attach
Easiest way:
$injector = angular.element(document.body).injector()
Then use that to run invoke()
or get()
Not sure if this is the cause of the problem, but I got this issue only after installing JVM Monitor.
Uninstalling JVM Monitor solved the issue for me.
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
There are a couple of options:
My preferred option would be the first one, if it's a short space, or the latter otherwise.
I have edited the "Best answer" code, though I found a useful thing that was missing. This is will also track the ip of a user if they are using a Proxy or simply if the server has nginx installed as a proxy reverser.
I added this code to his script at the top of the function:
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$adresseip = getRealIpAddr();
Afther that I edited his code.
Find the line that says the following:
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
and replace it with this:
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;
This will work.
Here is the full code if anything happens:
<?php
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$adresseip = getRealIpAddr();
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
$filetxt = 'userson.txt'; // the file in which the online users /visitors are stored
$timeon = 120; // number of secconds to keep a user online
$sep = '^^'; // characters used to separate the user name and date-time
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the line with visitors
$nrvst = 0; // to store the number of visitors
// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)
$addrow[] = $uvon. $sep. time();
// check if the file from $filetxt exists and is writable
if(is_writable($filetxt)) {
// get into an array the lines added in $filetxt
$ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($ar_rows);
// number of rows
// if there is at least one line, parse the $ar_rows array
if($nrrows>0) {
for($i=0; $i<$nrrows; $i++) {
// get each line and separate the user /visitor and the timestamp
$ar_line = explode($sep, $ar_rows[$i]);
// add in $addrow array the records in last $timeon seconds
if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
$addrow[] = $ar_rows[$i];
}
}
}
}
$nruvon = count($addrow); // total online
$usron = ''; // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
if(preg_match($rgxvst, $addrow[$i])) $nrvst++; // increment the visitors
else {
// gets and stores the user's name
$ar_usron = explode($sep, $addrow[$i]);
$usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
}
}
$nrusr = $nruvon - $nrvst; // gets the users (total - visitors)
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
Haven't tested this on the Sql script yet.
My guess is that rake
is a batch program. When you invoke it without call
, then control doesn't return to your build.bat
. Try:
@echo off
cls
CALL rake
pause
TL;DR;
Set "Build Active Architecture Only (ONLY_ACTIVE_ARCH
)" to Yes for your libraries/apps, even for release mode.
While trying to identify the root cause of the issue I realized some fun facts about Xcode 12.
Xcode 12 is actually the stepping stone for Apple Silicon which unfortunately is not yet available (when the answer was written). But with that platform we are gonna get arm64 based macOS where simulators will also run on arm64 architecture unlike the present Intel based x86_64 architecture.
Xcode usually depends on the "Run Destination" to build its libraries/apps. So when a simulator is chosen as the "Run Destination", it builds the app for available simulator architectures and when a device is chosen as the "Run Destination" it builds for the architecture that the device supports (arm*
).
xcodebuild
, in the Xcode 12+ build system considers arm64
as a valid architecture for simulator to support Apple Silicon. So when a simulator is chosen as the run destination, it can potentially try to compile/link your libs/apps against arm64
based simulators, as well. So it sends clang(++)
some -target flag like arm64-apple-ios13.0-simulator
in <architecture>-<os>-<sdk>-<destination> format and clang tries to build/link against arm64 based simulator that eventually fails on Intel based mac.
But xcodebuild
tries this only for Release builds. Why? Because, "Build Active Architecture Only (ONLY_ACTIVE_ARCH
)" build settings is usually set to "No" for the "Release" configuration only. And that means xcodebuild
will try to build all architectural variants of your libs/apps for the selected run destination for release builds. And for the Simulator run destination, it will includes both x86_64
and arm64
now on, since arm64
in Xcode 12+ is also a supported architecture for simulators to support Apple Silicon.
Simply putting, Xcode will fail to build your app anytime it tries the command line, xcodebuild
, (which defaults to release build, see the general tab of your project setting) or otherwise and tries to build all architectural variants supported by the run destination. So a simple workaround to this issue is to set "Build Active Architecture Only (ONLY_ACTIVE_ARCH
)" to Yes in your libraries/apps, even for release mode.
If the libraries are included as Pods and you have access to .podspec
you can simply set:
spec.pod_target_xcconfig = { 'ONLY_ACTIVE_ARCH' => 'YES' }
spec.user_target_xcconfig = { 'ONLY_ACTIVE_ARCH' => 'YES' } # not recommended
I personally don't like the second line since pods shouldn't pollute the target project and it could be overridden in the target settings, itself. So it should be the responsibility of the consumer project to override the setting by some means. However, this could be necessary for successful linting of podspecs.
However, if you don't have access to the .podspec
, you can always update the settings during installation of the pods:
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings["ONLY_ACTIVE_ARCH"] = "YES"
end
end
end
One thing I was concerned about that what will be the impact of this when we actually archive the libs/apps. During archiving apps usually take the "Release" configuration and since this will be creating a release build considering only the active architecture of the current run destination, with this approach, we may lose the slices for armv7, armv7s, etc from target build. However, I noticed the documentation says (highlighted in the attached picture) that this setting will be ignored when we choose "Generic iOS Device/Any Device" as the run destination, since it doesn't define any specific architecture. So I guess we should be good if we archive our app choosing that as a run destination.
jQuery takes care of this for you. The first argument to your .each()
callback function is the index of the current iteration of the loop. The second being the current matched DOM element So:
$('#list option').each(function(index, element){
alert("Iteration: " + index)
});
No, actually, if you are thinking class
and struct
mean class
es and struct
s, you're wrong. class
means any reference type (e.g. includes interfaces too) and struct
means any value type (e.g. struct
, enum
).
Though this is an old post and have many answers, but here I have my version of code to upload the file to sharepoint 2013 using CSOM(c#)
I hope if you are working with downloading and uploading files then you know how to create Clientcontext
object and Web
object
/* Assuming you have created ClientContext object and Web object*/
string listTitle = "List title where you want your file to upload";
string filePath = "your file physical path";
List oList = web.Lists.GetByTitle(listTitle);
clientContext.Load(oList.RootFolder);//to load the folder where you will upload the file
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.Overwrite = true;
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = fileName;
File fileToUpload = fileCollection.Add(fileInfo);
clientContext.ExecuteQuery();
fileToUpload.CheckIn("your checkin comment", CheckinType.MajorCheckIn);
if (oList.EnableMinorVersions)
{
fileToUpload.Publish("your publish comment");
clientContext.ExecuteQuery();
}
if (oList.EnableModeration)
{
fileToUpload.Approve("your approve comment");
}
clientContext.ExecuteQuery();
And here is the code for download
List oList = web.Lists.GetByTitle("ListNameWhereFileExist");
clientContext.Load(oList);
clientContext.Load(oList.RootFolder);
clientContext.Load(oList.RootFolder.Files);
clientContext.ExecuteQuery();
FileCollection fileCollection = oList.RootFolder.Files;
File SP_file = fileCollection.GetByUrl("fileNameToDownloadWithExtension");
clientContext.Load(SP_file);
clientContext.ExecuteQuery();
var Local_stream = System.IO.File.Open("c:/testing/" + SP_file.Name, System.IO.FileMode.CreateNew);
var fileInformation = File.OpenBinaryDirect(clientContext, SP_file.ServerRelativeUrl);
var Sp_Stream = fileInformation.Stream;
Sp_Stream.CopyTo(Local_stream);
Still there are different ways I believe that can be used to upload and download.
So is this the answer?
"If you need to calculate something but not show it, set the element to visibility:hidden
and position:absolute
, add it to the DOM tree, get the offsetHeight, and remove it. (That's what the prototype library does behind the lines last time I checked)."
I have the same problem on a number of elements. There is no jQuery or Prototype to be used on the site but I'm all in favor of borrowing the technique if it works. As an example of some things that failed to work, followed by what did, I have the following code:
// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
var DoOffset = true;
if (!elementPassed) { return 0; }
if (!elementPassed.style) { return 0; }
var thisHeight = 0;
var heightBase = parseInt(elementPassed.style.height);
var heightOffset = parseInt(elementPassed.offsetHeight);
var heightScroll = parseInt(elementPassed.scrollHeight);
var heightClient = parseInt(elementPassed.clientHeight);
var heightNode = 0;
var heightRects = 0;
//
if (DoBase) {
if (heightBase > thisHeight) { thisHeight = heightBase; }
}
if (DoOffset) {
if (heightOffset > thisHeight) { thisHeight = heightOffset; }
}
if (DoScroll) {
if (heightScroll > thisHeight) { thisHeight = heightScroll; }
}
//
if (thisHeight == 0) { thisHeight = heightClient; }
//
if (thisHeight == 0) {
// Dom Add:
// all else failed so use the protype approach...
var elBodyTempContainer = document.getElementById('BodyTempContainer');
elBodyTempContainer.appendChild(elementPassed);
heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
elBodyTempContainer.removeChild(elementPassed);
if (heightNode > thisHeight) { thisHeight = heightNode; }
//
// Bounding Rect:
// Or this approach...
var clientRects = elementPassed.getClientRects();
heightRects = clientRects.height;
if (heightRects > thisHeight) { thisHeight = heightRects; }
}
//
// Default height not appropriate here
// if (thisHeight == 0) { thisHeight = elementHeightDefault; }
if (thisHeight > 3000) {
// ERROR
thisHeight = 3000;
}
return thisHeight;
}
which basically tries anything and everything only to get a zero result. ClientHeight with no affect. With the problem elements I typically get NaN in the Base and zero in the Offset and Scroll heights. I then tried the Add DOM solution and clientRects to see if it works here.
29 Jun 2011, I did indeed update the code to try both adding to DOM and clientHeight with better results than I expected.
1) clientHeight was also 0.
2) Dom actually gave me a height which was great.
3) ClientRects returns a result almost identical to the DOM technique.
Because the elements added are fluid in nature, when they are added to an otherwise empty DOM Temp element they are rendered according to the width of that container. This get weird, because that is 30px shorter than it eventually ends up.
I added a few snapshots to illustrate how the height is calculated differently.
The height differences are obvious. I could certainly add absolute positioning and hidden but I am sure that will have no effect. I continued to be convinced this would not work!
(I digress further) The height comes out (renders) lower than the true rendered height. This could be addressed by setting the width of the DOM Temp element to match the existing parent and could be done fairly accurately in theory. I also do not know what would result from removing them and adding them back into their existing location. As they arrived through an innerHTML technique I will be looking using this different approach.
* HOWEVER * None of that was necessary. In fact it worked as advertised and returned the correct height!!!
When I was able to get the menus visible again amazingly DOM had returned the correct height per the fluid layout at the top of the page (279px). The above code also uses getClientRects which return 280px.
This is illustrated in the following snapshot (taken from Chrome once working.)
Now I have noooooo idea why that prototype trick works, but it seems to. Alternatively, getClientRects also works.
I suspect the cause of all this trouble with these particular elements was the use of innerHTML instead of appendChild, but that is pure speculation at this point.
After looking through all the answers, I was surprised to see that no one mentioned the Glide API for handling images. Great library, and abstracts out all the complexity of bitmap management. You can load and resize images quickly with this library and a single line of code.
Glide.with(this).load(yourImageResource).into(imageview);
You can get the repository here: https://github.com/bumptech/glide
This confused me for a while until I worked out that the dependencies of the various projects in the solution had been messed up. Get that straight and naturally your assembly appears in the right place.
The following script catenates several (relative/absolute) paths (BASEPATH) with a relative path (SUBDIR):
shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done
The output of which is:
BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir
The shopt -s extglob
is only necessary to allow BASEPATH to end on multiple slashes (which is probably nonsense). Without extended globing you can just use:
echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR
which would result in the less neat but still working:
BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir
edtFTPnet is a free, fast, open source FTP library for .NET, written in C#.
Use .lower()
- For example:
s = "Kilometer"
print(s.lower())
The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()
Functors are used in gtkmm to connect some GUI button to an actual C++ function or method.
If you use the pthread library to make your app multithreaded, Functors can help you.
To start a thread, one of the arguments of the pthread_create(..)
is the function pointer to be executed on his own thread.
But there's one inconvenience. This pointer can't be a pointer to a method, unless it's a static method, or unless you specify it's class, like class::method
. And another thing, the interface of your method can only be:
void* method(void* something)
So you can't run (in a simple obvious way), methods from your class in a thread without doing something extra.
A very good way of dealing with threads in C++, is creating your own Thread
class. If you wanted to run methods from MyClass
class, what I did was, transform those methods into Functor
derived classes.
Also, the Thread
class has this method:
static void* startThread(void* arg)
A pointer to this method will be used as an argument to call pthread_create(..)
. And what startThread(..)
should receive in arg is a void*
casted reference to an instance in heap of any Functor
derived class, which will be casted back to Functor*
when executed, and then called it's run()
method.
This schema has changed again (23rd October 2018). See Kushagr's answer for the latest.
This for a map with the marker (via aaronm's comment):
https://www.google.com/maps/?q=-15.623037,18.388672
For an older example (no marker on this one):
https://www.google.com/maps/preview/@-15.623037,18.388672,8z
The oldest format:
http://maps.google.com/maps?ll=-15.623037,18.388672&spn=65.61535,79.013672
DataType
has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint
attribute.
Adding a new core DataType is not possible since the DataType
enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute
. Then you can add a new constructor with your own DataType
enumeration.
public NewDataTypeAttribute(DataType dataType) : base(dataType)
{ }
public NewDataTypeAttribute(NewDataType newDataType) : base (newDataType.ToString();
You can also go through this link. But I will recommend you using Jquery for the same.
below answer support api level below and above 10
if (Build.VERSION.SDK_INT >= 11) {
Point size = new Point();
try {
this.getWindowManager().getDefaultDisplay().getRealSize(size);
screenWidth = size.x;
screenHeight = size.y;
} catch (NoSuchMethodError e) {
screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
screenWidth=this.getWindowManager().getDefaultDisplay().getWidth();
}
} else {
DisplayMetrics metrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
}
Its must you file dump.sql problem.Use Sequel Pro check your file ecoding.It should be garbage characters in your dump.sql.
del /s /q c:\where ever the file is\*
rmdir /s /q c:\where ever the file is\
mkdir c:\where ever the file is\
The simplest way is to use the safe
filter:
{{ message|safe }}
Check out the Django documentation for the safe filter for more information.
This can be done via CSS. The "pointer-events" property is what's preventing the tooltip from appearing. You can get disabled buttons to display tooltip by overriding the "pointer-events" property set by bootstrap.
.btn.disabled {
pointer-events: auto;
}
I would look at the Join operator:
from r in list join i in listofIds on r.Id equals i select r
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.
Edit: Extension method syntax for completeness (now that I've figured it out):
var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
This error message is easy to reproduce.
cmd
, Enter.
On Linux: Ctrl + Alt + t.)npm
and hit Enter to see if Node.js is installed.command not found
, download at https://nodejs.org/en/download/
and install.sudo apt install nodejs
if you prefer.)node thisFileDoesNotExist.js
(and hit Enter).On Windows expect to see something similar to:
internal/modules/cjs/loader.js:969
throw err;
^
Error: Cannot find module [... + a few more lines]
On Linux (Ubuntu 18.04):
module.js:549
throw err;
^
Error: Cannot find module [...]
I have not tried macOS, but would expect something similar there as well.
Note: This might happen for no apparent reason when debugging
in Visual Studio Code.
If you get the error inside VScode, see if the answer by
HappyHands31
is of any help.
Finally, to run Node.js in the terminal without an error, in the Windows terminal (command line) try:
echo console.log('\nHello world!')> hello.js
node hello.js
In the Linux terminal try:
echo "console.log('\nHello world\!\n')"> hello.js
node hello.js
Of course, expect to see the terminal responding:
Hello world!
You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".
It's probably not working due to one of:
To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.
For example:
$(document).ready(function() {
// This WILL work because we are listening on the 'document',
// for a click on an element with an ID of #test-element
$(document).on("click","#test-element",function() {
alert("click bound to document listening for #test-element");
});
// This will NOT work because there is no '#test-element' ... yet
$("#test-element").on("click",function() {
alert("click bound directly to #test-element");
});
// Create the dynamic element '#test-element'
$('body').append('<div id="test-element">Click mee</div>');
});
In this example, only the "bound to document" alert will fire.
Is this what you are looking for? Otherwise, let me know and I will remove this post.
Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect
Demo: http://www.stoimen.com/jquery.client.plugin/
This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.
For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html
And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js
you can use basename property
PS II> ls *.ps1 | select basename
You can try this it has worked for me.
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="//www.youtube.com/embed/PEwac2WZ7rU?rel=0?version=3&autoplay=1&controls=0&&showinfo=0&loop=1"></iframe>
</div>
Responsive embed using Bootstap
Allow browsers to determine video or slideshow dimensions based on the width of their containing block by creating an intrinsic ratio that will properly scale on any device.
Style youtube video:
For more information please visit this link https://developers.google.com/youtube/player_parameters#autoplay
Thanks
BanyanTheme
Your standard project setup will have a project structure something like:
src/main/java
src/main/resources
You place log4j.properties inside the resources folder, you can create the resources folder if one does not exist
What about something like this?
<?php
$URL = "http://example.com";
$base = '<base href="'.$URL.'">';
$host = preg_replace('/^[^\/]+\/\//', '', $URL);
$tarray = explode('/', $host);
$host = array_shift($tarray);
$URI = '/' . implode('/', $tarray);
$content = '';
$fp = @fsockopen($host, 80, $errno, $errstr, 30);
if(!$fp) { echo "Unable to open socked: $errstr ($errno)\n"; exit; }
fwrite($fp,"GET $URI HTTP/1.0\r\n");
fwrite($fp,"Host: $host\r\n");
if( isset($_SERVER["HTTP_USER_AGENT"]) ) { fwrite($fp,'User-Agent: '.$_SERVER
["HTTP_USER_AGENT"]."\r\n"); }
fwrite($fp,"Connection: Close\r\n");
fwrite($fp,"\r\n");
while (!feof($fp)) { $content .= fgets($fp, 128); }
fclose($fp);
if( strpos($content,"\r\n") > 0 ) { $eolchar = "\r\n"; }
else { $eolchar = "\n"; }
$eolpos = strpos($content,"$eolchar$eolchar");
$content = substr($content,($eolpos + strlen("$eolchar$eolchar")));
if( preg_match('/<head\s*>/i',$content) ) { echo( preg_replace('/<head\s*>/i','<head>'.
$base,$content,1) ); }
else { echo( preg_replace('/<([a-z])([^>]+)>/i',"<\\1\\2>".$base,$content,1) ); }
?>
Actually this is the path and you should mention a valid path for this to work. If your data directory is in current directory then instead of my-data
you should mention ./my-data
, otherwise it will give you that error in mysql
and mariadb
also.
volumes:
./my-data:/var/lib/mysql
Here is an example for toggling bold, underline, and italics.
protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
{
if ( ActiveControl is RichTextBox r )
{
if ( keyData == ( Keys.Control | Keys.B ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.U ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
return true;
}
if ( keyData == ( Keys.Control | Keys.I ) )
{
r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
return true;
}
}
return base.ProcessCmdKey( ref msg, keyData );
}
It really helpful for the clickable part for some portion of the text.
The dot is a special character in the regular expression. If you want to spanable the dot need to escape dot as \\
. instead of just passing ".
" to the spanable text method. Alternatively, you can also use the regular expression [.]
to spanable the String by a dot in Java.
If you are using ssh in background, use this:
sudo lsof -i -n | egrep '\<ssh\>'
you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.
You should always consider a non-vba solution first.
Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):
http://www.youtube.com/watch?v=RCLUM0UMLXo
http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx
If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.
If it has to be the latter, then there is need for more details on your specification, regarding performance questions.
You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.
This would look something like that:
Public Sub CopyFilter()
Dim wks As Worksheet
Dim avarTemp() As Variant
'go through each worksheet
For Each wks In ThisWorkbook.Worksheets
avarTemp = wks.UsedRange
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
'check in the first column in each row
If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
'copy cell
targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
End If
Next i
Next wks
End Sub
Ok, now i have something nice which could come in handy for myself:
Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
Dim avarTemp() As Variant
Dim avarResult() As Variant
Dim i As Long
avarTemp = rng
ReDim avarResult(0)
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
If avarTemp(i, 1) = "active" Then
avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
'expand our result array
ReDim Preserve avarResult(UBound(avarResult) + 1)
End If
Next i
FILTER = avarResult
End Function
You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)
The accepted answer previously contained new Buffer()
, which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).
The Buffer
constructor is deprecated according to the documentation.
Here is an example of a vulnerability that can result from using it in the ws library.
The code snippets should read:
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
After this answer was written, it has been updated and now matches this.
I think you should not use spaces between the [(ngModel)]
the =
and the str
. Then you should use a button or something like this with a click function and in this function you can use the values of your inputfields
.
<input id="str" [(ngModel)]="str"/>
<button (click)="sendValues()">Send</button>
and in your component file
str: string;
sendValues(): void {
//do sth with the str e.g. console.log(this.str);
}
Hope I can help you.
Resolved by adding the following exclusion in the dependencies (of pom.xml) that caused conflict.
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
You probably want pop
:
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
By default, pop
without any arguments removes the last item:
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
I had same issue. I used PIL Image to load the images and converted to a numpy array then patched a rectangle using matplotlib. It was a jpg image, so there was no way for me to get the dpi from PIL img.info['dpi'], so the accepted solution did not work for me. But after some tinkering I figured out way to save the figure with the same size as the original.
I am adding the following solution here thinking that it will help somebody who had the same issue as mine.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
img = Image.open('my_image.jpg') #loading the image
image = np.array(img) #converting it to ndarray
dpi = plt.rcParams['figure.dpi'] #get the default dpi value
fig_size = (img.size[0]/dpi, img.size[1]/dpi) #saving the figure size
fig, ax = plt.subplots(1, figsize=fig_size) #applying figure size
#do whatver you want to do with the figure
fig.tight_layout() #just to be sure
fig.savefig('my_updated_image.jpg') #saving the image
This saved the image with the same resolution as the original image.
In case you are not working with a jupyter notebook. you can get the dpi in the following manner.
figure = plt.figure()
dpi = figure.dpi
<ul>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
<li>this is my text</li>
</ul>
you can use this simple css style
ul {
list-style-type: '\2713';
}
The easiest way is:
<h:outputText value=" " />
The pythonic way to read a file and put every lines in a list:
from __future__ import with_statement #for python 2.5
with open('C:/path/numbers.txt', 'r') as f:
lines = f.readlines()
Then, assuming that each lines contains a number,
numbers =[int(e.strip()) for e in lines]
I was having this issue and fixed it by going to: C:\Dev-Cpp\libexec\gcc\mingw32\3.4.2 , then deleting collect2.exe
Update one table using Inner Join
UPDATE Table1 SET name=ml.name
FROM table1 t inner JOIN
Table2 ml ON t.ID= ml.ID
For me the issue was a conflict between several versions of the same library. The Eclipse assist was using an older version than maven.
I had to go to the .m2 directory and delete the unwanted lib version + restart eclipse.
Apologies for my previously mixed up answer.
Here is how to do:
myTreeView.SelectedNode = myTreeNode;
I have tested the code below and it works:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
treeView1.Nodes.Add("1", "1");
treeView1.Nodes.Add("2", "2");
treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
treeView1.SelectedNode = treeNode;
MessageBox.Show(treeNode.IsSelected.ToString());
}
}
Using Newton C++
bool exists_linear( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )
bool exists_binary( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )
the code will be something like this:
if ( newton::exists_linear(arr.begin(), arr.end(), value) )
std::cout << "found" << std::endl;
else
std::cout << "not found" << std::endl;
both exists_linear and exists_binary use std implementations. binary use std::binary_search, and linear use std::find, but return directly a bool, not an iterator.
Seems like the problem is with the date format.
var d = "17-09-2013 10:08",
dArr = d.split('-'),
ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000
item = objects.Find(obj => obj.property==myValue);
Update : for the new apache 2.4 jump directly to the end.
The Order keyword and its relation with Deny
and Allow
Directives is a real nightmare. It would be quite interesting to understand how we ended up with such solution, a non-intuitive one to say the least.
Order
keyword will have a big impact on how Allow
and Deny
directives are used.Deny
and Allow
directives are not applied in the order they are written, they must be seen as two distinct blocks (one the for Deny
directives, one for Allow
).You have two main modes:
Order Deny,Allow
Deny
rules.Deny
rules reject some requests.Allow
.I would rephrase it as:
Rule Deny
list of Deny rules
Except
list of Allow rules
Policy Allow (when no rule fired)
Order Allow,Deny
Allow
rules.Allow
rule.Allow
, you can still reject them with a Deny
.In the simplified form:
Rule Allow
list of Allow rules
Except
list of Deny rules
Policy Deny (when no rule fired)
You need to allow a list of networks which are the country networks. And in this country you want to exclude some proxies' IP addresses.
You have taken the allow-anyone-except-this-list-or-maybe-not mode, so by default anyone can access your server, except proxies' IPs listed in the Deny
list, but if they get rejected you still allow the country networks. That's too broad. Not good.
By inverting to order allow,deny
you will be in the reject-everyone-except-this-list-or-maybe-not mode.
So you will reject access to everyone but allow the country networks and then you will reject the proxies. And of course you must remove the Deny from all
as stated by @Gerben and @Michael Slade (this answer only explains what they wrote).
The Deny from all
is usually seen with order deny,allow
to remove the allow by default access and make a simple, readable configuration. For example, specify a list of allowed IPs after that. You don't need that rule and your question is a perfect case of a 3-way access mode (default policy, exceptions, exceptions to exceptions).
But the guys who designed these settings are certainly insane.
The whole authorization scheme has been refactored in Apache 2.4 with RequireAll, RequireAny and RequireNone directives. See for example this complex logic example.
So the old strange Order
logic becomes a relic, and to quote the new documentation:
Controling how and in what order authorization will be applied has been a bit of a mystery in the past
You need to use HttpWebRequest
rather than WebClient
as you can't set the timeout on WebClient
without extending it (even though it uses the HttpWebRequest
). Using the HttpWebRequest
instead will allow you to set the timeout.
You can use this function to get data type.
var myAr = [1,2];
checkType(myAr);
function checkType(data){
if(typeof data ==='object'){
if(Object.prototype.toString.call(data).indexOf('Array')!==(-1)){
return 'array';
} else{
return 'object';
}
} else {
return typeof data;
}
}
if(checkType(myAr) === 'array'){console.log('yes, It is an array')};
When using Bootstrap >= 3.0
source files (SASS
or LESS
) you don't have to get rid of the rounded corners on everything if there is just one element that is bugging you, for example, to just get rid of the rounded corners on the navbar, use:
$navbar-border-radius: 0;
@navbar-border-radius: 0;
However, if you do want to get rid of the rounded corners on everything, you can do what @adamwong246 mentioned and use:
$baseBorderRadius: 0;
@baseBorderRadius: 0;
Those two settings are the "root" settings from which the other settings like navbar-border-radius
will inherit from unless other values are specified.
For a list all variables check out the variables.less or variables.scss
You can also use a simple filtering function without any plugins. This is not exactly what you want but the result is the same:
$('a').data("user", {name: {first:"Tom",last:"Smith"},username: "tomsmith"});
$('a').filter(function() {
return $(this).data('user') && $(this).data('user').name.first === "Tom";
});
No need to cede.
just select pane ,right click then select Fit to parent.
It will automatically resize pane to anchor pane size.
I used a third party library called use-force-update to force render my react functional components. Worked like charm. Just use import the package in your project and use like this.
import useForceUpdate from 'use-force-update';
const MyButton = () => {
const forceUpdate = useForceUpdate();
const handleClick = () => {
alert('I will re-render now.');
forceUpdate();
};
return <button onClick={handleClick} />;
};
instead of url: serviceURL,
use
url: '<%= serviceURL%>',
and are you passing 2 parameters to successFunc?
function successFunc(data)
{
alert(data);
}
Wrapping a <a>
around won't work (unless you set the <div>
to display:inline-block;
or display:block;
to the <a>
) because the div is s a block-level element and the <a>
is not.
<a href="http://www.example.com" style="display:block;">
<div>
content
</div>
</a>
<a href="http://www.example.com">
<div style="display:inline-block;">
content
</div>
</a>
<a href="http://www.example.com">
<span>
content
</span >
</a>
<a href="http://www.example.com">
content
</a>
But maybe you should skip the <div>
and choose a <span>
instead, or just the plain <a>
. And if you really want to make the div clickable, you could attach a javascript redirect with a onclick handler, somethign like:
document.getElementById("myId").setAttribute('onclick', 'location.href = "url"');
but I would recommend against that.
You can use in
operator in conjunction with lower
method of strings.
if "mandy" in line.lower():
Note: I missed your question title which said Using Linq, so my answer does not in fact use Linq.
If you want to avoid caching a non-lazy copy of the entire collection, you could write a simple method that does it using a linked list.
The following method will add each value it finds in the original collection into a linked list, and trim the linked list down to the number of items required. Since it keeps the linked list trimmed to this number of items the entire time through iterating through the collection, it will only keep a copy of at most N items from the original collection.
It does not require you to know the number of items in the original collection, nor iterate over it more than once.
Usage:
IEnumerable<int> sequence = Enumerable.Range(1, 10000);
IEnumerable<int> last10 = sequence.TakeLast(10);
...
Extension method:
public static class Extensions
{
public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> collection,
int n)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
if (n < 0)
throw new ArgumentOutOfRangeException(nameof(n), $"{nameof(n)} must be 0 or greater");
LinkedList<T> temp = new LinkedList<T>();
foreach (var value in collection)
{
temp.AddLast(value);
if (temp.Count > n)
temp.RemoveFirst();
}
return temp;
}
}
If you just want to limit the find to the first level you can do:
find /dev -maxdepth 1 -name 'abc-*'
... or if you particularly want to exclude the .udev
directory, you can do:
find /dev -name '.udev' -prune -o -name 'abc-*' -print
You can set UIButton title color with hex code
btn.setTitleColor(UIColor(hexString: "#95469F"), for: .normal)
Blorgbeard had a great answer for SQL server. If you have a MySQL server like mine then the following will allow you to select the information from columns where the name is like some key phrase. You just have to substitute the table name, database name, and keyword.
SET @columnnames = (SELECT concat("`",GROUP_CONCAT(`COLUMN_NAME` SEPARATOR "`, `"),"`")
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='your_database'
AND `TABLE_NAME`='your_table'
AND COLUMN_NAME LIKE "%keyword%");
SET @burrito = CONCAT("SELECT ",@columnnames," FROM your_table");
PREPARE result FROM @burrito;
EXECUTE result;
You can simply pass your dataframe into the following function:
def sum_frame_by_column(frame, new_col_name, list_of_cols_to_sum):
frame[new_col_name] = frame[list_of_cols_to_sum].astype(float).sum(axis=1)
return(frame)
Example:
I have a dataframe (awards_frame) as follows:
...and I want to create a new column that shows the sum of awards for each row:
Usage:
I simply pass my awards_frame into the function, also specifying the name of the new column, and a list of column names that are to be summed:
sum_frame_by_column(awards_frame, 'award_sum', ['award_1','award_2','award_3'])
Result:
I would EXPECT the first query to be quicker, mainly because you have an equivalence and an explicit JOIN. In my experience IN
is a very slow operator, since SQL normally evaluates it as a series of WHERE
clauses separated by "OR" (WHERE x=Y OR x=Z OR...
).
As with ALL THINGS SQL though, your mileage may vary. The speed will depend a lot on indexes (do you have indexes on both ID columns? That will help a lot...) among other things.
The only REAL way to tell with 100% certainty which is faster is to turn on performance tracking (IO Statistics is especially useful) and run them both. Make sure to clear your cache between runs!
This answer is in three parts, see below for the official release (v3 and v4)
I couldn't even find the col-lg-push-x or pull classes in the original files for RC1 i downloaded, so check your bootstrap.css file. hopefully this is something they will sort out in RC2.
anyways, the col-push-* and pull classes did exist and this will suit your needs. Here is a demo
<div class="row">
<div class="col-sm-5 col-push-5">
Content B
</div>
<div class="col-sm-5 col-pull-5">
Content A
</div>
<div class="col-sm-2">
Content C
</div>
</div>
Also see This blog post on the subject
col-vp-push-x
= push the column to the right by x number of columns, starting from where the column would normally render -> position: relative
, on a vp or larger view-port.
col-vp-pull-x
= pull the column to the left by x number of columns, starting from where the column would normally render -> position: relative
, on a vp or larger view-port.
vp = xs, sm, md, or lg
x = 1 thru 12
I think what messes most people up, is that you need to change the order of the columns in your HTML markup (in the example below, B comes before A), and that it only does the pushing or pulling on view-ports that are greater than or equal to what was specified. i.e. col-sm-push-5
will only push 5 columns on sm
view-ports or greater. This is because Bootstrap is a "mobile first" framework, so your HTML should reflect the mobile version of your site. The Pushing and Pulling are then done on the larger screens.
<div class="row">
<div class="col-sm-5 col-sm-push-5">
Content B
</div>
<div class="col-sm-5 col-sm-pull-5">
Content A
</div>
<div class="col-sm-2">
Content C
</div>
</div>
View-port >= sm
|A|B|C|
View-port < sm
|B|
|A|
|C|
With v4 comes flexbox and other changes to the grid system and the push\pull classes have been removed in favor of using flexbox ordering.
.order-*
classes to control visual order (where * = 1 thru 12).order-md-*
.order-first
(-1) and .order-last
(13) avalable<div class="row">_x000D_
<div class="col order-2">1st yet 2nd</div>_x000D_
<div class="col order-1">2nd yet 1st</div>_x000D_
</div>
_x000D_
As Abel said, ES Modules in Node >= 14 no longer have require
by default.
If you want to add it, put this code at the top of your file:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
Source: https://nodejs.org/api/modules.html#modules_module_createrequire_filename
You mean like this?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
One of the most common reasons I see that error is when I am trying to display an alert dialog or progress dialog in an activity that is not in the foreground. Like when a background thread that displays a dialog box is running in a paused activity.
You can convert both the values to lower case and compare.
Here is an example:
If LCase(Range("J6").Value) = LCase("Tawi") Then
Range("J6").Value = "Tawi-Tawi"
End If
The new git-switch
command (starting in GIT 2.23) also has a flag --discard-changes
which should help you. git pull
might be necessary afterwards.
Warning: it's still considered to be experimental.
Probably, you are trying to point the tomcat directory having the source folder. Please download the tomcat binary version from here .For Linux environments, there you can find .zip and .tar.gz files under core section. Please download and extract them. after that, if you point this extracted directory, eclipse will be able to identify the tomcat version. Eclipse was not able to find the version of tomcat, since the directory you pointed out didn't contain the conf folder. Hope this helps!
ngOnInit() {
const $ = window["$"];
$('.flexslider').flexslider({
animation: 'slide',
start: function (slider) {
$('body').removeClass('loading')
}
})
}
This issue happened when I accidently renamed the line
apply plugin: 'com.android.application'
on file app/build.gradle
to some other name. So, I fixed it by changing it to what it was.
You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id}
- you need to indicate which are variables and which are string literals. Since anything inside {}
is an inline JSX expression, you can do:
href={"#demo" + this.state.id}
This will use the string literal #demo
and concatenate it to the value of this.state.id
. This can then be applied to all strings. Consider this:
var text = "world";
And this:
{"Hello " + text + " Andrew"}
This will yield:
Hello world Andrew
You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr}
(interpolated expression), which is closer to what you seem to be trying to do:
href={`#demo${this.state.id}`}
This will basically substitute the value of this.state.id
, concatenating it to #demo
. It is equivalent to doing: "#demo" + this.state.id
.
It will work when adding space between id and class identifier
$("#countery .save")...
you cannot call a controller method from another controller directly
my solution is to use inheritances and extend your controller from the library controller
class Controller1 extends CI_Controller {
public function index() {
// some codes here
}
public function methodA(){
// code here
}
}
in your controller we call it Mycontoller
it will extends Controller1
include_once (dirname(__FILE__) . "/controller1.php");
class Mycontroller extends Controller1 {
public function __construct() {
parent::__construct();
}
public function methodB(){
// codes....
}
}
and you can call methodA from mycontroller
http://example.com/mycontroller/methodA
http://example.com/mycontroller/methodB
this solution worked for me
Beginning PowerShell 5.0 New-Item
, Remove-Item
, and Get-ChildItem
have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item
accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.
New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"
Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.
Anyway if you want to create a Run As Administrator shortcut using Powershell you can use
$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)
If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.
This is a problem that can arise from writing down a "filename" instead of a path, while generating the .jks file. Generate a new one, put it on the Desktop (or any other real path) and re-generate APK.
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.
It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.
Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146
I think it's first worth noting that without javascript (plain html), the form
element submits when clicking either the <input type="submit" value="submit form">
or <button>submits form too</button>
. In javascript you can prevent that by using an event handler and calling e.preventDefault()
on button click, or form submit. e
is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit
, and the other on the button via onClick
.
Example: http://jsbin.com/vowuley/edit?html,js,console,output
I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>
You need to initialize it first:
p = Pump().getPumps()
Have you escaped your forward slashes( / )? I've had trouble with those before
I am using Ubuntu 16.04. When I installed anaconda I was facing the same problem. I tried this and it resolved my problem.
step 1 : $ conda install -c anaconda anaconda-navigator?
step 2 : $ anaconda-navigator
Hope it will help.
VIM for vscode does it awsomely. It's based one vim-surround if you don't use vscode.
Some examples:
"test" with cursor inside quotes type cs"' to end up with 'test'
"test" with cursor inside quotes type ds" to end up with test
"test" with cursor inside quotes type cs"t and enter 123> to end up with <123>test
test with cursor on word test type ysaw) to end up with (test)
private void drawArrows(Point[] point, Canvas canvas, Paint paint) {
float [] points = new float[8];
points[0] = point[0].x;
points[1] = point[0].y;
points[2] = point[1].x;
points[3] = point[1].y;
points[4] = point[2].x;
points[5] = point[2].y;
points[6] = point[0].x;
points[7] = point[0].y;
canvas.drawVertices(VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
Path path = new Path();
path.moveTo(point[0].x , point[0].y);
path.lineTo(point[1].x,point[1].y);
path.lineTo(point[2].x,point[2].y);
canvas.drawPath(path,paint);
}
Write-Host "Found file - " + $File.FullName -ForegroundColor Magenta
Magenta can be one of the "System.ConsoleColor" enumerator values - Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.
The + $File.FullName
is optional, and shows how to put a variable into the string.
In order to just download updates:
git fetch origin master
However, this just updates a reference called origin/master
. The best way to update your local master
would be the checkout/merge mentioned in another comment. If you can guarantee that your local master
has not diverged from the main trunk that origin/master
is on, you could use git update-ref
to map your current master
to the new point, but that's probably not the best solution to be using on a regular basis...
<body oncontextmenu="return false;">
works for me in Google Chrome. Not sure about other browsers.
Note, all someone has to do is disable JavaScript in order to see the right-click menu anyway.
In my efforts to learn object-oriented programming alongside learning statistics, I made this, maybe you'll find it useful:
samplesCourse = [9, 10, 10, 11, 13, 15, 16, 19, 19, 21, 23, 28, 30, 33, 34, 36, 44, 45, 47, 60]
class sampleSet:
def __init__(self, sampleList):
self.sampleList = sampleList
self.interList = list(sampleList) # interList is sampleList alias; alias used to maintain integrity of original sampleList
def find_median(self):
self.median = 0
if len(self.sampleList) % 2 == 0:
# find median for even-numbered sample list length
self.medL = self.interList[int(len(self.interList)/2)-1]
self.medU = self.interList[int(len(self.interList)/2)]
self.median = (self.medL + self.medU)/2
else:
# find median for odd-numbered sample list length
self.median = self.interList[int((len(self.interList)-1)/2)]
return self.median
def find_1stQuartile(self, median):
self.lower50List = []
self.Q1 = 0
# break out lower 50 percentile from sampleList
if len(self.interList) % 2 == 0:
self.lower50List = self.interList[:int(len(self.interList)/2)]
else:
# drop median to make list ready to divide into 50 percentiles
self.interList.pop(interList.index(self.median))
self.lower50List = self.interList[:int(len(self.interList)/2)]
# find 1st quartile (median of lower 50 percentiles)
if len(self.lower50List) % 2 == 0:
self.Q1L = self.lower50List[int(len(self.lower50List)/2)-1]
self.Q1U = self.lower50List[int(len(self.lower50List)/2)]
self.Q1 = (self.Q1L + self.Q1U)/2
else:
self.Q1 = self.lower50List[int((len(self.lower50List)-1)/2)]
return self.Q1
def find_3rdQuartile(self, median):
self.upper50List = []
self.Q3 = 0
# break out upper 50 percentile from sampleList
if len(self.sampleList) % 2 == 0:
self.upper50List = self.interList[int(len(self.interList)/2):]
else:
self.interList.pop(interList.index(self.median))
self.upper50List = self.interList[int(len(self.interList)/2):]
# find 3rd quartile (median of upper 50 percentiles)
if len(self.upper50List) % 2 == 0:
self.Q3L = self.upper50List[int(len(self.upper50List)/2)-1]
self.Q3U = self.upper50List[int(len(self.upper50List)/2)]
self.Q3 = (self.Q3L + self.Q3U)/2
else:
self.Q3 = self.upper50List[int((len(self.upper50List)-1)/2)]
return self.Q3
def find_InterQuartileRange(self, Q1, Q3):
self.IQR = self.Q3 - self.Q1
return self.IQR
def find_UpperFence(self, Q3, IQR):
self.fence = self.Q3 + 1.5 * self.IQR
return self.fence
samples = sampleSet(samplesCourse)
median = samples.find_median()
firstQ = samples.find_1stQuartile(median)
thirdQ = samples.find_3rdQuartile(median)
iqr = samples.find_InterQuartileRange(firstQ, thirdQ)
fence = samples.find_UpperFence(thirdQ, iqr)
print("Median is: ", median)
print("1st quartile is: ", firstQ)
print("3rd quartile is: ", thirdQ)
print("IQR is: ", iqr)
print("Upper fence is: ", fence)
From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):
1.10 Empty Operator -
empty A
The
empty
operator is a prefix operator that can be used to determine if a value is null or empty.To evaluate
empty A
- If
A
isnull
, returntrue
- Otherwise, if
A
is the empty string, then returntrue
- Otherwise, if
A
is an empty array, then returntrue
- Otherwise, if
A
is an emptyMap
, returntrue
- Otherwise, if
A
is an emptyCollection
, returntrue
- Otherwise return
false
So, considering the interfaces, it works on Collection
and Map
only. In your case, I think Collection
is the best option. Or, if it's a Javabean-like object, then Map
. Either way, under the covers, the isEmpty()
method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException
.
if (isset($_SERVER['HTTPS'])){
echo "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}else{
echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}
@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).
In my case I needed to force content-type: text/plain to be parsed as json.
If you cannot change the content-type of the request, try using the following code:
app.use(express.json({type: '*/*'}));
Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:
app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
// echo json
res.json(req.body);
});
Create am array and put inside the first, in this case i get data from JSON response
$.getJSON('/Tool/GetAllActiviesStatus/',
var dataFC = new Array();
function (data) {
for (var i = 0; i < data.Result.length; i++) {
var serie = new Array(data.Result[i].FUNCAO, data.Result[i].QT, true, true);
dataFC.push(serie);
});
The &nKByte
creates a temporary value, which cannot be bound to a reference to non-const.
You could change void test(float *&x)
to void test(float * const &x)
or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);
.
final File open = new File("PicDic.exe");
if (open.exists() == true) {
if (Desktop.isDesktopSupported()) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Desktop.getDesktop().open(open);
} catch (IOException ex) {
return;
}
}
});
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//DocumentEditorView.this.getFrame().dispose();
System.exit(0);
}
});
} else {
JOptionPane.showMessageDialog(this.getFrame(), "Desktop is not support to open editor\n You should try manualy");
}
} else {
JOptionPane.showMessageDialog(this.getFrame(), "PicDic.exe is not found");
}
//you can start another apps by using it and can slit your whole project in many apps. it will work lot
the over partition keyword is as if we are partitioning the data by client_id creation a subset of each client id
select client_id, operation_date,
row_number() count(*) over (partition by client_id order by client_id ) as operationctrbyclient
from client_operations e
order by e.client_id;
this query will return the number of operations done by the client_id
This is the simple only you have to set background color as transparent
ImageButton btn=(ImageButton)findViewById(R.id.ImageButton01);
btn.setBackgroundColor(Color.TRANSPARENT);
100 characters.
This is the var (variable) in varchar
: you only store what you enter (and an extra 2 bytes to store length upto 65535)
If it was char(200)
then you'd always store 200 characters, padded with 100 spaces
See the docs: "The CHAR and VARCHAR Types"
For the SQL Server Owner, you should be able to use:
select suser_sname(owner_sid) as 'Owner', state_desc, *
from sys.databases
For a list of SQL Users:
select * from master.sys.server_principals
Ref. SQL Server Tip: How to find the owner of a database through T-SQL
You can always use the type(x) == type(y)
trick, where y
is something with known type.
# check if x is a regular string
type(x) == type('')
# check if x is an integer
type(x) == type(1)
# check if x is a NoneType
type(x) == type(None)
Often there are better ways of doing that, particularly with any recent python. But if you only want to remember one thing, you can remember that.
In this case, the better ways would be:
# check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None
Note the last case: there is only one instance of NoneType
in python, and that is None
. You'll see NoneType a lot in exceptions (TypeError: 'NoneType' object is unsubscriptable
-- happens to me all the time..) but you'll hardly ever need to refer to it in code.
Finally, as fengshaun points out, type checking in python is not always a good idea. It's more pythonic to just use the value as though it is the type you expect, and catch (or allow to propagate) exceptions that result from it.
http://en.wikipedia.org/wiki/Hexspeak
http://www.urbandictionary.com/define.php?term=dead%3Abeef
"Dead beef" is a very popular sentence in programming, because it is built only from letters a-f, which are used in hexadecimal notation. Colons in the beginning and in the middle of the sentence make this sentence a (theoretically) valid IPv6 address.
echo "<pre/>"; print_r($array);
I have created FolderLayout
which may help you.
This link helped me
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/path" android:text="Path"
android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
<ListView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/list"></ListView>
</LinearLayout>
package com.testsample.activity;
public class FolderLayout extends LinearLayout implements OnItemClickListener {
Context context;
IFolderItemListener folderListener;
private List<String> item = null;
private List<String> path = null;
private String root = "/";
private TextView myPath;
private ListView lstView;
public FolderLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.context = context;
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.folderview, this);
myPath = (TextView) findViewById(R.id.path);
lstView = (ListView) findViewById(R.id.list);
Log.i("FolderView", "Constructed");
getDir(root, lstView);
}
public void setIFolderItemListener(IFolderItemListener folderItemListener) {
this.folderListener = folderItemListener;
}
//Set Directory for view at anytime
public void setDir(String dirPath){
getDir(dirPath, lstView);
}
private void getDir(String dirPath, ListView v) {
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root)) {
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
Log.i("Folders", files.length + "");
setItemList(item);
}
//can manually set Item to display, if u want
public void setItemList(List<String> item){
ArrayAdapter<String> fileList = new ArrayAdapter<String>(context,
R.layout.row, item);
lstView.setAdapter(fileList);
lstView.setOnItemClickListener(this);
}
public void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory()) {
if (file.canRead())
getDir(path.get(position), l);
else {
//what to do when folder is unreadable
if (folderListener != null) {
folderListener.OnCannotFileRead(file);
}
}
} else {
//what to do when file is clicked
//You can add more,like checking extension,and performing separate actions
if (folderListener != null) {
folderListener.OnFileClicked(file);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
onListItemClick((ListView) arg0, arg0, arg2, arg3);
}
}
And an Interface IFolderItemListener
to add what to do when a fileItem
is clicked
public interface IFolderItemListener {
void OnCannotFileRead(File file);//implement what to do folder is Unreadable
void OnFileClicked(File file);//What to do When a file is clicked
}
Also an xml to define the row
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowtext" android:layout_width="fill_parent"
android:textSize="23sp" android:layout_height="match_parent"/>
In your xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal" android:weightSum="1">
<com.testsample.activity.FolderLayout android:layout_height="match_parent" layout="@layout/folderview"
android:layout_weight="0.35"
android:layout_width="200dp" android:id="@+id/localfolders"></com.testsample.activity.FolderLayout></LinearLayout>
In Your Activity,
public class SampleFolderActivity extends Activity implements IFolderItemListener {
FolderLayout localFolders;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
localFolders = (FolderLayout)findViewById(R.id.localfolders);
localFolders.setIFolderItemListener(this);
localFolders.setDir("./sys");//change directory if u want,default is root
}
//Your stuff here for Cannot open Folder
public void OnCannotFileRead(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(
"[" + file.getName()
+ "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
//Your stuff here for file Click
public void OnFileClicked(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
Import the libraries needed. Hope these help you...
You can use this code
<script>
// Replace the <textarea id="editor"> with a CKEditor
// instance, using default configuration.
CKEDITOR.config.filebrowserImageBrowseUrl = '/admin/laravel-filemanager?type=Files';
CKEDITOR.config.filebrowserImageUploadUrl = '/admin/laravel-filemanager/upload?type=Images&_token=';
CKEDITOR.config.filebrowserBrowseUrl = '/admin/laravel-filemanager?type=Files';
CKEDITOR.config.filebrowserUploadUrl = '/admin/laravel-filemanager/upload?type=Files&_token=';
CKEDITOR.replaceAll( 'editor');
</script>
@font-face {
font-family: 'Roboto';
src: url('../font/Roboto-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
/* etc, etc. */
@font-face
font-family: 'Roboto'
src: local('Roboto'), local('Roboto-Regular'), url('../fonts/Roboto-Regular.ttf') format('truetype')
font-weight: normal
font-style: normal
@font-face
font-family: 'Roboto'
src: local('Roboto Bold'), local('Roboto-Bold'), url('../fonts/Roboto-Bold.ttf') format('truetype')
font-weight: bold
font-style: normal
@font-face
font-family: 'Roboto'
src: local('Roboto Italic'), local('Roboto-Italic'), url('../fonts/Roboto-Italic.ttf') format('truetype')
font-weight: normal
font-style: italic
@font-face
font-family: 'Roboto'
src: local('Roboto BoldItalic'), local('Roboto-BoldItalic'), url('../fonts/Roboto-BoldItalic.ttf') format('truetype')
font-weight: bold
font-style: italic
@font-face
font-family: 'Roboto'
src: local('Roboto Light'), local('Roboto-Light'), url('../fonts/Roboto-Light.ttf') format('truetype')
font-weight: 300
font-style: normal
@font-face
font-family: 'Roboto'
src: local('Roboto LightItalic'), local('Roboto-LightItalic'), url('../fonts/Roboto-LightItalic.ttf') format('truetype')
font-weight: 300
font-style: italic
@font-face
font-family: 'Roboto'
src: local('Roboto Medium'), local('Roboto-Medium'), url('../fonts/Roboto-Medium.ttf') format('truetype')
font-weight: 500
font-style: normal
@font-face
font-family: 'Roboto'
src: local('Roboto MediumItalic'), local('Roboto-MediumItalic'), url('../fonts/Roboto-MediumItalic.ttf') format('truetype')
font-weight: 500
font-style: italic
/* Roboto-Regular.ttf 400 */
/* Roboto-Bold.ttf 700 */
/* Roboto-Italic.ttf 400 */
/* Roboto-BoldItalic.ttf 700 */
/* Roboto-Medium.ttf 500 */
/* Roboto-MediumItalic.ttf 500 */
/* Roboto-Light.ttf 300 */
/* Roboto-LightItalic.ttf 300 */
/* https://fonts.google.com/specimen/Roboto#standard-styles */
I tried almost all the solution given here.
Which worked for me is I opened the GIT GUI and in that tried to Push. Which ask for the credentials, enter correct userid and password it will start working again.
You are correct, this is indeed a way to initialize member variables. I'm not sure that there's much benefit to this, other than clearly expressing that it's an initialization. Having a "bar=num" inside the code could get moved around, deleted, or misinterpreted much more easily.
click WAMP icon -> Apache -> httpd.conf and find listen 80
new versions of WAMP uses
Listen 0.0.0.0:80
Listen [::0]:80ServerName localhost:80
Change Port Number as you want, like
Listen 0.0.0.0:81
Listen [::0]:81ServerName localhost:81
and now restart Wamp, thats it
and in web browser type as
Happy Coding..
cout.fill( '0' );
cout.width( 3 );
cout << value;
Options -Indexes perfectly works for me ,
here is .htaccess
file :
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes <---- This Works for Me :)
</IfModule>
....etc stuff
</IfModule>
After :
I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged
EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged
CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example.
In the code below, MyControl
has two dependency properties - ActiveTabInt
and ActiveTabString
. When the user clicks the button on the host (MainWindow
), ActiveTabString
is modified. The PropertyChanged
CALLBACK on the dependency property sets the value of ActiveTabInt
. The PropertyChanged
EVENT is not manually raised by MyControl
.
MainWindow.xaml.cs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
ActiveTabString = "zero";
}
private string _ActiveTabString;
public string ActiveTabString
{
get { return _ActiveTabString; }
set
{
if (_ActiveTabString != value)
{
_ActiveTabString = value;
RaisePropertyChanged("ActiveTabString");
}
}
}
private int _ActiveTabInt;
public int ActiveTabInt
{
get { return _ActiveTabInt; }
set
{
if (_ActiveTabInt != value)
{
_ActiveTabInt = value;
RaisePropertyChanged("ActiveTabInt");
}
}
}
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private void Button_Click(object sender, RoutedEventArgs e)
{
ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
}
}
public class MyControl : Control
{
public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });
public string ActiveTabString
{
get { return (string)GetValue(ActiveTabStringProperty); }
set { SetValue(ActiveTabStringProperty, value); }
}
public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
"ActiveTabString",
typeof(string),
typeof(MyControl), new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
ActiveTabStringChanged));
public int ActiveTabInt
{
get { return (int)GetValue(ActiveTabIntProperty); }
set { SetValue(ActiveTabIntProperty, value); }
}
public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
"ActiveTabInt",
typeof(Int32),
typeof(MyControl), new FrameworkPropertyMetadata(
new Int32(),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
MyControl thiscontrol = sender as MyControl;
if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());
}
}
MainWindow.xaml
<StackPanel Orientation="Vertical">
<Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
<local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>
App.xaml
<Style TargetType="local:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyControl">
<TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
<TabItem Header="Tab Zero">
<TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
</TabItem>
<TabItem Header="Tab One">
<TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
</TabItem>
</TabControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
If you have multiple Java versions installed on your Mac, here's a quick way to switch the default version using Terminal. In this example, I am going to switch Java 10 to Java 8.
$ java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
10.0.1, x86_64: "Java SE 10.0.1" /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
1.8.0_171, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
Then, in your .bash_profile add the following.
# Java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
Now if you try java -version again, you should see the version you want.
$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)
<select [(ngModel)]="selectedcarrera" (change)="mostrardatos()" class="form-control" name="carreras">
<option *ngFor="let x of carreras" [ngValue]="x"> {{x.nombre}} </option>
</select>
In ts
mostrardatos(){
}
This will give you true if url does not return 200 OK
function check_404($url) {
$headers=get_headers($url, 1);
if ($headers[0]!='HTTP/1.1 200 OK') return true; else return false;
}
Simply use $(":input")
Example disabling all inputs (textarea, input text, etc):
$(":input").prop("disabled", true);
_x000D_
<form>_x000D_
<textarea>Tetarea</textarea>_x000D_
<input type="text" value="Text">_x000D_
<label><input type="checkbox"> Checkbox</label>_x000D_
</form>_x000D_
_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
_x000D_
Easier way is also to do this.
let elementReference = document.querySelector('<your css, #id selector>');
if (elementReference instanceof HTMLElement) {
elementReference.focus();
}
To delete also views add 'view' keyword:
delete from sqlite_master where type in ('view', 'table', 'index', 'trigger');
Here's an example of how you could implement a list view:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//We have our list view
final ListView dynamic = findViewById(R.id.dynamic);
//Create an array of elements
final ArrayList<String> classes = new ArrayList<>();
classes.add("Data Structures");
classes.add("Assembly Language");
classes.add("Calculus 3");
classes.add("Switching Systems");
classes.add("Analysis Tools");
//Create adapter for ArrayList
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, classes);
//Insert Adapter into List
dynamic.setAdapter(adapter);
//set click functionality for each list item
dynamic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("User clicked ", classes.get(position));
}
});
}
The equals( )
method and the ==
operator perform two different operations. The equals( )
method compares the characters inside a String
object. The ==
operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
The variable s1
refers to the String instance created by “Hello”
. The object referred to by
s2
is created with s1
as an initializer. Thus, the contents of the two String objects are identical,
but they are distinct objects. This means that s1
and s2
do not refer to the same objects and
are, therefore, not ==
, as is shown here by the output of the preceding example:
Hello equals Hello -> true
Hello == Hello -> false
I use EF database first in order to provide more flexibility and control over the database configuration.
EF code first and model first seemed cool at first, and provides database independence, however in doing this it does not allow you to specify what I consider very basic and common database configuration information. For example table indexes, security metadata, or have a primary key containing more than one column. I find I want to use these and other common database features and therefore have to do some database configuration directly anyway.
I find the default POCO classes generated during DB first are very clean, however lack the very useful data annotation attributes, or mappings to stored procedures. I used the T4 templates to overcome some of these limitations. T4 templates are awesome, especially when combined with your own metadata and partial classes.
Model first seems to have lots of potential, but is giving me lots of bugs during complex database schema refactoring. Not sure why.
Use the AssemblyInfo task from the MSBuild Community Tasks (http://msbuildtasks.tigris.org/) project, and integrate it into your .csproj/.vbproj file.
It has a number of options, including one to tie the version number to the date and time of day.
Recommended.
I think it would be a lot more productive to use a TextWriter
, in this case a StreamWriter to write to the MemoryStream. After that, as other have said, you need to "rewind" the MemoryStream using something like stringAsStream.Position = 0L;
.
stringAsStream = new MemoryStream();
// create stream writer with UTF-16 (Unicode) encoding to write to the memory stream
using(StreamWriter sWriter = new StreamWriter(stringAsStream, UnicodeEncoding.Unicode))
{
sWriter.Write("Lorem ipsum.");
}
stringAsStream.Position = 0L; // rewind
Note that:
StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed without a byte order mark (BOM)
Also, you don't have to create a new UnicodeEncoding()
usually, since there's already one as a static member of the class for you to use in convenient utf-8, utf-16, and utf-32 flavors.
And then, finally (as others have said) you're trying to convert the byte
s directly to char
s, which they are not. If I had a memory stream and knew it was a string, I'd use a TextReader
to get the string back from the bytes. It seems "dangerous" to me to mess around with the raw bytes.
In Python 3, we use the bytes
object, also known as str
in Python 2.
# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
I find it more convenient to use the base64
module...
# Python 3
key = base64.b16decode(b'130000000800')
# Python 2
key = base64.b16decode('130000000800')
You can also use literals...
# Python 3
key = b'\x13\0\0\0\x08\0'
# Python 2
key = '\x13\0\0\0\x08\0'
Note that you do not need that many -l
s if you install glfw with the BUILD_SHARED_LIBS
option. (You can enable this option by running ccmake
first).
This way sudo make install
will install the shared library in /usr/local/lib/libglfw.so
.
You can then compile the example file with a simple:
g++ main.cpp -L /usr/local/lib/ -lglfw
Then do not forget to add /usr/local/lib/ to the search path for shared libraries before running your program. This can be done using:
export LD_LIBRARY_PATH=/usr/local/lib:${LD_LIBRARY_PATH}
And you can put that in your ~/.bashrc
so you don't have to type it all the time.
This is the solution that worked for me
https://gist.github.com/elidickinson/5525752#gistcomment-1649300, thanks to @philipp-klinz
<table cellpadding="0" cellspacing="0" border="0" style="padding:0px;margin:0px;width:100%;">
<tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
<tr>
<td style="padding:0px;margin:0px;"> </td>
<td style="padding:0px;margin:0px;" width="560"><!-- max width goes here -->
<!-- PLACE CONTENT HERE -->
</td>
<td style="padding:0px;margin:0px;"> </td>
</tr>
<tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
</table>
Your EditText
should be wrapped in a TextInputLayout
<android.support.design.widget.TextInputLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tilEmail">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/etEmail"
android:hint="Email"
android:layout_marginTop="10dp"
/>
</android.support.design.widget.TextInputLayout>
To get an error message like you wanted, set error to TextInputLayout
TextInputLayout tilEmail = (TextInputLayout) findViewById(R.id.tilEmail);
if (error){
tilEmail.setError("Invalid email id");
}
You should add design support library dependency. Add this line in your gradle dependencies
compile 'com.android.support:design:22.2.0'
Some of the other posts are confused about which dimension is which. Here's an NUNIT test that shows how 2D arrays work in C#
[Test]
public void ArraysAreRowMajor()
{
var myArray = new int[2,3]
{
{1, 2, 3},
{4, 5, 6}
};
int rows = myArray.GetLength(0);
int columns = myArray.GetLength(1);
Assert.AreEqual(2,rows);
Assert.AreEqual(3,columns);
Assert.AreEqual(1,myArray[0,0]);
Assert.AreEqual(2,myArray[0,1]);
Assert.AreEqual(3,myArray[0,2]);
Assert.AreEqual(4,myArray[1,0]);
Assert.AreEqual(5,myArray[1,1]);
Assert.AreEqual(6,myArray[1,2]);
}
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
ES6 is quite powerful in iterating through objects (strings, Array, Map, Set). Let's use a Spread Operator to solve this.
entry = prompt("Enter your name");
var count = [...entry];
console.log(count);
SELECT u.*, p.*
FROM users AS u
INNER JOIN payments AS p ON p.id = (
SELECT id
FROM payments AS p2
WHERE p2.user_id = u.id
ORDER BY date DESC
LIMIT 1
)
Or
SELECT u.*, p.*
FROM users AS u
INNER JOIN payments AS p ON p.user_id = u.id
WHERE NOT EXISTS (
SELECT 1
FROM payments AS p2
WHERE
p2.user_id = p.user_id AND
(p2.date > p.date OR (p2.date = p.date AND p2.id > p.id))
)
This solutions are better than the accepted answer because they work correctly when there are multiple payments with same user and date. You can try on SQL Fiddle.
For opening a file, try this:
objexcel.Workbooks.Open(@"C:\YourPath\YourExcelFile.xls",
missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,missing, missing);
You must supply those stupid looking 'missing' arguments. If you were writing the same code in VB.Net you wouldn't have needed them, but you can't avoid them in C#.
For TSQL I like to encapsulate case statements in an outer apply. This prevents me from having to have the case statement written twice, allows reference to the case statement by alias in future joins and avoids the need for positional references.
select oa.day,
model.name,
attempt.type,
oa.result
COUNT(*) MyCount
FROM attempt attempt, prod_hw_id prod_hw_id, model model
WHERE time >= '2013-11-06 00:00:00'
AND time < '2013-11-07 00:00:00'
AND attempt.hard_id = prod_hw_id.hard_id
AND prod_hw_id.model_id = model.model_id
OUTER APPLY (
SELECT CURRENT_DATE-1 AS day,
CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END result
) oa
group by oa.day,
model.name,
attempt.type,
oa.result
order by model.name, attempt.type, oa.result;
You should be careful if the strings in a
or str
gets longer. The straightforward solutions take O(S*(A^2)), where S
is the length of str
and A is the sum of the lenghts of all strings in a
. For a faster solution, look at Aho-Corasick algorithm for string matching, which runs in linear time O(S+A).
Cross Platform, Python 2/3 code:
# import sys, os
def wait_key():
''' Wait for a key press on the console and return it. '''
result = None
if os.name == 'nt':
import msvcrt
result = msvcrt.getch()
else:
import termios
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
try:
result = sys.stdin.read(1)
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
return result
I removed the fctl/non-blocking stuff because it was giving IOError
s and I didn't need it. I'm using this code specifically because I want it to block. ;)
Addendum:
I implemented this in a package on PyPI with a lot of other goodies called console:
>>> from console.utils import wait_key
>>> wait_key()
'h'
Just pick the columns you want directly....
df[['A','E','I','C']]
As soon as you have run npm init
and you start installing npm packages it'll create the node_moduals
folder after that first install
e.g
npm init
(Asks you to set up your package.json file)
npm install <package name here> --save-dev
installs package & creates the node modules directory
Try setting a Windows System Environment variable called _JAVA_OPTIONS
with the heap size you want. Java should be able to find it and act accordingly.
Put the test in a function and you will be able to reuse it and you have better code readability.
Do NOT use the "On Error Resume Next" since it may conflict with other part of your code.
Sub DoesTheSheetExists()
If SheetExist("SheetName") Then
Debug.Print "The Sheet Exists"
Else
Debug.Print "The Sheet Does NOT Exists"
End If
End Sub
Function SheetExist(strSheetName As String) As Boolean
Dim i As Integer
For i = 1 To Worksheets.Count
If Worksheets(i).Name = strSheetName Then
SheetExist = True
Exit Function
End If
Next i
End Function
Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain
to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.
I updated some answers posted to add the following:
Specify how many numbers after the decimal point is allowed.
String.prototype.isDecimal = function isDecimal(evt,decimalPts) {
debugger;
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
return false;
//Prevent more than one point
if (charCode == 46 && this.includes("."))
return false;
// Restrict the needed decimal digits
if (this.includes("."))
{
var number = [];
number = this.split(".");
if (number[1].length == decimalPts)
return false;
}
return true;
};
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where
strm
is the identifier of a istream object andvariable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object
strm
.
Just replace strm
with cin
.
Try this:
var value;
for (var key in dictionary) {
value = dictionary[key];
// your code here...
}
foreach($results['data'] as $result) {
echo $result['type'], '<br />';
}
or echo $results['data'][1]['type'];
In special cases where you want to find whether a word is contained in a long text, you can iterate through the long text with a loop.
found=F
query_word=this
long_string="many many words in this text"
for w in $long_string; do
if [ "$w" = "$query_word" ]; then
found=T
break
fi
done
This is pure Bourne shell.
Defining a custom __call__()
method in the meta-class allows the class's instance to be called as a function, not always modifying the instance itself.
In [1]: class A:
...: def __init__(self):
...: print "init"
...:
...: def __call__(self):
...: print "call"
...:
...:
In [2]: a = A()
init
In [3]: a()
call
import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall(directory_to_extract_to)
That's pretty much it!
Here is a basic example that explains the callback()
function in JavaScript:
var x = 0;_x000D_
_x000D_
function testCallBack(param1, param2, callback) {_x000D_
alert('param1= ' + param1 + ', param2= ' + param2 + ' X=' + x);_x000D_
if (callback && typeof(callback) === "function") {_x000D_
x += 1;_x000D_
alert("Calla Back x= " + x);_x000D_
x += 1;_x000D_
callback();_x000D_
}_x000D_
}_x000D_
_x000D_
testCallBack('ham', 'cheese', function() {_x000D_
alert("Function X= " + x);_x000D_
});
_x000D_
Thanks to CSS3 there is a solution !
The solution is to put the image as background-image
and then set the background-size
to contain
.
HTML
<div class='bounding-box'>
</div>
CSS
.bounding-box {
background-image: url(...);
background-repeat: no-repeat;
background-size: contain;
}
Test it here: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain
Full compatibility with latest browsers: http://caniuse.com/background-img-opts
To align the div in the center, you can use this variation:
.bounding-box {
background-image: url(...);
background-size: contain;
position: absolute;
background-position: center;
background-repeat: no-repeat;
height: 100%;
width: 100%;
}
Use:
num_lines = sum(1 for line in open('data.txt'))
print(num_lines)
That will work.
To read more than one json tip (array, attribute) I did the following.
var jVariable = JsonConvert.DeserializeObject<YourCommentaryClass>(jsonVariableContent);
change to
var jVariable = JsonConvert.DeserializeObject <List<YourCommentaryClass>>(jsonVariableContent);
Because you cannot see all the bits in the method used in the foreach loop. Example foreach loop
foreach (jsonDonanimSimple Variable in jVariable)
{
debugOutput(jVariable.Id.ToString());
debugOutput(jVariable.Header.ToString());
debugOutput(jVariable.Content.ToString());
}
I also received an error in this loop and changed it as follows.
foreach (jsonDonanimSimple Variable in jVariable)
{
debugOutput(Variable.Id.ToString());
debugOutput(Variable.Header.ToString());
debugOutput(Variable.Content.ToString());
}
A simple one way version which can be used like this:
Visibility="{Binding IsHidden, Converter={x:Static Ui:Converters.BooleanToVisibility}, ConverterParameter=true}
can be implemented like this:
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var invert = false;
if (parameter != null)
{
invert = Boolean.Parse(parameter.ToString());
}
var booleanValue = (bool) value;
return ((booleanValue && !invert) || (!booleanValue && invert))
? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I tried all the methods I can find online and failed. Then I read this post and get some ideas from @Alex answer. Then I search about ""credsStore": "osxkeychain"" which is used in my config.json. The I follow this link https://docs.docker.com/engine/reference/commandline/login/ to logout and then login again. Finally, I can push my image successfully.
Just find the text ignore: ":hidden" in your jquery validation file and comment it. After comment this it will never loss any hidden elements to validate...
Thanks
If you are working with Keras library and want to use tensorboard to print your graphs of accuracy and other variables, Then below are the steps to follow.
step 1: Initialize the keras callback library to import tensorboard by using below command
from keras.callbacks import TensorBoard
step 2: Include the below command in your program just before "model.fit()" command.
tensor_board = TensorBoard(log_dir='./Graph', histogram_freq=0, write_graph=True, write_images=True)
Note: Use "./graph". It will generate the graph folder in your current working directory, avoid using "/graph".
step 3: Include Tensorboard callback in "model.fit()".The sample is given below.
model.fit(X_train,y_train, batch_size=batch_size, epochs=nb_epoch, verbose=1, validation_split=0.2,callbacks=[tensor_board])
step 4 : Run your code and check whether your graph folder is there in your working directory. if the above codes work correctly you will have "Graph" folder in your working directory.
step 5 : Open Terminal in your working directory and type the command below.
tensorboard --logdir ./Graph
step 6: Now open your web browser and enter the address below.
http://localhost:6006
After entering, the Tensorbaord page will open where you can see your graphs of different variables.
Just a reminder on adding columns. If one of the values is NULL the total of those columns becomes NULL. Thus why some posters have recommended coalesce with the second parameter being 0
I know this was an older posting but wanted to add this for completeness.
When you put <form>
tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form
that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form>
will satisfy:
A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.
So to check form validity, you can check value of $scope.yourformname.$valid
property of scope.
More information you can get at Developer's Guide section about forms.
The Uri.parse(extras.getString("imageUri"))
was causing an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference
So I changed to the following:
intent.putExtra("imageUri", imageUri)
and
Uri uri = (Uri) getIntent().get("imageUri");
This solved the problem.
This will resolve your error. Run these commands in your terminal. These commands will add the older versions. You can update them later or you can change version here too before running these commands one by one.
sudo apt-get install build-essential
wget http://nodejs.org/dist/v0.8.16/node-v0.8.16.tar.gz
tar -xzf node-v0.8.16.tar.gz
cd node-v0.8.16/
./configure
make
sudo make install
Just replace the form.submit function with your own implementation:
var form = document.getElementById('form');
var formSubmit = form.submit; //save reference to original submit function
form.onsubmit = function(e)
{
formHandler();
return false;
};
var formHandler = form.submit = function()
{
alert('hi there');
formSubmit(); //optionally submit the form
};
I did this to remove the error:
Mapper.CreateMap<FacebookUser, ProspectModel>();
prospect = Mapper.Map(prospectFromDb, prospect);
userInfos.GroupBy(userInfo => userInfo.metric)
.OrderBy(group => group.Key)
.Select(group => Tuple.Create(group.Key, group.Count()));
Yup! That's very straight forward and that's where the package strategy comes into play. there are three ways to my knowledge. folder structure:
GOPATH/src/ github.com/ abc/ myproject/ adapter/ main.go pkg1 pkg2 warning: adapter can contain package main only and sun directories
go build main.go
go build main.go
go build myproject/adapter
exe file will be created at the directory you are currently at.
The content inside strings in Golang can be compared using ==
operator. If the results are not as expected there may be some hidden characters like \n
, \r
, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings
package in golang.
For Instance, spaces can be removed using strings.TrimSpace
function. You can also define a custom function to remove any character you need. strings.TrimFunc
function can give you more power.
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
After lots of search and experimentation with some answers here and elsewhere, I think your answer is here:
pd.DataFrame(columns=df.columns, data=LabelEncoder().fit_transform(df.values.flatten()).reshape(df.shape))
This will preserve category names across columns:
import pandas as pd
from sklearn.preprocessing import LabelEncoder
df = pd.DataFrame([['A','B','C','D','E','F','G','I','K','H'],
['A','E','H','F','G','I','K','','',''],
['A','C','I','F','H','G','','','','']],
columns=['A1', 'A2', 'A3','A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10'])
pd.DataFrame(columns=df.columns, data=LabelEncoder().fit_transform(df.values.flatten()).reshape(df.shape))
A1 A2 A3 A4 A5 A6 A7 A8 A9 A10
0 1 2 3 4 5 6 7 9 10 8
1 1 5 8 6 7 9 10 0 0 0
2 1 3 9 6 8 7 0 0 0 0
Usually the process is the other way around. Do not go looking for situations where to use design patterns, look for code that can be optimized. When you have code that you think is not structured correctly. try to find a design pattern that will solve the problem.
Design patterns are meant to help you solve structural problems, do not go design your application just to be able to use design patterns.
Use it like this
<input type="file" accept=".png, .jpg, .jpeg" />
It worked for me
I came across this trying to add labels o some vertical radio boxes. I had to do this:
<%: Html.RadioButton("RadioGroup1", "Yes") %><label style="display:inline-block;padding-top:2px;">Yes</label><br />
<%: Html.RadioButton("RadioGroup1", "No") %><label style="display:inline-block;padding-top:3px;">No</label><br />
<%: Html.RadioButton("RadioGroup1", "Maybe") %><label style="display:inline-block;padding-top:4px;">Maybe</label><br />
This gets them to display properly, where the label is centered on the radio button, though I had to increment the top padding with each line, as you can see. The code isn't pretty, but the result is.
MacOS X specific:
C11 is supported, so you can just call aligned_malloc (16, size).
MacOS X picks code that is optimised for individual processors at boot time for memset, memcpy and memmove and that code uses tricks that you've never heard of to make it fast. 99% chance that memset runs faster than any hand-written memset16 which makes the whole question pointless.
If you want a 100% portable solution, before C11 there is none. Because there is no portable way to test alignment of a pointer. If it doesn't have to be 100% portable, you can use
char* p = malloc (size + 15);
p += (- (unsigned int) p) % 16;
This assumes that the alignment of a pointer is stored in the lowest bits when converting a pointer to unsigned int. Converting to unsigned int loses information and is implementation defined, but that doesn't matter because we don't convert the result back to a pointer.
The horrible part is of course that the original pointer must be saved somewhere to call free () with it. So all in all I would really doubt the wisdom of this design.
Just a minor correction - the last part should be up to 6. Hence,
^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}$
The longest TLD is museum
(6 chars) - http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains
Or just add left: 0
and right: 0
to your original CSS, which makes it behave similarly to a regular non-fixed element and the usual auto-margin technique works:
.jqbox_innerhtml
{
position: fixed;
width:500px;
height:200px;
background-color:#FFF;
padding:10px;
border:5px solid #CCC;
z-index:200;
margin: 5% auto;
left: 0;
right: 0;
}
Note you need to use a valid (X)HTML DOCTYPE
for it to behave correctly in IE (which you should of course have anyway..!)
However, will it automatically remove these committed files from the repository?
No. Even with an existing .gitignore
you are able to stage "ignored" files with the -f
(force) flag. If they files are already commited, they don't get removed automatically.
git rm --cached path/to/ignored.exe
Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:
import requests
url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)
print(response.text)
More about Request object: https://requests.readthedocs.io/en/master/api/
var firstName = "Ada";
var lastLetterOfFirstName = firstName[firstName.length - 1];
I spent a while looking into this and pretty much all of the freeware and shareware on the web sucked. This included software to directly convert the .ppt file to Flash or some sort of video format and also software to record your desktop screen. Software was clunky, and the quality was poor.
The solution we eventually came up with is a little bit manual, but it gave by far the best quality results:
Saving out as .wmv isn't perfect, but I'm sure it's probably quite straightforward to convert that to some other format or Flash. We were looking to get them up on YouTube and this did the trick.
To pass multiple headers in a curl request you simply add additional -H
or --header
to your curl command.
Example
//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL
//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json' https://www.example.com
Going Further
For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:
For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.
$ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
$ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com
You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.
Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.
...
Also make sure the value is not too large or too small for int like in my case.
First you should take a note about difference between git am
and git apply
When you are using git am
you usually wanna to apply many patches. Thus should use:
git am *.patch
or just:
git am
Git will find patches automatically and apply them in order ;-)
UPD
Here you can find how to generate such patches
Tedious but it worked for me (Kepler):
Using the OS zip utility, zip everything below the project workspace folder to a zip file, to be placed in a separate directory (will use c:\tmp\workspace.zip
as an example).
Unzip workspace.zip
to the c:\tmp
directory. Assume there's a project folder called Project1
a. Ensure all the files in Project1
have Full Control permissions for Everyone or at least 777
permissions.
Remove all the project folders in the Eclipse workspace.
Recreate each project one by one according to its original type (Java, Dynamic Web, etc.). (Will use Project1
as an example.) Do not add anything.
In Eclipse, do File -> Import -> File System. Then select c:\tmp\Project1
as a source
Select the workspace Project1 as a destination. Do not overwrite any file.
In Eclipse, refresh the project and test it. It should work.
What SSL private key should be sent along with the client certificate?
None of them :)
One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth
). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.
Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.
Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure
Use TLS 1.0 and above; and use Server Name Indication.
You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:
openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
-cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem
You can also use -CAfile
to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.
I created my own Gem, but I did it in a directory that is not in my load path:
$ pwd
/Users/myuser/projects
$ gem build my_gem/my_gem.gemspec
Then I ran irb
and tried to load the Gem:
> require 'my_gem'
LoadError: cannot load such file -- my_gem
I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:
. None of those directories included my ~/projects directory where I created the custom gem.
So one solution is to modify the load path itself:
$: << "/Users/myuser/projects/my_gem/lib"
Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:
> require 'my_gem'
=> true
Now if you want to install the gem in RVM path, then you would need to run:
$ gem install my_gem
But it will need to be in a repository like rubygems.org.
$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem
I solved this problem to add a public setter for all properties, which should be deserialized.
Controller (Example: User.php)
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Users extends CI_controller
{
// Table
protected $table = 'users';
function index()
{
$data['users'] = $this->model->ra_object($this->table);
$this->load->view('users_list', $data);
}
}
View (Example: users_list.php)
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user) : ?>
<tr>
<td><?php echo $user->name; ?></td>
<td><?php echo $user->surname; ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- // User table -->
Error is: FROM (SELECT empno,name FROM table1 where location = 'A' ORDER BY emp_no)
And solution is : FROM (SELECT empno,name FROM table1 where location = 'A') ORDER BY emp_no
There are basically two ways
store the previous value of window.onload
so your code can call a previous handler if present before or after your code executes
using the addEventListener
approach (that of course Microsoft doesn't like and requires you to use another different name).
The second method will give you a bit more safety if another script wants to use window.onload
and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.
Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.