Two ways:
Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.
Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.
I found following program works for me
test1.sh
a=xxx
test2.sh $a
in test2.sh you use $1
to refer variable a
in test1.sh
echo $1
The output would be xxx
I found an answer which worked for me and can be found in the following link:
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window
object) this can work well for checking if values have been declared.
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
I got same error and I solved it.
delete package-lock.json file and node_modules folder then npm install
Instead of the -f
of make
you might want to use the -C <path>
option. This first changes the to the path '<path>
', and then calles make
there.
Example:
clean:
rm -f ./*~ ./gmon.out ./core $(SRC_DIR)/*~ $(OBJ_DIR)/*.o
rm -f ../svn-commit.tmp~
rm -f $(BIN_DIR)/$(PROJECT)
$(MAKE) -C gtest-1.4.0/make clean
I was using {{myFunction()}}
in the template but then found another way here using $timeout
inside the controller. Thought I'd share it, works great for me.
angular.module('myApp').controller('myCtrl', ['$timeout',
function($timeout) {
var self = this;
self.controllerFunction = function () { alert('controller function');}
$timeout(function () {
var vanillaFunction = function () { alert('vanilla function'); }();
self.controllerFunction();
});
}]);
function autoRefresh(){
table.ajax.reload(null,false);
alert('Refresh');//for test, uncomment
}
setInterval('autoRefresh()', 5000);
If you want to display at row=159220
row=159220
#To display in a table format
display(res.loc[row:row])
display(res.iloc[row:row+1])
#To display in print format
display(res.loc[row])
display(res.iloc[row])
I really like var_dump()
's verbose output and wasn't satisfied with var_export()
's or print_r()
's output because it didn't give as much information (e.g. data type missing, length missing).
To write secure and predictable code, sometimes it's useful to differentiate between an empty string and a null. Or between a 1 and a true. Or between a null and a false. So I want my data type in the output.
Although helpful, I didn't find a clean and simple solution in the existing responses to convert the colored output of var_dump()
to a human-readable output into a string without the html tags and including all the details from var_dump()
.
Note that if you have a colored var_dump()
, it means that you have Xdebug installed which overrides php's default var_dump()
to add html colors.
For that reason, I created this slight variation giving exactly what I need:
function dbg_var_dump($var)
{
ob_start();
var_dump($var);
$result = ob_get_clean();
return strip_tags(strtr($result, ['=>' => '=>']));
}
Returns the below nice string:
array (size=6)
'functioncall' => string 'add-time-property' (length=17)
'listingid' => string '57' (length=2)
'weekday' => string '0' (length=1)
'starttime' => string '00:00' (length=5)
'endtime' => string '00:00' (length=5)
'price' => string '' (length=0)
Hope it helps someone.
looks like SimpleDateFormat is not checking the pattern strictly even after setLenient(false); method is applied on it, so i have used below method to validate if the date inputted is valid date or not as per supplied pattern.
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public boolean isValidFormat(String dateString, String pattern) {
boolean valid = true;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
try {
formatter.parse(dateString);
} catch (DateTimeParseException e) {
valid = false;
}
return valid;
}
Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so
let markdown = `
1. Apple
2. Mango
this is juicy
3. Orange
`
Workable solution:
downloadCSV(data){
const newBlob = new Blob([decodeURIComponent(encodeURI(data))], { type: 'text/csv;charset=utf-8;' });
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const fileData = window.URL.createObjectURL(newBlob);
const link = document.createElement('a');
link.href = fileData;
link.download = `Usecase-Unprocessed.csv`;
// this is necessary as link.click() does not work on the latest firefox
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(fileData);
link.remove();
}, 5000);
}
1. Change the INNER JOIN before the WHERE clause.
2. You have two WHEREs which is not allowed.
Try this:
SELECT table1.f_id FROM table1 INNER JOIN table2 ON (table2.f_id = table1.f_id AND table2.f_type = 'InProcess') WHERE table1.f_com_id = '430' AND table1.f_status = 'Submitted'
This is working for me It's very simple
return $.ajax({
type: 'POST',
url: urlBaseUrl
data: {someData:someData},
dataType: "json",
success: function(resultData) {
}
});
In its simplest form...
CREATE FUNCTION fnGreatestInt (@Int1 int, @Int2 int )
RETURNS int
AS
BEGIN
IF @Int1 >= ISNULL(@Int2,@Int1)
RETURN @Int1
ELSE
RETURN @Int2
RETURN NULL --Never Hit
END
As part of the uuid spec, if you generate a uuid from random it must contain a "4" as the 13th character and a "8", "9", "a", or "b" in the 17th (source).
// this makes sure that the 13th character is "4"
u[6] = (u[6] | 0x40) & 0x4F
// this makes sure that the 17th is "8", "9", "a", or "b"
u[8] = (u[8] | 0x80) & 0xBF
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}
Please check this. https://code.google.com/p/android/issues/detail?id=82850
I faced the same issue. Could notice that the "adb integration" was disabled. Please enable it at your IDE (Tools | Android)
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
In Python, one can use statsmodels.iolib.foreign.genfromdta
to read Stata datasets. In addition, there is also a wrapper of the aforementioned function which can be used to read a Stata file directly from the web: statsmodels.datasets.webuse
.
Nevertheless, both of the above rely on the use of the pandas.io.stata.StataReader.data
, which is now a legacy function and has been deprecated. As such, the new pandas.read_stata
function should now always be used instead.
According to the source file of stata.py
, as of version 0.23.0
, the following are supported:
As others have noted, the pandas.to_csv
function can then be used to save the file into disk. A related function numpy.savetxt
can also save the data
as a text file.
EDIT:
The following details come from help dtaversion
in Stata 15.1:
Stata version .dta file format
----------------------------------------
1 102
2, 3 103
4 104
5 105
6 108
7 110 and 111
8, 9 112 and 113
10, 11 114
12 115
13 117
14 and 15 118 (# of variables <= 32,767)
15 119 (# of variables > 32,767, Stata/MP only)
----------------------------------------
file formats 103, 106, 107, 109, and 116
were never used in any official release.
Since Git 2.16.1(2) you can use
C:\> git update-git-for-windows
In version between 2.14.2 and 2.16.1, the command was
C:\> git update
(It was later renamed to avoid confusion with updating the local repository, e.g. like svn update
does it.)
That command does not exist in Git 2.13 and before.
If this errors with "is not a git command" then either you don't actually have Git for Windows, or your version is very old.
In which case, simply get the latest installer from https://git-scm.com/download (check whether you want 32- or 64-bit) and run it to upgrade.
If you already have the latest version it does nothing, in which case you can manually run the installer to reinstall.
C:\> git update-git-for-windows
Git for Windows 2.17.0.windows.1 (64bit)
Up to date
Um, why not just:
>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'
Since Java 11 you can do:
FileWriter fw = new FileWriter("filename.txt", Charset.forName("utf-8"));
def test():
....
return r1, r2, r3, ....
>> ret_val = test()
>> print ret_val
(r1, r2, r3, ....)
now you can do everything you like with your tuple.
There are already answers which give how to change Inner HTML of element.
But I would suggest, you should use some animation like Fade Out/ Fade In to change HTML which gives good effect of changed HTML rather instantly changing inner HTML.
$('#regTitle').fadeOut(500, function() {
$(this).html('Hello World!').fadeIn(500);
});
If you have many functions which need this, then you can call common function which changes inner Html.
function changeInnerHtml(elementPath, newText){
$(elementPath).fadeOut(500, function() {
$(this).html(newText).fadeIn(500);
});
}
just do this
try
{
//some code
try
{
int idNumber = function2();
}
finally
{
do stuff here....
}
}
catch(Exception e)
{//... perhaps something here}
For all intents and purposes the finally block will always execute. Now there are a couple of exceptions where it won't actually execute: task killing the program, and there is a fast fail security exception which kills the application instantly. Other than that, an exception will be thrown in function 2, the finally block will execute the needed code and then catch the exception in the outer catch block.
I have a slightly different setup, but think my solution will help you out.
I have a Windows 8 Machine, Python 2.7 installed and running my stuff through eclipse.
Some Background:
When I did an easy install
it tries to install MySQL-python 1.2.5
which failed with an error: Unable to find vcvarsall.bat
. I did an easy_install
of pip
and tried the pip
install which also failed with a similar error. They both reference vcvarsall.bat
which is something to do with visual studio, since I don't have visual studio on my machine, it left me looking for a different solution, which I share below.
The Solution:
After I did both of those installs I was able to query my MySQL db through eclipse.
You can also use OpenCV's inbuilt functions cv2.hconcat
and cv2.vconcat
which like their names suggest are used to join images horizontally and vertically respectively.
import cv2
img1 = cv2.imread('opencv/lena.jpg')
img2 = cv2.imread('opencv/baboon.jpg')
v_img = cv2.vconcat([img1, img2])
h_img = cv2.hconcat([img1, img2])
cv2.imshow('Horizontal', h_img)
cv2.imshow('Vertical', v_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Horizontal Concatenation
Vertical Concatenation
The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.
import ftplib
f = ftplib.FTP()
f.connect("localhost")
f.login()
ls = []
f.retrlines('MLSD', ls.append)
for entry in ls:
print entry
The code above will print:
modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests
modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2
modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd
modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart
...
Starting from python 3.3, ftplib will provide a specific method to do this:
Since you're writing a calculator that would presumably also accept floats (1.5, 0.03
), a more robust way would be to use this simple helper function:
def convertStr(s):
"""Convert string to either int or float."""
try:
ret = int(s)
except ValueError:
#Try float.
ret = float(s)
return ret
That way if the int conversion doesn't work, you'll get a float returned.
Edit: Your division
function might also result in some sad faces if you aren't fully aware of how python 2.x handles integer division.
In short, if you want 10/2
to equal 2.5
and not 2
, you'll need to do from __future__ import division
or cast one or both of the arguments to float, like so:
def division(a, b):
return float(a) / float(b)
@ Robert: I have tried to adapt your code with a relative path, and created a batch file to run the VBS.
The VBS starts and closes but doesn't launch the macro... Any idea of where the issue could be?
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFilePath = objFSO.GetAbsolutePathName(".")
Set xlBook = xlApp.Workbooks.Open(strFilePath, "Excels\CLIENTES.xlsb") , 0, True)
xlApp.Run "open_form"
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
I removed the "Application.Quit" because my macro is calling a userform taking care of it.
Cheers
EDIT
I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:
Issues I was facing:
1 - I did not want to use the Workbook_Open Event as the excel is locked in read only. 2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.
I first wrote a macro to launch my userform while hiding the application:
Sub open_form()
Application.Visible = False
frmAddClient.Show vbModeless
End Sub
I then created a vbs to launch this macro (doing it with a relative path has been tricky):
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"
And I finally did a batch file to execute the VBS...
@echo off
pushd %~dp0
cscript Add_Client.vbs
Note that I have also included the "Set back to visible" in my Userform_QueryClose
:
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
ThisWorkbook.Close SaveChanges:=True
Application.Visible = True
Application.Quit
End Sub
Anyway, thanks for your help, and I hope this will help if someone needs it
Hey guys, I had heaps of trouble with this yesterday. I went through the whole process a few times, requesting a new certificate request from the authority with the assistant, clearing out everything in the portal, uploading the certificate, creating a new profile and downloading everything. No dice.
However, check this out.
First up clear out all the certificates on the portal to start fresh.
After creating the new certificate request with the assistant, press "Show in Finder", and double click that bad boy. You should get a popup for the Certificate Assistant with a screen showing "Please specify the issuing Certificate Authority", etc. If you don't, just close it and double click again. Now just proceed through the dialog choosing "Request a certificate from an existing CA" - Continue Request is "Saved to disk" - Continue Save it where ever you like, even override the file.
At the end you should see the magic "Creating key pair"
Run over to the KeyChain access and you'll see your keys in there! Upload this certificate to the apple portal and then go through their wizard as normal, everything should work great now.
Timezones. You have to deal with them, by using getTimezoneOffset()
if you want your visitors from around the wolrd to get the same time.
Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.
var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var eventTime = new Date();
eventTime.setTime(366549200);
var Offset = new Date(eventTime.getTimezoneOffset()*60000)
var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
As the others have said already, your first line should be
#!/usr/bin/env ruby
And you also have to make it executable: (in the shell)
chmod +x test.rb
Then follows the ruby code. If you open a file
File.open("file", "r") do |io|
# do something with io
end
the file is opened in the current directory you'd get with pwd
in the shell.
The path to your script is also simple to get. With $0
you get the first argument of the shell, which is the relative path to your script. The absolute path can be determined like that:
#!/usr/bin/env ruby
require 'pathname'
p Pathname.new($0).realpath()
For file system operations I almost always use Pathname. This is a wrapper for many of the other file system related classes. Also useful: Dir, File...
A newer way to do this in .NET Core is with TagHelpers
.
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro
Building on these examples (MaxLength, Label), you can extend the existing TagHelper
to suit your needs.
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;
namespace ProjectName.TagHelpers
{
[HtmlTargetElement("input", Attributes = "asp-for")]
public class RequiredTagHelper : TagHelper
{
public override int Order
{
get { return int.MaxValue; }
}
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
if (context.AllAttributes["required"] == null)
{
var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
if (isRequired)
{
var requiredAttribute = new TagHelperAttribute("required");
output.Attributes.Add(requiredAttribute);
}
}
}
}
}
You'll then need to add it to be used in your views:
@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"
Given the following model:
using System;
using System.ComponentModel.DataAnnotations;
namespace ProjectName.Models
{
public class Foo
{
public int Id { get; set; }
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
}
}
and view (snippet):
<label asp-for="Name"></label>
<input asp-for="Name"/>
Will result in this HTML:
<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>
I hope this is helpful to anyone with same question but using .NET Core.
Yes.
When calling file_get_contents
on a URL, one should use the stream_create_context
function, which is fairly well documented on php.net.
This is more or less exactly covered on the following page at php.net in the user comments section: http://php.net/manual/en/function.stream-context-create.php
If you want to convert to integers only, another fast (and short) way is the double-bitwise not (i.e. using two tilde characters):
e.g.
~~x;
Reference: http://james.padolsey.com/cool-stuff/double-bitwise-not/
The 5 common ways I know so far to convert a string to a number all have their differences (there are more bitwise operators that work, but they all give the same result as ~~
). This JSFiddle shows the different results you can expect in the debug console: http://jsfiddle.net/TrueBlueAussie/j7x0q0e3/22/
var values = ["123",
undefined,
"not a number",
"123.45",
"1234 error",
"2147483648",
"4999999999"
];
for (var i = 0; i < values.length; i++){
var x = values[i];
console.log(x);
console.log(" Number(x) = " + Number(x));
console.log(" parseInt(x, 10) = " + parseInt(x, 10));
console.log(" parseFloat(x) = " + parseFloat(x));
console.log(" +x = " + +x);
console.log(" ~~x = " + ~~x);
}
123
Number(x) = 123
parseInt(x, 10) = 123
parseFloat(x) = 123
+x = 123
~~x = 123
undefined
Number(x) = NaN
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = NaN
~~x = 0
null
Number(x) = 0
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = 0
~~x = 0
"not a number"
Number(x) = NaN
parseInt(x, 10) = NaN
parseFloat(x) = NaN
+x = NaN
~~x = 0
123.45
Number(x) = 123.45
parseInt(x, 10) = 123
parseFloat(x) = 123.45
+x = 123.45
~~x = 123
1234 error
Number(x) = NaN
parseInt(x, 10) = 1234
parseFloat(x) = 1234
+x = NaN
~~x = 0
2147483648
Number(x) = 2147483648
parseInt(x, 10) = 2147483648
parseFloat(x) = 2147483648
+x = 2147483648
~~x = -2147483648
4999999999
Number(x) = 4999999999
parseInt(x, 10) = 4999999999
parseFloat(x) = 4999999999
+x = 4999999999
~~x = 705032703
The ~~x
version results in a number in "more" cases, where others often result in undefined
, but it fails for invalid input (e.g. it will return 0
if the string contains non-number characters after a valid number).
Please note: Integer overflow and/or bit truncation can occur with ~~
, but not the other conversions. While it is unusual to be entering such large values, you need to be aware of this. Example updated to include much larger values.
Some Perf tests indicate that the standard parseInt
and parseFloat
functions are actually the fastest options, presumably highly optimised by browsers, but it all depends on your requirement as all options are fast enough: http://jsperf.com/best-of-string-to-number-conversion/37
This all depends on how the perf tests are configured as some show parseInt/parseFloat to be much slower.
Just to summarize, here are some commands that navigate to a directory and compile code using Cygwin and Windows Vista:
At the prompt, use cd
to change to the appropriate directory:
$ cd /cygdrive/c/Users/nate/Desktop
Use ls
to list the files in the directory:
$ ls
prog.c
Use the gcc
command to compile a file in this directory:
$ gcc prog.c -o prog
If you don't see any errors, you should be able to run the resulting program:
$ ./prog
Update:
For the "Cygwin1.dll not found
" error, I like Nik's answer. You might also check out this related post about cygwin1.dll not found, which suggests adding c:\cygwin\bin\
to your Windows PATH.
There are instructions on how to change the Windows PATH variable for Windows XP, and on Vista I think it's similar.
c:\cygwin\bin
to the list, making sure to separate it from any previous items with a semicolonFor those who use IIS 7 to host a git http
/https
endpoint:
You need to increase your uploadReadAheadSize
.
Launch Internet Information Services (IIS) Manager
Expand the Server field
Expand Sites
Select the site you want to make the modification for.
In the Features section, double click Configuration Editor
Under Section
select: system.webServer > serverRuntime
Modify the uploadReadAheadSize
section (The value must be between 0
and 2147483647
.)
Click Apply
Restart the Website
<html>
<head>
<style type="text/css">
#wrapper{ width:100%; float:left; height:auto; border:1px solid #5694cf;}
</style>
</head>
<div id="wrapper">
<object data="http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf" width="100%" height="100%">
<p>Your web browser doesn't have a PDF Plugin. Instead you can <a href="http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf"> Click
here to download the PDF</a></p>
</object>
</div>
</html>
You can add the android:textAllCaps="true"
property to your xml file in the EditText. This will enforce the softinput keyboard to appear in all caps mode. The value you enter will appear in Uppercase. However, this won't ensure that the user can only enter in UpperCase
letters. If they want, they can still fall back to the lower case letters. If you want to ensure that the output of the Edittext
is in All caps, then you have to manually convert the input String using toUpperCase()
method of String
class.
Another possibility for this warning (and, most likely, problems with app behavior) is that the original author of the app relied on session.auto_start
being on (defaults to off)
If you don't want to mess with the code and just need it to work, you can always change php configuration and restart php-fpm (if this is a web app):
/etc/php.d/my-new-file.ini :
session.auto_start = 1
(This is correct for CentOS 8, adjust for your OS/packaging)
You could actually put the value = to the text and then do
$j(document).ready(function(){
$j("select#select_2").change(function(){
val = $j("#select_2 option:selected").html();
alert(val);
});
});
Or what I did on a similar case was
<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
with you're options here
</select>
With this second option you should have a undefined. Give me feedback if it worked :)
Patrick
The problem is that variables declared in one case
are still visible in the subsequent case
s unless an explicit { }
block is used, but they will not be initialized because the initialization code belongs to another case
.
In the following code, if foo
equals 1, everything is ok, but if it equals 2, we'll accidentally use the i
variable which does exist but probably contains garbage.
switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
Wrapping the case in an explicit block solves the problem:
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
To further elaborate, switch
statements are just a particularly fancy kind of a goto
. Here's an analoguous piece of code exhibiting the same issue but using a goto
instead of a switch
:
int main() {
if(rand() % 2) // Toss a coin
goto end;
int i = 42;
end:
// We either skipped the declaration of i or not,
// but either way the variable i exists here, because
// variable scopes are resolved at compile time.
// Whether the *initialization* code was run, though,
// depends on whether rand returned 0 or 1.
std::cout << i;
}
I understand the problem of performing the segue at one place and maintaining the state to send parameters in prepare for segue.
I figured out a way to do this. I've added a property called userInfoDict to ViewControllers using a category. and I've override perform segue with identifier too, in such a way that If the sender is self(means the controller itself). It will pass this userInfoDict to the next ViewController.
Here instead of passing the whole UserInfoDict you can also pass the specific params, as sender and override accordingly.
1 thing you need to keep in mind. don't forget to call super method in ur performSegue method.
You can copy a string in python via string formatting :
>>> a = 'foo'
>>> b = '%s' % a
>>> id(a), id(b)
(140595444686784, 140595444726400)
You can do this with the additional effects in jQuery UI: See here for details
Quick example:
$(this).hide("slide", { direction: "left" }, 1000);
$(this).show("slide", { direction: "left" }, 1000);
You can use this command:
start /min iexplore http://www.google.com
With the use of /min, it will hit on the URL without opening in the browser.
No import is necessary as long as you declare both a.go
and b.go
to be in the same package. Then, you can use go run
to recognize multiple files with:
$ go run a.go b.go
In Perl you want to use single quotes when you have a string which doesn't need to interpolate variables or escaped characters like \n, \t, \r, etc.
PHP makes the same distinction as Perl: content in single quotes will not be interpreted (not even \n will be converted), as opposed to double quotes which can contain variables to have their value printed out.
Python does not, I'm afraid. Technically seen, there is no $ token (or the like) to separate a name/text from a variable in Python. Both features make Python more readable, less confusing, after all. Single and double quotes can be used interchangeably in Python.
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
As per latest api docs:
$(document).ready(function() {
$('#example').dataTable({
"order": []
});
});
I would have thought that it would be better to use stat
to find the size of a file, since the filesystem knows it already, rather than causing the whole file to have to be read with awk
or wc
- especially if it is a multi-GB file or one that may be non-resident in the file-system on an HSM.
stat -c%s file
Yes, I concede it doesn't account for multi-byte characters, but would add that the OP has never clarified whether that is/was an issue.
best way to upgrade is compile it from source
see this tutorial that may be helful for you
http://www.computersnyou.com/2012/09/how-to-upgrade-php-in-mac-osx-compiling.html
AST_NODE* Statement(AST_NODE* node)
is missing a semicolon (a major clue was the error message "In function ‘Statement’: ...") and so is line 24,
return node
(Once you fix those, you will encounter other problems, some of which are mentioned by others here.)
You can give a try to TinyPNG PHP library. Using this library your image gets optimized automatically during resizing process. All you need to install the library and get an API key from https://tinypng.com/developers. To install a library, run the below command.
composer require tinify/tinify
After that, your code is as follows.
require_once("vendor/autoload.php");
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile("large.jpg"); //image to be resize
$resized = $source->resize(array(
"method" => "fit",
"width" => 150,
"height" => 100
));
$resized->toFile("thumbnail.jpg"); //resized image
I have a written a blog on the same topic http://artisansweb.net/resize-image-php-using-tinypng
The wait for the document.ready event is not the entire fix to this problem, because this code is still in a race condition: Sometimes this code is fired before the click event is processed so this directly returns, since the browser hasn't started loading the new page yet.
After some searching I found a post on Obay the testing goat, which has a solution for this problem. The c# code for that solution is something like this:
IWebElement page = null;
...
public void WaitForPageLoad()
{
if (page != null)
{
var waitForCurrentPageToStale = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
waitForCurrentPageToStale.Until(ExpectedConditions.StalenessOf(page));
}
var waitForDocumentReady = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
waitForDocumentReady.Until((wdriver) => (driver as IJavaScriptExecutor).ExecuteScript("return document.readyState").Equals("complete"));
page = driver.FindElement(By.TagName("html"));
}
` I fire this method directly after the driver.navigate.gotourl, so that it gets a reference of the page as soon as possible. Have fun with it!
A reason for this problem (which is even harder to detect than the issue with char* str = "some string"
- which others have explained) is when you are using constexpr
.
constexpr char* str = "some string";
It seems that it would behave similar to const char* str
, and so would not cause a warning, as it occurs before char*
, but it instead behaves as char* const str
.
Constant pointer, and pointer to a constant. The difference between const char* str
, and char* const str
can be explained as follows.
const char* str
: Declare str to be a pointer to a const char. This means that the data to which this pointer is pointing to it constant. The pointer can be modified, but any attempt to modify the data would throw a compilation error.
str++ ;
: VALID. We are modifying the pointer, and not the data being pointed to.*str = 'a';
: INVALID. We are trying to modify the data being pointed to.char* const str
: Declare str to be a const pointer to char. This means that point is now constant, but the data being pointed too is not. The pointer cannot be modified but we can modify the data using the pointer.
str++ ;
: INVALID. We are trying to modify the pointer variable, which is a constant.*str = 'a';
: VALID. We are trying to modify the data being pointed to. In our case this will not cause a compilation error, but will cause a runtime error, as the string will most probably will go into a read only section of the compiled binary. This statement would make sense if we had dynamically allocated memory, eg. char* const str = new char[5];
.const char* const str
: Declare str to be a const pointer to a const char. In this case we can neither modify the pointer, nor the data being pointed to.
str++ ;
: INVALID. We are trying to modify the pointer variable, which is a constant.*str = 'a';
: INVALID. We are trying to modify the data pointed by this pointer, which is also constant.In my case the issue was that I was expecting constexpr char* str
to behave as const char* str
, and not char* const str
, since visually it seems closer to the former.
Also, the warning generated for constexpr char* str = "some string"
is slightly different from char* str = "some string"
.
constexpr char* str = "some string"
: ISO C++11 does not allow conversion from string literal to 'char *const'
char* str = "some string"
: ISO C++11 does not allow conversion from string literal to 'char *'
.You can use C gibberish ? English converter to convert C
declarations to easily understandable English statements, and vice versa. This is a C
only tool, and thus wont support things (like constexpr) which are exclusive to C++
.
Here is a working solution.
class BST:
def __init__(self,data):
self.root = data
self.left = None
self.right = None
def insert(self,data):
if self.root == None:
self.root = BST(data)
elif data > self.root:
if self.right == None:
self.right = BST(data)
else:
self.right.insert(data)
elif data < self.root:
if self.left == None:
self.left = BST(data)
else:
self.left.insert(data)
def inordertraversal(self):
if self.left != None:
self.left.inordertraversal()
print (self.root),
if self.right != None:
self.right.inordertraversal()
t = BST(4)
t.insert(1)
t.insert(7)
t.insert(3)
t.insert(6)
t.insert(2)
t.insert(5)
t.inordertraversal()
I've used this successfully inside R script:
library("reshape2",lib.loc="/path/to/R-packages/")
useful if for whatever reason libraries are in more than one place.
You might also consider removing the need for duplicated parameter names in your Sql by changing your Sql to
table.Variable2 LIKE '%' || :VarB || '%'
and then getting your client to provide '%' for any value of VarB instead of null. In some ways I think this is more natural.
You could also change the Sql to
table.Variable2 LIKE '%' || IfNull(:VarB, '%') || '%'
SELECT ... INTO creates a new table. You'll need to use INSERT. Also, you have the database and owner names reversed.
INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable
for getting tooltips to refresh when the model changes, i simply use data-original-title
instead of title
.
e.g.
<i class="fa fa-gift" data-toggle="tooltip" data-html="true" data-original-title={{getGiftMessage(gift)}} ></i>
note that i'm initializing use of tooltips like this:
<script type="text/javascript">
$(function () {
$("body").tooltip({ selector: '[data-toggle=tooltip]' });
})
</script>
versions:
var list3 = list1.Where(x => !list2.Any(z => z.Id == x.Id)).ToList();
Note: list3
will contain the items or objects that are not in both lists.
Note: Its ToList()
not toList()
Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:
Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)
Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.
Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.
Mash the build button.
Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:
<Router>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
<Route path="/login" component={Login} />
</Router>
And the other components would look something like this:
var NavBar = React.createClass({
render() {
return (
<div>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
var App = React.createClass({
render() {
return (
<div>
<NavBar />
<div>Other Content</div>
{this.props.children}
</div>
)
}
});
Privileges assigned through GRANT option do not need FLUSH PRIVILEGES to take effect - MySQL server will notice these changes and reload the grant tables immediately.
If you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE, your changes have no effect on privilege checking until you either restart the server or tell it to reload the tables. If you change the grant tables directly but forget to reload them, your changes have no effect until you restart the server. This may leave you wondering why your changes seem to make no difference!
To tell the server to reload the grant tables, perform a flush-privileges operation. This can be done by issuing a FLUSH PRIVILEGES statement or by executing a mysqladmin flush-privileges or mysqladmin reload command.
If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.
Shorter way:
var queue = function (args){
typeof variableToCheck !== "undefined"? doSomething(args) : setTimeout(function () {queue(args)}, 2000);
};
You can also pass arguments
Simple steps
git config -f .git/config --remove-section submodule.$submodulename
git config -f .gitmodules --remove-section submodule.$submodulename
git rm --cached $submodulepath
rm -rf $submodulepath
rm -rf .git/modules/$submodulename
Please note: $submodulepath
doesn't contain leading or trailing slashes.
Background
When you do git submodule add
, it only adds it to .gitmodules
, but
once you did git submodule init
, it added to .git/config
.
So if you wish to remove the modules, but be able to restore it quickly, then do just this:
git rm --cached $submodulepath
git config -f .git/config --remove-section submodule.$submodulepath
It is a good idea to do git rebase HEAD
first and git commit
at the end, if you put this in a script.
Also have a look at an answer to Can I unpopulate a Git submodule?.
Swift 3.0/4.0
If you have created your own custom cell you can change the selection color on awakeFromNib()
for all of the cells:
override func awakeFromNib() {
super.awakeFromNib()
let colorView = UIView()
colorView.backgroundColor = UIColor.orange.withAlphaComponent(0.4)
self.selectedBackgroundView = colorView
}
The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.
I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float:
territory):
<br />s
to split the options apart and some CSS to vertically align them:<style type='text/css'>
.input input
{
width: 20px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
Styling the <label>
is why you'll need to resort to Javascript. A library like jQuery
is perfect for this:
<style type='text/css'>
.input label.focused
{
background-color: #EEEEEE;
font-style: italic;
}
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('.input :radio').focus(updateSelectedStyle);
$('.input :radio').blur(updateSelectedStyle);
$('.input :radio').change(updateSelectedStyle);
})
function updateSelectedStyle() {
$('.input :radio').removeClass('focused').next().removeClass('focused');
$('.input :radio:checked').addClass('focused').next().addClass('focused');
}
</script>
The focus
and blur
hooks are needed to make this work in IE.
In Node.js, "high resolution time" is made available via process.hrtime
. It returns a array with first element the time in seconds, and second element the remaining nanoseconds.
To get current time in microseconds, do the following:
var hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)
(Thanks to itaifrenkel for pointing out an error in the conversion above.)
In modern browsers, time with microsecond precision is available as performance.now
. See https://developer.mozilla.org/en-US/docs/Web/API/Performance/now for documentation.
I've made an implementation of this function for Node.js, based on process.hrtime
, which is relatively difficult to use if your solely want to compute time differential between two points in a program. See http://npmjs.org/package/performance-now . Per the spec, this function reports time in milliseconds, but it's a float with sub-millisecond precision.
In Version 2.0 of this module, the reported milliseconds are relative to when the node process was started (Date.now() - (process.uptime() * 1000)
). You need to add that to the result if you want a timestamp similar to Date.now()
. Also note that you should bever recompute Date.now() - (process.uptime() * 1000)
. Both Date.now
and process.uptime
are highly unreliable for precise measurements.
To get current time in microseconds, you can use something like this.
var loadTimeInMS = Date.now()
var performanceNow = require("performance-now")
console.log((loadTimeInMS + performanceNow()) * 1000)
It's actually working quite good with:
import sys
mods = [m.__name__ for m in sys.modules.values() if m]
This will create a list with importable module names.
You can consider using memory-mapped files, via FileChannels .
Generally a lot faster for large files. There are performance trade-offs that could make it slower, so YMMV.
Related answer: Java NIO FileChannel versus FileOutputstream performance / usefulness
Set the main div
CSS to somthing like:
<style>
.wrapper{
display:flex;
flex-direction: column;
}
</style>
<div id="wrapper">
<div id="inner1">This is inner div 1</div>
<div id="inner2">This is inner div 2</div>
</div>
For more flexbox CSS refer: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Use the -ExpandProperty
flag of Select-Object
$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority
Update to answer the other question:
Note that you can as well just access the property:
$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
So to get multiple of these into variables:
$var=Get-WSManInstance -enumerate wmicimv2/win32_process
$prio = $var.Priority
$pid = $var.ProcessID
You say that you have a list of widgets to change dynamically. Do you want to reuse and reconfigure existing widgets, or create all new widgets and delete the old ones? It affects the answer.
If you want to reuse the existing widgets, just reconfigure them. Or, if you just want to hide some of them temporarily, use the corresponding "forget" method to hide them. If you mapped them with pack()
calls, you would hide with pack_forget()
(or just forget()
) calls. Accordingly, grid_forget()
to hide gridded widgets, and place_forget()
for placed widgets.
If you do not intend to reuse the widgets, you can destroy them with a straight destroy()
call, like widget.destroy()
, to free up resources.
Prior to Internet Explorer 8 there were no support for Media queries. But depending on your case you can try to use conditional comments to target only Internet Explorer 8 and lower. You just have to use a proper CSS files architecture.
Let's discuss why an "object not found" error can be thrown in R in addition to explaining what it means. What it means (to many) is obvious: the variable in question, at least according to the R interpreter, has not yet been defined, but if you see your object in your code there can be multiple reasons for why this is happening:
check syntax of your declarations. If you mis-typed even one letter or used upper case instead of lower case in a later calling statement, then it won't match your original declaration and this error will occur.
Are you getting this error in a notebook or markdown document? You may simply need to re-run an earlier cell that has your declarations before running the current cell where you are calling the variable.
Are you trying to knit your R document and the variable works find when you run the cells but not when you knit the cells? If so - then you want to examine the snippet I am providing below for a possible side effect that triggers this error:
{r sourceDataProb1, echo=F, eval=F}
# some code here
The above snippet is from the beginning of an R markdown cell. If eval and echo are both set to False this can trigger an error when you try to knit the document. To clarify. I had a use case where I had left these flags as False because I thought i did not want my code echoed or its results to show in the markdown HTML I was generating. But since the variable was then used in later cells, this caused an error during knitting. Simple trial and error with T/F TRUE/FALSE flags can establish if this is the source of your error when it occurs in knitting an R markdown document from RStudio.
Lastly: did you remove the variable or clear it from memory after declaring it?
Use the shell error handling for unset variables (note the double $
):
$ cat Makefile
foo:
echo "something is set to $${something:?}"
$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127
$ make foo something=x
echo "something is set to ${something:?}"
something is set to x
If you need a custom error message, add it after the ?
:
$ cat Makefile
hello:
echo "hello $${name:?please tell me who you are via \$$name}"
$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127
$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus
Try array_replace_recursive or array_replace functions
$a = array('userID' => 1, 'username'=> 2);
array (
userID => 1,
username => 2
)
$b = array('userID' => 1, 'companyID' => 3);
array (
'userID' => 1,
'companyID' => 3
)
$c = array_replace_recursive($a,$b);
array (
userID => 1,
username => 2,
companyID => 3
)
http://php.net/manual/en/function.array-replace-recursive.php
Simple Way
if ($('#text-field > p.filled-text').length != 0)
The GNU ld linker is a so-called smart linker. It will keep track of the functions used by preceding static libraries, permanently tossing out those functions that are not used from its lookup tables. The result is that if you link a static library too early, then the functions in that library are no longer available to static libraries later on the link line.
The typical UNIX linker works from left to right, so put all your dependent libraries on the left, and the ones that satisfy those dependencies on the right of the link line. You may find that some libraries depend on others while at the same time other libraries depend on them. This is where it gets complicated. When it comes to circular references, fix your code!
If your return type is an array then return an empty array otherwise return null.
In my case, on my Mac OSX, with Python 2.7.18 installed via mac ports, I was able to set the python version to 2.7 with:
$ sudo port select --set python python27
So:
$ python -V
Python 2.7.18
You can not count nulls (at least not in Oracle). Instead try this
SELECT count(1) FROM TABLE WHERE COL_NAME IS NULL
In Short,
Logins will have the access of the server.
and
Users will have the access of the database.
let's say you want a pointer to point at the address 0x28ff4402, the usual way is
uint32_t *ptr;
ptr = (uint32_t*) 0x28ff4402 //type-casting the address value to uint32_t pointer
*ptr |= (1<<13) | (1<<10); //access the address how ever you want
So the short way is to use a MACRO,
#define ptr *(uint32_t *) (0x28ff4402)
you need to enable first the App password of your google account -> security section link
then the app password that will be generated copy it and paste it in to .env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=app_password
MAIL_ENCRYPTION=ssl
The fastest way I found is that:
import java.lang.reflect.Method;
public class TraceHelper {
// save it static to have it available on every call
private static Method m;
static {
try {
m = Throwable.class.getDeclaredMethod("getStackTraceElement",
int.class);
m.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getMethodName(final int depth) {
try {
StackTraceElement element = (StackTraceElement) m.invoke(
new Throwable(), depth + 1);
return element.getMethodName();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
It accesses the native method getStackTraceElement(int depth) directly. And stores the accessible Method in a static variable.
Use extended procedure xp_cmdshell to run a shell command. I used it to print output to a file:
exec xp_cmdshell 'echo "mytextoutput" >> c:\debuginfo.txt'
This creates the file debuginfo.txt if it does not exist. Then it adds the text "mytextoutput" (without quotation marks) to the file. Any call to the function will write an additional line.
You may need to enable this db-server property first (default = disabled), which I realize may not be to the liking of dba's for production environments though.
Covers most of the general stuff -
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
Reference: python .gitignore
I have reformatted your code.
The error was situated in this line :
printf("%d", (**c));
To fix it, change to :
printf("%d", (*c));
The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.
In addition, the () was optional.
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int *c = NULL;
a = &b;
c = &a;
printf("%d", *c);
return 0;
}
EDIT :
The line :
c = &a;
must be replaced by :
c = a;
It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :
10
EDIT 2:
If you want to use a double * :
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int **c = NULL;
a = &b;
c = &a;
printf("%d", **c);
return 0;
}
Output:
10
I had my XML files in a LAYOUT folder instead of MENU folder.
This was as a result of moving to Android Studio from Eclipse.
Solution for me was simple ... move my XML files to the MENU folder and recompile.
I voted for Vinh's answer to get the value.
If you need to find the corresponding label, you can use this code:
$('#ClientID' + ' input:checked').parent().find('label').text()
HTML doesn't have a built-in editable dropdown list or combobox, but I implemented a mostly-CSS solution in an article.
You can see a full demo here but in summary, write HTML like this:
<span class="combobox withtextlist">
<input value="Fruit">
<span tabindex="-1" class="downarrow"></span>
<select size="10" class="sticky">
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
<option>Dewberry</option>
</select>
</span>
And use CSS like this to style it (this is designed for both comboboxes, which have a down-arrow ? button, and dropdown menus which open when clicked and may be styled differently):
/* ------------------------------------------ */
/* ----- combobox / dropdown list styling */
/* ------------------------------------------ */
.combobox {
/* Border slightly darker than Chrome's <select>, slightly lighter than FireFox's */
border: 1px solid #999;
padding-right: 1.25em; /* leave room for ? */
}
.dropdown, .combobox {
/* "relative" and "inline-block" (or just "block") are needed
here so that "absolute" works correctly in children */
position: relative;
display: inline-block;
}
.combobox > .downarrow, .dropdown > .downarrow {
/* ? Outside normal flow, relative to container */
display: inline-block;
position: absolute;
top: 0;
bottom: 0;
right: 0;
width: 1.25em;
cursor: default;
nav-index: -1; /* nonfunctional in most browsers */
border-width: 0px; /* disable by default */
border-style: inherit; /* copy parent border */
border-color: inherit; /* copy parent border */
}
/* Add a divider before the ? down arrow in non-dropdown comboboxes */
.combobox:not(.dropdown) > .downarrow {
border-left-width: 1px;
}
/* Auto-down-arrow if one is not provided */
.downarrow:empty::before {
content: '?';
}
.downarrow::before, .downarrow > *:only-child {
text-align: center;
/* vertical centering trick */
position: relative;
top: 50%;
display: block; /* transform requires block/inline-block */
transform: translateY(-50%);
}
.combobox > input {
border: 0
}
.dropdown > *:last-child,
.combobox > *:last-child {
/* Using `display:block` here has two desirable effects:
(1) Accessibility: it lets input widgets in the dropdown to
be selected with the tab key when the dropdown is closed.
(2) It lets the opacity transition work.
But it also makes the contents visible, which is undesirable
before the list drops down. To compensate, use `opacity: 0`
and disable mouse pointer events. Another side effect is that
the user can select and copy the contents of the hidden list,
but don't worry, the selected content is invisible. */
display: block;
opacity: 0;
pointer-events: none;
transition: 0.4s; /* fade out */
position: absolute;
left: 0;
top: 100%;
border: 1px solid #888;
background-color: #fff;
box-shadow: 1px 2px 4px 1px #666;
box-shadow: 1px 2px 4px 1px #4448;
z-index: 9999;
min-width: 100%;
box-sizing: border-box;
}
/* List of situations in which to show the dropdown list.
- Focus dropdown or non-last child of it => show last-child
- Focus .downarrow of combobox => show last-child
- Stay open for focus in last child, unless .less-sticky
- .sticky last child stays open on hover
- .less-sticky stays open on hover, ignores focus in last-child */
.dropdown:focus > *:last-child,
.dropdown > *:focus ~ *:last-child,
.combobox > .downarrow:focus ~ *:last-child,
.combobox > .sticky:last-child:hover,
.dropdown > .sticky:last-child:hover,
.combobox > .less-sticky:last-child:hover,
.dropdown > .less-sticky:last-child:hover,
.combobox > *:last-child:focus:not(.less-sticky),
.dropdown > *:last-child:focus:not(.less-sticky) {
display: block;
opacity: 1;
transition: 0.15s;
pointer-events: auto;
}
/* focus-within not supported by Edge/IE. Unsupported selectors cause
the entire block to be ignored, so we must repeat all styles for
focus-within separately. */
.combobox > *:last-child:focus-within:not(.less-sticky),
.dropdown > *:last-child:focus-within:not(.less-sticky) {
display: block;
opacity: 1;
transition: 0.15s;
pointer-events: auto;
}
/* detect Edge/IE and behave if though less-sticky is on for all
dropdowns (otherwise links won't be clickable) */
@supports (-ms-ime-align:auto) {
.dropdown > *:last-child:hover {
display: block;
opacity: 1;
pointer-events: auto;
}
}
/* detect IE and do the same thing. */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
.dropdown > *:last-child:hover {
display: block;
opacity: 1;
pointer-events: auto;
}
}
.dropdown:not(.sticky) > *:not(:last-child):focus,
.downarrow:focus, .dropdown:focus {
pointer-events: none; /* Causes second click to close */
}
.downarrow:focus {
outline: 2px solid #8BF; /* Edge/IE can't do outline transparency */
outline: 2px solid #48F8;
}
/* ---------------------------------------------- */
/* Optional extra styling for combobox / dropdown */
/* ---------------------------------------------- */
*, *:before, *:after {
/* See https://css-tricks.com/international-box-sizing-awareness-day/ */
box-sizing: border-box;
}
.combobox > *:first-child {
display: inline-block;
width: 100%;
box-sizing: border-box; /* so 100% includes border & padding */
}
/* `.combobox:focus-within { outline:...}` doesn't work properly
in Firefox because the focus box is expanded to include the
(possibly hidden) drop list. As a workaround, put focus box on
the focused child. It is barely-visible so that it doesn't look
TOO ugly if the child isn't the same size as the parent. It
may be uglier if the first child is not styled as width:100% */
.combobox > *:not(:last-child):focus {
outline: 2px solid #48F8;
}
.combobox {
margin: 5px;
}
You also need some JavaScript to synchronize the list with the textbox:
function parentComboBox(el) {
for (el = el.parentNode; el != null && Array.prototype.indexOf.call(el.classList, "combobox") <= -1;)
el = el.parentNode;
return el;
}
// Uses jQuery
$(".combobox.withtextlist > select").change(function() {
var textbox = parentComboBox(this).firstElementChild;
textbox.value = this[this.selectedIndex].text;
});
$(".combobox.withtextlist > select").keypress(function(e) {
if (e.keyCode == 13) // Enter pressed
parentComboBox(this).firstElementChild.focus(); // Closes the popup
});
This answer is 33 times faster than @Escualo assuming that the list is very large, and assuming that it's already an np.array(). I had to turn down the number of test runs because the test is looking at 10000000 elements not just 100.
import random
from datetime import datetime
import operator
import numpy as np
def explicit(l):
max_val = max(l)
max_idx = l.index(max_val)
return max_idx, max_val
def implicit(l):
max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
return max_idx, max_val
def npmax(l):
max_idx = np.argmax(l)
max_val = l[max_idx]
return (max_idx, max_val)
if __name__ == "__main__":
from timeit import Timer
t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
"import random; import operator; import numpy as np;"
"l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
Results on my computer:
Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass
It could be not supported file encoding. Change it to UTF-8 for example.
I've done this using Sublime
One thing you should know is $ prefix refers to an Angular Method, $$ prefixes refers to angular methods that you should avoid using.
below is an example template and its controllers, we'll explore how $broadcast/$on can help us achieve what we want.
<div ng-controller="FirstCtrl">
<input ng-model="name"/>
<button ng-click="register()">Register </button>
</div>
<div ng-controller="SecondCtrl">
Registered Name: <input ng-model="name"/>
</div>
The controllers are
app.controller('FirstCtrl', function($scope){
$scope.register = function(){
}
});
app.controller('SecondCtrl', function($scope){
});
My question to you is how do you pass the name to the second controller when a user clicks register? You may come up with multiple solutions but the one we're going to use is using $broadcast and $on.
$broadcast vs $emit
Which should we use? $broadcast will channel down to all the children dom elements and $emit will channel the opposite direction to all the ancestor dom elements.
The best way to avoid deciding between $emit or $broadcast is to channel from the $rootScope and use $broadcast to all its children. Which makes our case much easier since our dom elements are siblings.
Adding $rootScope and lets $broadcast
app.controller('FirstCtrl', function($rootScope, $scope){
$scope.register = function(){
$rootScope.$broadcast('BOOM!', $scope.name)
}
});
Note we added $rootScope and now we're using $broadcast(broadcastName, arguments). For broadcastName, we want to give it a unique name so we can catch that name in our secondCtrl. I've chosen BOOM! just for fun. The second arguments 'arguments' allows us to pass values to the listeners.
Receiving our broadcast
In our second controller, we need to set up code to listen to our broadcast
app.controller('SecondCtrl', function($scope){
$scope.$on('BOOM!', function(events, args){
console.log(args);
$scope.name = args; //now we've registered!
})
});
It's really that simple. Live Example
Other ways to achieve similar results
Try to avoid using this suite of methods as it is neither efficient nor easy to maintain but it's a simple way to fix issues you might have.
You can usually do the same thing by using a service or by simplifying your controllers. We won't discuss this in detail but I thought I'd just mention it for completeness.
Lastly, keep in mind a really useful broadcast to listen to is '$destroy' again you can see the $ means it's a method or object created by the vendor codes. Anyways $destroy is broadcasted when a controller gets destroyed, you may want to listen to this to know when your controller is removed.
Yes, its definitely possible to avoid the intermediate conversion to JSON. Using a deep-copy tool like Dozer you can convert the map directly to a POJO. Here is a simplistic example:
Example POJO:
public class MyPojo implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private Integer age;
private Double savings;
public MyPojo() {
super();
}
// Getters/setters
@Override
public String toString() {
return String.format(
"MyPojo[id = %s, name = %s, age = %s, savings = %s]", getId(),
getName(), getAge(), getSavings());
}
}
Sample conversion code:
public class CopyTest {
@Test
public void testCopyMapToPOJO() throws Exception {
final Map<String, String> map = new HashMap<String, String>(4);
map.put("id", "5");
map.put("name", "Bob");
map.put("age", "23");
map.put("savings", "2500.39");
map.put("extra", "foo");
final DozerBeanMapper mapper = new DozerBeanMapper();
final MyPojo pojo = mapper.map(map, MyPojo.class);
System.out.println(pojo);
}
}
Output:
MyPojo[id = 5, name = Bob, age = 23, savings = 2500.39]
Note: If you change your source map to a Map<String, Object>
then you can copy over arbitrarily deep nested properties (with Map<String, String>
you only get one level).
In my case (using windows 10) gradlew.bat has the following lines of code in:
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
The APP_HOME variable is essentially gradles root folder for the project, so, if this gets messed up in some way you are going to get:
Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain
For me, this had been messed up because my project folder structure had an ampersand (&) in it. Eg C:\Test&Dev\MyProject
So, gradel was trying to find the gradle-wrapper.jar file in a root folder of C:\Test (stripping off everything after and including the '&')
I found this by adding the following line below the set APP_HOME=%DIRNAME% line above. Then ran the bat file to see the result.
echo "%APP_HOME%"
There will be a few other 'special characters' that could break a path/directory.
$xml = $( $.parseXML( xml ) );
$xml.find("<<your_xml_tag_name>>").each(function(index,elem){
// elem = found XML element
});
Use time.sleep
or Event().wait
like this:
from threading import Event
from time import sleep
delay_in_sec = 2
# Use time.sleep like this
sleep(delay_in_sec) # Returns None
print(f'slept for {delay_in_sec} seconds')
# Or use Event().wait like this
Event().wait(delay_in_sec) # Returns False
print(f'waited for {delay_in_sec} seconds')
Use threading.Timer
like this:
from threading import Timer
delay_in_sec = 2
def hello(delay_in_sec):
print(f'function called after {delay_in_sec} seconds')
t = Timer(delay_in_sec, hello, [delay_in_sec]) # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start() # Returns None
print("Started")
Outputs:
Started
function called after 2 seconds
timer_obj.cancel()
.This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:
set(CMAKE_CXX_STANDARD 14)
.
Example:
cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)
# Rest of your declarations...
Set focus: The framework will handled moving focus in response to user input. To force focus to a specific view, call requestFocus()
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
Put the entire script into a template string, with {SERVERNAME} placeholders. Then edit the string using:
SET @SQL_SCRIPT = REPLACE(@TEMPLATE, '{SERVERNAME}', @DBNAME)
and then run it with
EXECUTE (@SQL_SCRIPT)
It's hard to believe that, in the course of three years, nobody noticed that my code doesn't work!
You can't EXEC
multiple batches. GO
is a batch separator, not a T-SQL statement. It's necessary to build three separate strings, and then to EXEC
each one after substitution.
I suppose one could do something "clever" by breaking the single template string into multiple rows by splitting on GO
; I've done that in ADO.NET code.
And where did I get the word "SERVERNAME" from?
Here's some code that I just tested (and which works):
DECLARE @DBNAME VARCHAR(255)
SET @DBNAME = 'TestDB'
DECLARE @CREATE_TEMPLATE VARCHAR(MAX)
DECLARE @COMPAT_TEMPLATE VARCHAR(MAX)
DECLARE @RECOVERY_TEMPLATE VARCHAR(MAX)
SET @CREATE_TEMPLATE = 'CREATE DATABASE {DBNAME}'
SET @COMPAT_TEMPLATE='ALTER DATABASE {DBNAME} SET COMPATIBILITY_LEVEL = 90'
SET @RECOVERY_TEMPLATE='ALTER DATABASE {DBNAME} SET RECOVERY SIMPLE'
DECLARE @SQL_SCRIPT VARCHAR(MAX)
SET @SQL_SCRIPT = REPLACE(@CREATE_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)
SET @SQL_SCRIPT = REPLACE(@COMPAT_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)
SET @SQL_SCRIPT = REPLACE(@RECOVERY_TEMPLATE, '{DBNAME}', @DBNAME)
EXECUTE (@SQL_SCRIPT)
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
Instagram developer console has provided the solution for it. https://www.instagram.com/developer/endpoints/
To use this in PHP, here is the code snippet,
/**
**
** Add this code snippet after your first curl call
** assume the response of the first call is stored in $userdata
** $access_token have your access token
*/
$maximumNumberOfPost = 33; // it can be 20, depends on your instagram application
$no_of_images = 50 // Enter the number of images you want
if ($no_of_images > $maximumNumberOfPost) {
$ImageArray = [];
$next_url = $userdata->pagination->next_url;
while ($no_of_images > $maximumNumberOfPost) {
$originalNumbersOfImage = $no_of_images;
$no_of_images = $no_of_images - $maximumNumberOfPost;
$next_url = str_replace("count=" . $originalNumbersOfImage, "count=" . $no_of_images, $next_url);
$chRepeat = curl_init();
curl_setopt_array($chRepeat, [
CURLOPT_URL => $next_url,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $access_token"
],
CURLOPT_RETURNTRANSFER => true
]);
$userRepeatdata = curl_exec($chRepeat);
curl_close($chRepeat);
if ($userRepeatdata) {
$userRepeatdata = json_decode($userRepeatdata);
$next_url = $userRepeatdata->pagination->next_url;
if (isset($userRepeatdata->data) && $userRepeatdata->data) {
$ImageArray = $userRepeatdata->data;
}
}
}
}
You can do it in pure CSS using the :after pseudo-element and getting creative with the margins.
Here's an example, using Font Awesome for the search icon:
.search-box-container input {_x000D_
padding: 5px 20px 5px 5px;_x000D_
}_x000D_
_x000D_
.search-box-container:after {_x000D_
content: "\f002";_x000D_
font-family: FontAwesome;_x000D_
margin-left: -25px;_x000D_
margin-right: 25px;_x000D_
}
_x000D_
<!-- font awesome -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="search-box-container">_x000D_
<input type="text" placeholder="Search..." />_x000D_
</div>
_x000D_
Just add another join:
SELECT dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id,
images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
your error is because of you use class and when use class we need to bind the functions with This in order to work well. anyway there are a lot of tutorial why we should "this" and what is "this" do in javascript.
if you correct your submit button it should be work:
<button type="button" onClick={this.onSubmit.bind(this)} className="btn">Save</button>
and also if you want to show value of that input in console you should use var title = this.title.value;
There are a few reasons for the main thread (or any other thread) to join other threads
A thread may have created or holding (locking) some resources. The join-calling thread may be able to clear the resources on its behalf
join() is a natural blocking call for the join-calling thread to continue after the called thread has terminated.
If a python program does not join other threads, the python interpreter will still join non-daemon threads on its behalf.
If you do not have access to the TestRunner
type information in the calling assembly (it sounds like you may not), you can call the method like this:
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
var obj = Activator.CreateInstance(type);
// Alternately you could get the MethodInfo for the TestRunner.Run method
type.InvokeMember("Run",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
If you have access to the IRunnable
interface type, you can cast your instance to that (rather than the TestRunner
type, which is implemented in the dynamically created or loaded assembly, right?):
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
IRunnable runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one
If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage
Ex: using localStorage and cookies library
var mode = getStoredValue('myPageMode');
function buttonClick(mode) {
mode = mode;
storeValue('myPageMode', mode);
}
function storeValue(key, value) {
if (localStorage) {
localStorage.setItem(key, value);
} else {
$.cookies.set(key, value);
}
}
function getStoredValue(key) {
if (localStorage) {
return localStorage.getItem(key);
} else {
return $.cookies.get(key);
}
}
Use SET
command in Windows CMD to temporarily set the default python for the current session.
SET PATH=C:\Program Files\Python 3.5
I'm not sure if this answers your question, but for example:
if (A || B)
{
Console.WriteLine("Or");
}
if (A && B)
{
Console.WriteLine("And");
}
I know it's an old question and Path.GetFileNameWithoutExtension
is a better and maybe cleaner option. But personally I've added this two methods to my project and wanted to share them. This requires C# 8.0 due to it using ranges and indices.
public static string RemoveExtension(this string file) => ReplaceExtension(file, null);
public static string ReplaceExtension(this string file, string extension)
{
var split = file.Split('.');
if (string.IsNullOrEmpty(extension))
return string.Join(".", split[..^1]);
split[^1] = extension;
return string.Join(".", split);
}
Answer above did not work for me on Chrome. The change event was been fired after I clicked out of the field somewhere, which did not help because the datepicker window is also closed too when you click out of the field.
I did use this code and it worked pretty well. You can place it after calling .datepicker();
HTML
<input type="text" class="datepicker-input" placeholder="click to show datepicker" />
JavaScript
$(".datepicker-input").each(function() {
$(this).datepicker();
});
$(".datepicker-input").click(function() {
$(".datepicker-days .day").click(function() {
$('.datepicker').hide();
});
});
I found another fix:
if (mView.getParent() == null) {
myDialog = new Dialog(MainActivity.this);
myDialog.setContentView(mView);
createAlgorithmDialog();
} else {
createAlgorithmDialog();
}
Here i just have an if statement check if the view had a parent and if it didn't Create the new dialog, set the contentView and show the dialog in my "createAlgorithmDialog()" method.
This also sets the positive and negative buttons (ok and cancel buttons) up with onClickListeners.
Just code it like this:
function example($anon) {
$anon();
}
example(function(){
// some codes here
});
it would be great if you could invent something like this (inspired by Laravel Illuminate):
Object::method("param_1", function($param){
$param->something();
});
I tried to make to do the normalization a bit faster:
en, _ = glyphSmart(data)
func glyphSmart(text string) (int, int) {
gc := 0
dummy := 0
for ind, _ := range text {
gc++
dummy = ind
}
dummy = 0
return gc, dummy
}
I usually print the logs on screen and write into a file as well. Hope this helps someone.
f, err := os.OpenFile("/tmp/orders.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
wrt := io.MultiWriter(os.Stdout, f)
log.SetOutput(wrt)
log.Println(" Orders API Called")
It prevents disclosure of the response through JSON hijacking.
In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).
An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...>
or <img>
tag, but it can't get any information about the result (headers, contents).
Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.
Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.
Note that this happens at the time the JSON is executed as JavaScript, not at the time it's parsed.
There are multiple countermeasures:
By placing a while(1);
statement before the JSON data, Google makes sure that the JSON data is never executed as JavaScript.
Only a legitimate page could actually get the whole content, strip the while(1);
, and parse the remainder as JSON.
Things like for(;;);
have been seen at Facebook for instance, with the same results.
Similarly, adding invalid tokens before the JSON, like &&&START&&&
, makes sure that it is never executed.
This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.
Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.
A valid JSON object, when not enclosed by anything, is not valid in JavaScript:
eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
This is however valid JSON:
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}
So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid JavaScript, while still being valid JSON.
As noted by @hvd in the comments, the empty object {}
is valid JavaScript, and knowing the object is empty may itself be valuable information.
The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).
Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.
Both methods require server side changes in order to avoid developers accidentally sending vulnerable JSON.
The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.
For your purpose, you probably want something like:
FOR %i IN (*.ext) DO my-function %i
Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).
The (*.ext)
part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:
FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i
To perform an operation in a different directory.
There are scores of options for the filespec and FOR in general. See
HELP FOR
from the command prompt for more information.
No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.
Here are some similar questions with similar results:
on Ubuntu 12.04 and the packaged version of NodeJs is too old to install Bower using the PPA
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get -y install nodejs
When this has installed, check the version:
npm --version
1.4.3
Now install Bower:
sudo npm install -g bower
This will fetch and install Bower globally.
Because your question is geared towards a single table, you can use this:
EXEC sp_fkeys 'TableName'
I found it on SO here:
https://stackoverflow.com/a/12956348/652519
I found the information I needed pretty quickly. It lists the foreign key's table, column and name.
EDIT
Here's a link to the documentation that details the different parameters that can be used: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
Access-Engine does not support
SELECT count(DISTINCT....) FROM ...
You have to do it like this:
SELECT count(*)
FROM
(SELECT DISTINCT Name FROM table1)
Its a little workaround... you're counting a DISTINCT selection.
You could do it like this:
String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
which produces:
[123, 456, 789, 0]
The regex (?<=\G...)
matches an empty string that has the last match (\G
) followed by three characters (...
) before it ((?<= )
)
Think about somebody doing help(yourmodule)
at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help
in terms of amount of information). So if you have in x.py
:
"""This module does blah blah."""
class Blah(object):
"""This class does blah blah."""
then:
>>> import x; help(x)
shows:
Help on module x:
NAME
x - This module does blah blah.
FILE
/tmp/x.py
CLASSES
__builtin__.object
Blah
class Blah(__builtin__.object)
| This class does blah blah.
|
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'Blah' objects>
| list of weak references to the object (if defined)
As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).
I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.
you may use this below option.
<style>
div:not(.no_common_style){
background-color:red;
}
</style>
now , if their any place where you do not want to apply default style you can use 'no_common_style' class as class. ex:
<div class="no_common_style">
It will not display in red
</div>
Adding to @Martin's answer...
If anyone planning to keep an application level constant file, you can group the constant based on their type or nature
struct Constants {
struct MixpanelConstants {
static let activeScreen = "Active Screen";
}
struct CrashlyticsConstants {
static let userType = "User Type";
}
}
Call : Constants.MixpanelConstants.activeScreen
UPDATE 5/5/2019 (kinda off topic but ???)
After reading some code guidelines & from personal experiences it seems structs are not the best approach for storing global constants for a couple of reasons. Especially the above code doesn't prevent initialization of the struct. We can achieve it by adding some boilerplate code but there is a better approach
ENUMS
The same can be achieved using an enum with a more secure & clear representation
enum Constants {
enum MixpanelConstants: String {
case activeScreen = "Active Screen";
}
enum CrashlyticsConstants: String {
case userType = "User Type";
}
}
print(Constants.MixpanelConstants.activeScreen.rawValue)
How large is length
? You may do better to re-use a fixed sized (moderately large, but not obscene) buffer, and forget BinaryReader
... just use Stream.Read
and Stream.Write
.
(edit) something like:
private static void copy(string srcFile, string dstFile, int offset,
int length, byte[] buffer)
{
using(Stream inStream = File.OpenRead(srcFile))
using (Stream outStream = File.OpenWrite(dstFile))
{
inStream.Seek(offset, SeekOrigin.Begin);
int bufferLength = buffer.Length, bytesRead;
while (length > bufferLength &&
(bytesRead = inStream.Read(buffer, 0, bufferLength)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
length -= bytesRead;
}
while (length > 0 &&
(bytesRead = inStream.Read(buffer, 0, length)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
If you need extract the text without the brackets, you can use bash awk
echo " [hola mundo] " | awk -F'[][]' '{print $2}'
result:
hola mundo
==
tests object references, .equals()
tests the string values.
Sometimes it looks as if ==
compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.
For example:
String fooString1 = new String("foo");
String fooString2 = new String("foo");
// Evaluates to false
fooString1 == fooString2;
// Evaluates to true
fooString1.equals(fooString2);
// Evaluates to true, because Java uses the same object
"bar" == "bar";
But beware of nulls!
==
handles null
strings fine, but calling .equals()
from a null string will cause an exception:
String nullString1 = null;
String nullString2 = null;
// Evaluates to true
System.out.print(nullString1 == nullString2);
// Throws a NullPointerException
System.out.print(nullString1.equals(nullString2));
So if you know that fooString1
may be null, tell the reader that by writing
System.out.print(fooString1 != null && fooString1.equals("bar"));
The following are shorter, but it’s less obvious that it checks for null:
System.out.print("bar".equals(fooString1)); // "bar" is never null
System.out.print(Objects.equals(fooString1, "bar")); // Java 7 required
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
You can use this method as an alternative.
What will happen is that we take all the tables associated with the users table and delete the related data using looping
$tables = DB::select("
SELECT
TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'users'
");
foreach($tables as $table){
$table_name = $table->TABLE_NAME;
$column_name = $table->COLUMN_NAME;
DB::delete("delete from $table_name where $column_name = ?", [$id]);
}
If you want a list of lists:
>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]
If a list of tuples is OK:
>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]
Don't post the data as an array. To bind to a list, the key/value pairs should be submitted with the same value for each key.
You should not need a form to do this. You just need a list of key/value pairs, which you can include in the call to $.post.
SELECT NULL
FROM HRMTable hm(NOLOCK)
WHERE hm.EmployeeID = 123
AND (
(
CAST(@Fromdate AS date) BETWEEN CAST(hm.FromDate AS date)
AND CAST(hm.ToDate AS date)
)
OR (
CAST(@Todate AS date) BETWEEN CAST(hm.FromDate AS date)
AND CAST(hm.ToDate AS date)
)
)
)
I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there. I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.
UC Irvine Python Extension Repository - http://www.lfd.uci.edu/~gohlke/pythonlibs
pywin32 module - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32
{ "scripts" :
{ "build": "node build.js"}
}
npm run build
ORnpm run-script build
{
"name": "build",
"version": "1.0.0",
"scripts": {
"start": "node build.js"
}
}
npm start
NB: you were missing the
{ brackets }
and the node command
folder structure is fine:
+ build
- package.json
- build.js
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
The code as listed in the question needs two changes
$host = "ssl://smtp.gmail.com";
$port = "465";
Port 465 is required for an SSL connection.
I think it needs to be checked if any row is selected or not? The below code would check it:
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var selectedItem = entityGrid.dataItem(entityGrid.select());
if (selectedItem != undefined)
alert("The Row Is SELECTED");
else
alert("NO Row Is SELECTED")
You should really look at Process Builder. It is really built for this kind of thing.
ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();
the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.
Do you want the first and last name of the row with the largest id?
If so (and you were missing a FROM clause):
SELECT firstname, lastname, id
FROM foo
ORDER BY id DESC
LIMIT 1;
I've experienced that, at least with the Cygwin version of tar I'm using ("CYGWIN_NT-5.1 1.7.17(0.262/5/3) 2012-10-19 14:39 i686 Cygwin" on a Windows XP Home Edition SP3 machine), the order of options is important.
While this construction worked for me:
tar cfvz target.tgz --exclude='<dir1>' --exclude='<dir2>' target_dir
that one didn't work:
tar cfvz --exclude='<dir1>' --exclude='<dir2>' target.tgz target_dir
This, while tar --help
reveals the following:
tar [OPTION...] [FILE]
So, the second command should also work, but apparently it doesn't seem to be the case...
Best rgds,
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id'); // you can add here your personal ID
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data : {
action : 'my_action',
userID : userID
},
success: function(data)
{
alert("success!");
console.log(data);
}
});
});
});
$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 'ID not found';
echo $uid;
$uid add in your functions
note: if $ is not supperted than add jQuery where $ defined
This happens when a session other than the one used to alter a table is holding a lock likely because of a DML (update/delete/insert). If you are developing a new system, it is likely that you or someone in your team issues the update statement and you could kill the session without much consequence. Or you could commit from that session once you know who has the session open.
If you have access to a SQL admin system use it to find the offending session. And perhaps kill it.
You could use v$session and v$lock and others but I suggest you google how to find that session and then how to kill it.
In a production system, it really depends. For oracle 10g and older, you could execute
LOCK TABLE mytable in exclusive mode;
alter table mytable modify mycolumn varchar2(5);
In a separate session but have the following ready in case it takes too long.
alter system kill session '....
It depends on what system do you have, older systems are more likely to not commit every single time. That is a problem since there may be long standing locks. So your lock would prevent any new locks and wait for a lock that who knows when will be released. That is why you have the other statement ready. Or you could look for PLSQL scripts out there that do similar things automatically.
In version 11g there is a new environment variable that sets a wait time. I think it likely does something similar to what I described. Mind you that locking issues don't go away.
ALTER SYSTEM SET ddl_lock_timeout=20;
alter table mytable modify mycolumn varchar2(5);
Finally it may be best to wait until there are few users in the system to do this kind of maintenance.
Copy the file into your src folder. Go to the Project Explorer in Eclipse, Right-click on your project, and click on "Refresh". The file should appear on the Project Explorer pane as well.
Try ArrayDeque
or LinkedList
, which both implement the Queue
interface.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html
I don't know if this what you want but try to remove overflow: hidden from #wrap
Here you go, Python documentation on old string formatting. tutorial -> 7.1.1. Old String Formatting -> "More information can be found in the [link] section".
Note that you should start using the new string formatting when possible.
The best solution to your problem is to move your project folder to other directory with no non-ASCII characters and blank spaces.
For example ?:\Android\PROJECT-FOLDER
.
You can create the directory in C:\
using the name that you want.
Visual Studio 2012 (with ASP.NET and Web Tools 2012.2 RC installed) supports this natively.
Visual Studio 2013 onwards have this built-in.
(Image courtesy: robert.muehsig)
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
class CompareFunctor
{
public:
CompareFunctor(int n) { _n = n; }
bool operator()(int & val1, int & val2)
{
int diff1 = abs(val1 - _n);
int diff2 = abs(val2 - _n);
return (diff1 < diff2);
}
private:
int _n;
};
int Find_Closest_Value(int nums[], int size, int n)
{
CompareFunctor cf(n);
int cn = *min_element(nums, nums + size, cf);
return cn;
}
int main()
{
int nums[] = { 2, 42, 82, 122, 162, 202, 242, 282, 322, 362 };
int size = sizeof(nums) / sizeof(int);
int n = 80;
int cn = Find_Closest_Value(nums, size, n);
cout << "\nClosest value = " << cn << endl;
cin.get();
}
I made a sample WebApp in May 2012 that uses JDO 3.0 & DataNucleus 3.0 - take a look how clean it is: https://github.com/TorbenVesterager/BadAssWebApp
Okay maybe it's a little bit too clean, because I use the POJOs both for the database and the JSON client, but it's fun :)
PS: Contains a few SuppressWarnings annotations (developed in IntelliJ 11)
You could use something like:
<td>
<div style="float:left;width:49%;text-align:left;">this is left</div>
<div style="float:right;width:49%;text-align:right;">this is right</div>
</td>
The 49%
is to give some room for the renderer to wrap things around.
And you can use either <div>
or <span>
RUBY
This code will reject the empty arrays and returns the proper array with values.
def find_sequence(val, num)
b = val.length
(0..b - 1).map {|n| val.uniq.combination(n).each.find_all {|value| value.reduce(:+) == num}}.reject(&:empty?)
end
val = [-10, 1, -1, 2, 0]
num = 2
Output will be [[2],[2,0],[-1,1,2],[-1,1,2,0]]
For jQuery with twitter bootstrap
Check caps locked for the following characters:
uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';', '*', '''
lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ',', '+', '#'
/* check for CAPS LOCK on all password fields */
$("input[type='password']").keypress(function(e) {
var kc = e.which; // get keycode
var isUpperCase = ((kc >= 65 && kc <= 90) || (kc >= 33 && kc <= 34) || (kc >= 36 && kc <= 39) || (kc >= 40 && kc <= 42) || kc == 47 || (kc >= 58 && kc <= 59) || kc == 61 || kc == 63 || kc == 167 || kc == 196 || kc == 214 || kc == 220) ? true : false; // uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';'
var isLowerCase = ((kc >= 97 && kc <= 122) || (kc >= 48 && kc <= 57) || kc == 35 || (kc >= 43 && kc <= 44) || kc == 46 || kc == 228 || kc == 223 || kc == 246 || kc == 252) ? true : false; // lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ','
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = (e.shiftKey) ? e.shiftKey : ((kc == 16) ? true : false); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ((isUpperCase && !isShift) || (isLowerCase && isShift)) {
$(this).next('.form-control-feedback').show().parent().addClass('has-warning has-feedback').next(".capsWarn").show();
} else {
$(this).next('.form-control-feedback').hide().parent().removeClass('has-warning has-feedback').next(".capsWarn").hide();
}
}).after('<span class="glyphicon glyphicon-warning-sign form-control-feedback" style="display:none;"></span>').parent().after("<span class='capsWarn text-danger' style='display:none;'>Is your CAPSLOCK on?</span>");
There are two things you can do:
@Deprecated
annotation to the method, and@deprecated
tag to the javadoc of the methodYou should do both!
Quoting the java documentation on this subject:
Starting with J2SE 5.0, you deprecate a class, method, or field by using the @Deprecated annotation. Additionally, you can use the @deprecated Javadoc tag tell developers what to use instead.
Using the annotation causes the Java compiler to generate warnings when the deprecated class, method, or field is used. The compiler suppresses deprecation warnings if a deprecated compilation unit uses a deprecated class, method, or field. This enables you to build legacy APIs without generating warnings.
You are strongly recommended to use the Javadoc @deprecated tag with appropriate comments explaining how to use the new API. This ensures developers will have a workable migration path from the old API to the new API
There has been some major changes in ms 2008 -> Might be worth considering the following article when making a decisions on what data type to use. http://msdn.microsoft.com/en-us/library/ms143432.aspx
Bytes per
ALTER TABLE dbo.<tablename> ADD CONSTRAINT
<namingconventionconstraint> UNIQUE NONCLUSTERED
(
<columnname>
) ON [PRIMARY]
I add my SMS method if it can help someone. Be careful with smsManager.sendTextMessage, If the text is too long, the message does not go away. You have to respect max length depending of encoding. More information here SMS Manager send mutlipart message when there is less than 160 characters
//TO USE EveryWhere
SMSUtils.sendSMS(context, phoneNumber, message);
//Manifest
<!-- SMS -->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver
android:name=".SMSUtils"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="SMS_SENT"/>
<action android:name="SMS_DELIVERED"/>
</intent-filter>
</receiver>
//JAVA
public class SMSUtils extends BroadcastReceiver {
public static final String SENT_SMS_ACTION_NAME = "SMS_SENT";
public static final String DELIVERED_SMS_ACTION_NAME = "SMS_DELIVERED";
@Override
public void onReceive(Context context, Intent intent) {
//Detect l'envoie de sms
if (intent.getAction().equals(SENT_SMS_ACTION_NAME)) {
switch (getResultCode()) {
case Activity.RESULT_OK: // Sms sent
Toast.makeText(context, context.getString(R.string.sms_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE: // generic failure
Toast.makeText(context, context.getString(R.string.sms_not_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE: // No service
Toast.makeText(context, context.getString(R.string.sms_not_send_no_service), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU: // null pdu
Toast.makeText(context, context.getString(R.string.sms_not_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF: //Radio off
Toast.makeText(context, context.getString(R.string.sms_not_send_no_radio), Toast.LENGTH_LONG).show();
break;
}
}
//detect la reception d'un sms
else if (intent.getAction().equals(DELIVERED_SMS_ACTION_NAME)) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, context.getString(R.string.sms_receive), Toast.LENGTH_LONG).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, context.getString(R.string.sms_not_receive), Toast.LENGTH_LONG).show();
break;
}
}
}
/**
* Test if device can send SMS
* @param context
* @return
*/
public static boolean canSendSMS(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}
public static void sendSMS(final Context context, String phoneNumber, String message) {
if (!canSendSMS(context)) {
Toast.makeText(context, context.getString(R.string.cannot_send_sms), Toast.LENGTH_LONG).show();
return;
}
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT_SMS_ACTION_NAME), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED_SMS_ACTION_NAME), 0);
final SMSUtils smsUtils = new SMSUtils();
//register for sending and delivery
context.registerReceiver(smsUtils, new IntentFilter(SMSUtils.SENT_SMS_ACTION_NAME));
context.registerReceiver(smsUtils, new IntentFilter(DELIVERED_SMS_ACTION_NAME));
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(message);
ArrayList<PendingIntent> sendList = new ArrayList<>();
sendList.add(sentPI);
ArrayList<PendingIntent> deliverList = new ArrayList<>();
deliverList.add(deliveredPI);
sms.sendMultipartTextMessage(phoneNumber, null, parts, sendList, deliverList);
//we unsubscribed in 10 seconds
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
context.unregisterReceiver(smsUtils);
}
}, 10000);
}
}
This is taken from Java: The Complete Reference, Ninth Edition
Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported by the language. Primitive types, rather than objects, are used for these quantities for the sake of performance. Using objects for these values would add an unacceptable overhead to even the simplest of calculations. Thus, the primitive types are not part of the object hierarchy, and they do not inherit Object.
Despite the performance benefit offered by the primitive types, there are times when you will need an object representation. For example, you can’t pass a primitive type by reference to a method. Also, many of the standard data structures implemented by Java operate on objects, which means that you can’t use these (object specific) data structures to store primitive types. To handle these (and other) situations, Java provides type wrappers, which are classes that encapsulate a primitive type within an object.
Wrapper classes relate directly to Java’s autoboxing feature. The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.
I'm going to add to the answer given before.
It's not a bug in your code or the browser's code. It's the JavaScript code inside the YouTube iframe polls for the extensions it could interoperate with in case they were installed (likely to determine if the extension is installed).
Look at the source of www-embed-player.js
(loaded from s.ytimg.com
, it's YouTube static files CDN).
You'll find the following:
function Wj(a){return"chrome-extension://"+a+"/cast_sender.js"}
This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.
To keep the text which falls between the equal sign and the comma:
-replace "^.*?=(.*?),.*?$",'$1'
This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.
From the performance point of view your solution is not optimal. Every time you add another log entry with +=, the whole string is copied to another place in memory. I would recommend using StringBuilder instead:
StringBuilder sb = new StringBuilder();
...
sb.Append("log something");
...
// flush every 20 seconds as you do it
File.AppendAllText(filePath+"log.txt", sb.ToString());
sb.Clear();
By the way your timer event is probably executed on another thread. So you may want to use a mutex when accessing your sb
object.
Another thing to consider is what happens to the log entries that were added within the last 20 seconds of the execution. You probably want to flush your string to the file right before the app exits.
Define columns by min width based on viewport:
/* Number of Cards by Row based on Viewport */
@media (min-width: 576px) {
.card-deck .card {
min-width: 50.1%; /* 1 Column */
margin-bottom: 12px;
}
}
@media (min-width: 768px) {
.card-deck .card {
min-width: 33.4%; /* 2 Columns */
}
}
@media (min-width: 992px) {
.card-deck .card {
min-width: 25.1%; /* 3 Columns */
}
}
@media (min-width: 1200px) {
.card-deck .card {
min-width: 20.1%; /* 4 Columns */
}
}
It was not asked precisely to remove accent (only special characters), but I needed to.
The solutions givens here works but they don’t remove accent: é, è, etc.
So, before doing epascarello’s solution, you can also do:
var newString = "développeur & intégrateur";_x000D_
_x000D_
newString = replaceAccents(newString);_x000D_
newString = newString.replace(/[^A-Z0-9]+/ig, "_");_x000D_
alert(newString);_x000D_
_x000D_
/**_x000D_
* Replaces all accented chars with regular ones_x000D_
*/_x000D_
function replaceAccents(str) {_x000D_
// Verifies if the String has accents and replace them_x000D_
if (str.search(/[\xC0-\xFF]/g) > -1) {_x000D_
str = str_x000D_
.replace(/[\xC0-\xC5]/g, "A")_x000D_
.replace(/[\xC6]/g, "AE")_x000D_
.replace(/[\xC7]/g, "C")_x000D_
.replace(/[\xC8-\xCB]/g, "E")_x000D_
.replace(/[\xCC-\xCF]/g, "I")_x000D_
.replace(/[\xD0]/g, "D")_x000D_
.replace(/[\xD1]/g, "N")_x000D_
.replace(/[\xD2-\xD6\xD8]/g, "O")_x000D_
.replace(/[\xD9-\xDC]/g, "U")_x000D_
.replace(/[\xDD]/g, "Y")_x000D_
.replace(/[\xDE]/g, "P")_x000D_
.replace(/[\xE0-\xE5]/g, "a")_x000D_
.replace(/[\xE6]/g, "ae")_x000D_
.replace(/[\xE7]/g, "c")_x000D_
.replace(/[\xE8-\xEB]/g, "e")_x000D_
.replace(/[\xEC-\xEF]/g, "i")_x000D_
.replace(/[\xF1]/g, "n")_x000D_
.replace(/[\xF2-\xF6\xF8]/g, "o")_x000D_
.replace(/[\xF9-\xFC]/g, "u")_x000D_
.replace(/[\xFE]/g, "p")_x000D_
.replace(/[\xFD\xFF]/g, "y");_x000D_
}_x000D_
_x000D_
return str;_x000D_
}
_x000D_
I know this sounds stupid, but don't see it on here yet :). I had this error caused by forgetting the closing bracket on a function and its associated semi-colon since it was anonymous assigned to a var at the end of my controller.
It appears that many issues with the controller (whether caused by injection error, syntax, etc.) cause this error to appear.
if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...
You could loop through DataGridView
using Rows
property, like:
foreach (DataGridViewRow row in datagridviews.Rows)
{
currQty += row.Cells["qty"].Value;
//More code here
}
In case you want jquery validate to auto pick validations on dynamically added items, you can simply remove and add validation on the whole form like below
//remove validations on entire form
$("#yourFormId")
.removeData("validator")
.removeData("unobtrusiveValidation");
//Simply add it again
$.validator
.unobtrusive
.parse("#yourFormId");
I kept getting the same error until I made the connecting field a unique index in both connecting tables. Only then did the query become updatable.
Philip Stilianos
Wow, you have a huge misunderstanding how asp.net works.
This line of code
System.Diagnostics.Process.Start("help/AdminTutorial.html");
Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.
A very easy solution would be to change the href attribute of the link in you page_load method.
Your aspx code:
<a href="#" runat="server" id="myLink">Tutorial</a>
Your codebehind / cs code of page_load:
...
if (userinfo.user == "Admin")
{
myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else
{
myLink.Attributes["href"] = "help/otherSite.html";
}
...
Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.
It's either through system property
-Dorg.slf4j.simpleLogger.defaultLogLevel=debug
or simplelogger.properties
file on the classpath
see http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for details
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style type="text/css">
*{
font-family: arial;
font-size: 15px;
}
</style>
</head>
<body>
<button id="more">More</button><br/><br/>
<div>
User Name : <input type="text" class="users"/><br/><br/>
</div>
<button id="btn_data">Send Data</button>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#more').on('click',function(x){
var textMore = "User Name : <input type='text' class='users'/><br/><br/>";
$("div").append(textMore);
});
$('#btn_data').on('click',function(x){
var users=$(".users");
$(users).each(function(i, e) {
console.log($(e).val());
});
})
});
</script>
</body>
</html>
About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :
Basically, flatMap
is the equivalent of Promise.then
.
For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay
operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)
Use:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
Check out this for more info: http://www.learningjquery.com/2006/09/introducing-document-ready
Note: This should work as long as the script import for your JQuery library is above this call.
Update:
If for some reason your code is not loading synchronously (which I have never run into, but apparently may be possible from the comment below should not happen), you could code it like the following.
function yourFunctionToRun(){
//Your JQuery goodness here
}
function runYourFunctionWhenJQueryIsLoaded() {
if (window.$){
//possibly some other JQuery checks to make sure that everything is loaded here
yourFunctionToRun();
} else {
setTimeout(runYourFunctionWhenJQueryIsLoaded, 50);
}
}
runYourFunctionWhenJQueryIsLoaded();
DELETE FROM konta WHERE taken <> '';
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
let screenSize: CGRect = UIScreen.main.bounds
If it is a parameter in a function, you can validate it with ValidateNotNullOrEmpty
as you can see in this example:
Function Test-Something
{
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$UserName
)
#stuff todo
}
I had to add !important
to get it to work. I also made my own class button-primary-override
.
.button-primary-override:hover,
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
background-color: #42A5F5 !important;
border-color: #42A5F5 !important;
background-image: none !important;
border: 0 !important;
}
Set the check box after loading the modal window. I think you are setting the check box before loading the page.
$('#fModal').modal('show');
$("#estado_cat").attr("checked","checked");
char[] myChar = theString.ToCharArray();
The best way to put is that hg forget
is identical to hg remove
except that it leaves the files behind in your working copy. The files are left behind as untracked files and can now optionally be ignored with a pattern in .hgignore
.
In other words, I cannot tell if you used hg forget
or hg remove
when I pull from you. A file that you ran hg forget
on will be deleted when I update to that changeset — just as if you had used hg remove
instead.
You should use position: relative
and text-align: center
on the parent element and then display: inline-block
on the child element you want to center. This is a simple CSS design pattern that will work across all major browsers. Here is an example below or check out the CodePen Example.
p {_x000D_
text-align: left;_x000D_
}_x000D_
.container {_x000D_
position: relative;_x000D_
display: block;_x000D_
text-align: center;_x000D_
}_x000D_
/* Style your object */_x000D_
_x000D_
.object {_x000D_
padding: 10px;_x000D_
color: #ffffff;_x000D_
background-color: #556270;_x000D_
}_x000D_
.centerthis {_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
<p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>_x000D_
_x000D_
<span class="object centerthis">Something Centered</span>_x000D_
_x000D_
<p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>_x000D_
</div>
_x000D_
Does this help?
$("#SelectName option[value='theValueOfOption']")[0].selected = true;
If it's a value you'd like to have for every request & template, using a context processor is more appropriate.
Here's how:
Make a context_processors.py
file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE
value in every context:
from django.conf import settings # import the settings file
def admin_media(request):
# return the value you want as a dictionnary. you may add multiple values in there.
return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
add your context processor to your settings.py file:
TEMPLATES = [{
# whatever comes before
'OPTIONS': {
'context_processors': [
# whatever comes before
"your_app.context_processors.admin_media",
],
}
}]
Use RequestContext
in your view to add your context processors in your template. The render
shortcut does this automatically:
from django.shortcuts import render
def my_view(request):
return render(request, "index.html")
and finally, in your template:
...
<a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
...
There is something fundamentally wrong with what you're trying to do. Binary floating-points values do not have decimal places. You cannot meaningfully round one to a given number of decimal places, because most "round" decimal values simply cannot be represented as a binary fraction. Which is why one should never use float
or double
to represent money.
So if you want decimal places in your result, that result must either be a String
(which you already got with the DecimalFormat
), or a BigDecimal
(which has a setScale()
method that does exactly what you want). Otherwise, the result cannot be what you want it to be.
Read The Floating-Point Guide for more information.
You can use the following:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/showdescriptioncontenttitle"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<TextView
android:id="@+id/textview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Your text"
android:typeface="serif" />
</LinearLayout>
The layout needs to be relative for the "center" property to be used.
Just in case, instead of [(ngModel)]
you can use (input)
(is fired when a user writes something in the input <textarea>
) or (blur)
(is fired when a user leaves the input <textarea>
) event,
<textarea cols="30" rows="4" (input)="str = $event.target.value"></textarea>