java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.<!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.io -->
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
</dependency>
Add above dependency in pom.xml file
You can first get all the view controllers in the array and then after checking with the corresponding view controller class, you can delete the one you want.
Here is small piece of code:
NSArray* tempVCA = [self.navigationController viewControllers];
for(UIViewController *tempVC in tempVCA)
{
if([tempVC isKindOfClass:[urViewControllerClass class]])
{
[tempVC removeFromParentViewController];
}
}
I think this will make your work easier.
The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.
That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!
<style>
html, body {
height: 100%;
}
#tableContainer-1 {
height: 100%;
width: 100%;
display: table;
}
#tableContainer-2 {
vertical-align: middle;
display: table-cell;
height: 100%;
}
#myTable {
margin: 0 auto;
}
</style>
<div id="tableContainer-1">
<div id="tableContainer-2">
<table id="myTable" border>
<tr><td>Name</td><td>J W BUSH</td></tr>
<tr><td>Proficiency</td><td>PHP</td></tr>
<tr><td>Company</td><td>BLAH BLAH</td></tr>
</table>
</div>
</div>
response.GetResponseStream()
should be used to return the response stream. And don't forget to close
the Stream
and Response
objects.
DECLARE
CTABLE USER_OBJECTS.OBJECT_NAME%TYPE;
CCOLUMN ALL_TAB_COLS.COLUMN_NAME%TYPE;
V_ALL_COLS VARCHAR2(5000);
CURSOR CURSOR_TABLE
IS
SELECT OBJECT_NAME
FROM USER_OBJECTS
WHERE OBJECT_TYPE='TABLE'
AND OBJECT_NAME LIKE 'STG%';
CURSOR CURSOR_COLUMNS (V_TABLE_NAME IN VARCHAR2)
IS
SELECT COLUMN_NAME
FROM ALL_TAB_COLS
WHERE TABLE_NAME = V_TABLE_NAME;
BEGIN
OPEN CURSOR_TABLE;
LOOP
FETCH CURSOR_TABLE INTO CTABLE;
OPEN CURSOR_COLUMNS (CTABLE);
V_ALL_COLS := NULL;
LOOP
FETCH CURSOR_COLUMNS INTO CCOLUMN;
V_ALL_COLS := V_ALL_COLS || CCOLUMN;
IF CURSOR_COLUMNS%FOUND THEN
V_ALL_COLS := V_ALL_COLS || ', ';
ELSE
EXIT;
END IF;
END LOOP;
close CURSOR_COLUMNS ;
DBMS_OUTPUT.PUT_LINE(V_ALL_COLS);
EXIT WHEN CURSOR_TABLE%NOTFOUND;
END LOOP;`enter code here`
CLOSE CURSOR_TABLE;
END;
I have added Close of second cursor. It working and getting output as well...
Nobody has actually given a pure javascript
answer (as requested by OP), so here it is:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
return false;
}
req.send(sendstr); // param string only used for POST
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return "XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()
if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
In your case:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
static mySingleton *obj=nil;
@implementation mySingleton
-(id) init {
if(obj != nil){
[self release];
return obj;
} else if(self = [super init]) {
obj = self;
}
return obj;
}
+(mySingleton*) getSharedInstance {
@synchronized(self){
if(obj == nil) {
obj = [[mySingleton alloc] init];
}
}
return obj;
}
- (id)retain {
return self;
}
- (id)copy {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
- (void)release {
if(obj != self){
[super release];
}
//do nothing
}
- (id)autorelease {
return self;
}
-(void) dealloc {
[super dealloc];
}
@end
var date = DateTime.Now;
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:
with open('my_file.txt', 'rU') as in_file:
data = in_file.read().split('\n')
That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:
with open('new_file.txt', 'w') as out_file:
out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters
Hopefully that fits what you're looking for.
The first option should sufice: http://jsfiddle.net/sFCg3/
jQuery('#autoship_option').val('');
But you have to make sure you are runing this on an event like click
of a button or ready
or document, like on the jsfiddle.
Also make sure that theres always a value attribute on the option tags. If not, some browsers always return empty on val()
.
Edit:
Now that you have clarifyed the use of the Chosen plugin, you have to call
$("#autoship_option").trigger("liszt:updated");
after changing the value for it to update the intereface.
dot
is matrix multiplication, but *
does something else.
We have two arrays:
X
, shape (97,2)y
, shape (2,1)With Numpy arrays, the operation
X * y
is done element-wise, but one or both of the values can be expanded in one or more dimensions to make them compatible. This operation is called broadcasting. Dimensions, where size is 1 or which are missing, can be used in broadcasting.
In the example above the dimensions are incompatible, because:
97 2
2 1
Here there are conflicting numbers in the first dimension (97 and 2). That is what the ValueError above is complaining about. The second dimension would be ok, as number 1 does not conflict with anything.
For more information on broadcasting rules: http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
(Please note that if X
and y
are of type numpy.matrix
, then asterisk can be used as matrix multiplication. My recommendation is to keep away from numpy.matrix
, it tends to complicate more than simplifying things.)
Your arrays should be fine with numpy.dot
; if you get an error on numpy.dot
, you must have some other bug. If the shapes are wrong for numpy.dot
, you get a different exception:
ValueError: matrices are not aligned
If you still get this error, please post a minimal example of the problem. An example multiplication with arrays shaped like yours succeeds:
In [1]: import numpy
In [2]: numpy.dot(numpy.ones([97, 2]), numpy.ones([2, 1])).shape
Out[2]: (97, 1)
This post has a reasonable answer:
CMakeLists.txt.in
:
cmake_minimum_required(VERSION 2.8.2)
project(googletest-download NONE)
include(ExternalProject)
ExternalProject_Add(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG master
SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src"
BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
CMakeLists.txt
:
# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in
googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download )
execute_process(COMMAND ${CMAKE_COMMAND} --build .
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download )
# Prevent GoogleTest from overriding our compiler/linker options
# when building with Visual Studio
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
# Add googletest directly to our build. This adds
# the following targets: gtest, gtest_main, gmock
# and gmock_main
add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src
${CMAKE_BINARY_DIR}/googletest-build)
# The gtest/gmock targets carry header search path
# dependencies automatically when using CMake 2.8.11 or
# later. Otherwise we have to add them here ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
include_directories("${gtest_SOURCE_DIR}/include"
"${gmock_SOURCE_DIR}/include")
endif()
# Now simply link your own targets against gtest, gmock,
# etc. as appropriate
However it does seem quite hacky. I'd like to propose an alternative solution - use Git submodules.
cd MyProject/dependencies/gtest
git submodule add https://github.com/google/googletest.git
cd googletest
git checkout release-1.8.0
cd ../../..
git add *
git commit -m "Add googletest"
Then in MyProject/dependencies/gtest/CMakeList.txt
you can do something like:
cmake_minimum_required(VERSION 3.3)
if(TARGET gtest) # To avoid diamond dependencies; may not be necessary depending on you project.
return()
endif()
add_subdirectory("googletest")
I haven't tried this extensively yet but it seems cleaner.
Edit: There is a downside to this approach: The subdirectory might run install()
commands that you don't want. This post has an approach to disable them but it was buggy and didn't work for me.
Edit 2: If you use add_subdirectory("googletest" EXCLUDE_FROM_ALL)
it seems means the install()
commands in the subdirectory aren't used by default.
For the solution in batch. I am using the following command:
FOR /D /R %%G in (obj,bin) DO @IF EXIST %%G IF %%~aG geq d RMDIR /S /Q "%%G"
The reason not using DIR /S /AD /B xxx
1. DIR /S /AD /B obj
will return empty list (at least on my Windows10)
2. DIR /S /AD /B *obj
will contain the result which is not expected (tobj folder)
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing three object arrays
Object[] array1 = new Object[] { 1, 123 };
Object[] array2 = new Object[] { 1, 123, 22, 4 };
Object[] array3 = new Object[] { 1, 123 };
// comparing array1 and array2
boolean retval=Arrays.equals(array1, array2);
System.out.println("array1 and array2 equal: " + retval);
System.out.println("array1 and array2 equal: " + array1.equals(array2));
// comparing array1 and array3
boolean retval2=Arrays.equals(array1, array3);
System.out.println("array1 and array3 equal: " + retval2);
System.out.println("array1 and array3 equal: " + array1.equals(array3));
}
}
Here is the output:
array1 and array2 equal: false
array1 and array2 equal: false
array1 and array3 equal: true
array1 and array3 equal: false
Seeing this kind of problem I would personally go for Arrays.equals(array1, array2)
as per your question to avoid confusion.
cout << "\a";
In Xcode, After compiling, you have to run the executable by hand to hear the beep.
You can set environment variables in the notebook using os.environ
. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"
You can double check that you have the correct devices visible to TF
from tensorflow.python.client import device_lib
print device_lib.list_local_devices()
I tend to use it from utility module like notebook_util
import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf
<input type="submit" <a href="#" onclick="history.back();">"Back"</a>
Is invalid HTML due to the unclosed input
element.
<a href="#" onclick="history.back(1);">"Back"</a>
is enough
Check to see if the key-value pair is actually showing up in the request:
In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers
Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like:
F12: Developer Tools > Sources Tab > YourJavascriptSrc.js
and check your code.
But as other answers have said:
xhttp.setRequestHeader(key, value);
should add a key-value pair to your request header, just make sure to place it after your open()
and before your send()
There isn't a way to define a variable in the formula bar of Excel. As a workaround you could place the function in another cell (optionally, hiding the contents or placing it in a separate sheet). Otherwise you could create a VBA function.
The default value of error_reporting flag is E_ALL & ~E_NOTICE if not set in php.ini. But in some installation (particularly installations targeting development environments) has E_ALL | E_STRICT set as value of this flag (this is the recommended value during development). In some cases, specially when you'll want to run some open source projects, that was developed prior to PHP 5.3 era and not yet updated with best practices defined by PHP 5.3, in your development environment, you'll probably run into getting some messages like you are getting. The best way to cope up on this situation, is to set only E_ALL as the value of error_reporting flag, either in php.ini or in code (probably in a front-controller like index.php in web-root as follows:
if(defined('E_STRICT')){
error_reporting(E_ALL);
}
Solution for a fresh install of Tomcat 7 on Ubuntu 12.04.
Edit this file - /etc/tomcat7/tomcat-users.xml
to add this xml section -
<tomcat-users>
<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="tomcatadmin" password="tomcat2009" roles="admin,admin-gui,manager-gui"/>
</tomcat-users>
restart Tomcat -
service tomcat7 restart
urls to access managers -
just wanted to put the latest info out there.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:[email protected]
Most of the answers seem to assume that iterative
= for loop
. If your for loop is unrestricted (a la C, you can do whatever you want with your loop counter), then that is correct. If it's a real for
loop (say as in Python or most functional languages where you cannot manually modify the loop counter), then it is not correct.
All (computable) functions can be implemented both recursively and using while
loops (or conditional jumps, which are basically the same thing). If you truly restrict yourself to for loops
, you will only get a subset of those functions (the primitive recursive ones, if your elementary operations are reasonable). Granted, it's a pretty large subset which happens to contain every single function you're likely to encouter in practice.
What is much more important is that a lot of functions are very easy to implement recursively and awfully hard to implement iteratively (manually managing your call stack does not count).
I tried all these method but none worked for me. I removed .git file using rm -rf .git
form the local repository and then again did git init
and git add
and routine commands. It worked.
iOS Simulator -> I/O -> Keyboard -> Connect Hardware Keyboard
I was facing similar issues but above flow chart is the fix for your issue.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}
In this code you can put your address in a text box.
If you are getting this from an outside site it might be helpful to use jQuery's getJSON. If it's a list you can iterate through it with $.each
$.getJSON(url, function (json) {
alert(json.result);
$.each(json.list, function (i, fb) {
alert(fb.result);
});
});
Would not that have to be:
.replaceAll("\"","\\\\\"")
FIVE backslashes in the replacement String.
Why do you not use the java functionality for that:
If your numbers are small (smaller than yours) you could use: Integer.parseInt(hex, 16)
to convert a Hex - String into an integer.
String hex = "ff"
int value = Integer.parseInt(hex, 16);
For big numbers like yours, use public BigInteger(String val, int radix)
BigInteger value = new BigInteger(hex, 16);
@See JavaDoc:
Should work.
Here's a working example:
Excerpt:
function loadIframe(iframeName, url) {
var $iframe = $('#' + iframeName);
if ($iframe.length) {
$iframe.attr('src',url);
return false;
}
return true;
}
You should look at a job scheduled using the SQL Server Agent.
For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.
<div class="headerdivider"></div>
and
.headerdivider {
border-left: 1px solid #38546d;
background: #16222c;
width: 1px;
height: 80px;
position: absolute;
right: 250px;
top: 10px;
}
I realize this is a later answer, but I found another reference to a way to address this issue that might help others in the future. This web page describes setting an environment variable (COMPLUS_ZapDisable=1) that prevents optimization, at least it did for me! (Don't forget the second part of disabling the Visual Studio hosting process.) In my case, this might have been even more relevant because I was debugging an external DLL thru a symbol server, but I'm not sure.
Here i post my code, after i have pushed myself for one working day to find this solution.
Function to get the last saved record :
private function getLastId($query) {
$conn = $this->getDoctrine()->getConnection();
$stmt = $conn->prepare($query);
$stmt->execute();
$lastId = $stmt->fetch()['id'];
return $lastId;
}
Another Function which call the above function
private function clientNum() {
$lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
$noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
return $noClient;
}
add #include <iostream>
to the start of io.cpp
too.
And just to provide a contrast, there's also pip.
You need to require only one plugin which is the Subversion plugin.
Then simply, go into Jenkins ? job_name ? Build Trigger section ? (i) Trigger build remotely (i.e., from scripts) Authentication token: Token_name
Go to the SVN server's hooks directory, and then after fire the below commands:
cp post-commit.tmpl post-commit
chmod 777 post-commit
chown -R www-data:www-data post-commit
vi post-commit
Note: All lines should be commented Add the below line at last
Syntax (for Linux users):
/usr/bin/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name
Syntax (for Windows user):
C:/curl_for_win/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name
Insert Into FEMALE(ID, Image)
Select '1', BulkColumn
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image
You will also need admin rights to run the query.
set define off <- This is the best solution I found
I also tried...
set define }
I was able to insert several records containing ampersand characters '&' but I cannot use the '}' character into the text So I decided to use "set define off" and everything works as it should.
Inside the DataTemplate
you're working in the context of a Rule
, that's why you cannot bind to SelectedRule.Name
-- there is no such property on a Rule
.
To bind to the original data context (which is your ViewModel) you can write:
<TextBlock Text="{Binding ElementName=lbRules, Path=DataContext.SelectedRule.Name}" />
UPDATE: regarding the SelectedItem property binding, it looks perfectly valid, I tried the same on my machine and it works fine. Here is my full test app:
XAML:
<Window x:Class="TestWpfApplication.ListBoxSelectedItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ListBoxSelectedItem" Height="300" Width="300"
xmlns:app="clr-namespace:TestWpfApplication">
<Window.DataContext>
<app:ListBoxSelectedItemViewModel/>
</Window.DataContext>
<ListBox ItemsSource="{Binding Path=Rules}" SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:" />
<TextBox Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
Code behind:
namespace TestWpfApplication
{
/// <summary>
/// Interaction logic for ListBoxSelectedItem.xaml
/// </summary>
public partial class ListBoxSelectedItem : Window
{
public ListBoxSelectedItem()
{
InitializeComponent();
}
}
public class Rule
{
public string Name { get; set; }
}
public class ListBoxSelectedItemViewModel
{
public ListBoxSelectedItemViewModel()
{
Rules = new ObservableCollection<Rule>()
{
new Rule() { Name = "Rule 1"},
new Rule() { Name = "Rule 2"},
new Rule() { Name = "Rule 3"},
};
}
public ObservableCollection<Rule> Rules { get; private set; }
private Rule selectedRule;
public Rule SelectedRule
{
get { return selectedRule; }
set
{
selectedRule = value;
}
}
}
}
Structure your code so that all your temporary objects are located inside closures instead of global namespace / global object properties and go out of scope when you've done with them. GC will take care of the rest.
Try the following code:
function getStackTrace(){
var f = arguments.callee;
var ret = [];
var item = {};
var iter = 0;
while ( f = f.caller ){
// Initialize
item = {
name: f.name || null,
args: [], // Empty array = no arguments passed
callback: f
};
// Function arguments
if ( f.arguments ){
for ( iter = 0; iter<f.arguments.length; iter++ ){
item.args[iter] = f.arguments[iter];
}
} else {
item.args = null; // null = argument listing not supported
}
ret.push( item );
}
return ret;
}
Worked for me in Firefox-21 and Chromium-25.
For me what worked by combining all the posts I have read is:
1.Enable OLE automation - if not enabled
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2.Create a folder where the generated files will be stored:
C:\GREGTESTING
3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
CREATE TABLE [dbo].[Document](
[Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Extension] [varchar](50) NULL,
[FileName] [varchar](200) NULL,
[Doc_Content] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)
Important note!
Don't forget to add in Doc_Content column the varbinary of file you want to generate!
4.Run the below script
DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath varchar(max)
--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num] varchar(100) , [FileName] varchar(100), [Doc_Content] varBinary(max) )
INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM [dbo].[Document]
SELECT @i = COUNT(1) FROM @Doctable
WHILE @i >= 1
BEGIN
SELECT
@data = [Doc_Content],
@fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
@folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+ @fPath
--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END
Heh, this is an old question that could use a better answer.
User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”
Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string?type conversion and observe the success or failure:
template <typename T>
std::optional <T> string_to( const std::string& s )
{
std::istringstream ss( s );
T result;
ss >> result >> std::ws; // attempt the conversion
if (ss.eof()) return result; // success
return {}; // failure
}
Using the optional
type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.
Here is an example of using it:
int n;
std::cout << "n? ";
{
std::string s;
getline( std::cin, s );
auto x = string_to <int> ( s );
if (!x) return complain();
n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
limitations and type identification
In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.
The next caveat is that some types subsume others. For example, if you are trying to distinguish between int
and double
, check for int
first, since anything that converts to an int
is also a double
.
You can use axe selectors for this.
There are two approaches:
<
)#a:hover < #content + #b
This axe style rule will select #b
, which is the immediate sibling of #content
, which is the immediate parent of #a
which has a :hover
state.
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}
#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}
#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}
#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}
#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}
#a:hover < #content + #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>
<div id="b">Show me</div>
<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
\
)#a:hover \ #b
This axe style rule will select #b
, which is present in the same document as #a
which has a :hover
state.
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}
#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}
#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}
#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}
#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}
#a:hover \ #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>
<div id="b">Show me</div>
<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
You can use RegExMatch
:
=IF(RegExMatch(A1;"Bla");"YES";"NO")
Use text-decoration:none !important;
instead of text-decoration:none;
to make sure you "lose" the underline.
I create HashMaps in bash 3 using dynamic variables. I explained how that works in my answer to: Associative arrays in Shell scripts
Also you can take a look in shell_map, which is a HashMap implementation made in bash 3.
You can implement your OTF
font using @font-face like:
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWeb.otf") format("opentype");
}
@font-face {
font-family: GraublauWeb;
font-weight: bold;
src: url("path/GraublauWebBold.otf") format("opentype");
}
// Edit: OTF now works in most browsers, see comments
However if you want to support a wide variety of browsers i would recommend you to switch to WOFF
and TTF
font types. WOFF
type is implemented by every major desktop browser, while the TTF
type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf") format("truetype");
}
If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:
@font-face {
font-family: GraublauWeb;
src: url("webfont.eot"); /* IE9 Compat Modes */
src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
url("webfont.woff") format("woff"), /* Modern Browsers */
url("webfont.ttf") format("truetype"), /* Safari, Android, iOS */
url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}
You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:
hope this helps
Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.
All the methods above do not handle deep cloning of objects where it is nested to n levels. I did not check its performance over others but it is short and simple.
The first example below shows object cloning using Object.assign
which clones just till first level.
var person = {_x000D_
name:'saksham',_x000D_
age:22,_x000D_
skills: {_x000D_
lang:'javascript',_x000D_
experience:5_x000D_
}_x000D_
}_x000D_
_x000D_
newPerson = Object.assign({},person);_x000D_
newPerson.skills.lang = 'angular';_x000D_
console.log(newPerson.skills.lang); //logs Angular
_x000D_
Using the below approach deep clones object
var person = {_x000D_
name:'saksham',_x000D_
age:22,_x000D_
skills: {_x000D_
lang:'javascript',_x000D_
experience:5_x000D_
}_x000D_
}_x000D_
_x000D_
anotherNewPerson = JSON.parse(JSON.stringify(person));_x000D_
anotherNewPerson.skills.lang = 'angular';_x000D_
console.log(person.skills.lang); //logs javascript
_x000D_
I want to post a simple solution for every schema you've got. If you are using MySQL DB, you can simply get from your schema all the table's name and add the WHERE-LIKE condition on it. You also could do it with the usual command line as follows:
SHOW TABLES WHERE tables_in_<your_shcema_name> LIKE '%<table_partial_name>%';
where tables_in_<your_shcema_name>
returns the column's name of SHOW TABLES
command.
As pointed out by others, you simply create mockAppender
and then create a LoggingEvent
instance which essentially listens to the logging event registered/happens inside mockAppender
.
Here is how it looks like in test:
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
@RunWith(MockitoJUnitRunner.class)
public class TestLogEvent {
// your Logger
private Logger log = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
// here we mock the appender
@Mock
private Appender<ILoggingEvent> mockAppender;
// Captor is generic-ised with ch.qos.logback.classic.spi.LoggingEvent
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
/**
* set up the test, runs before each test
*/
@Before
public void setUp() {
log.addAppender(mockAppender);
}
/**
* Always have this teardown otherwise we can stuff up our expectations.
* Besides, it's good coding practise
*/
@After
public void teardown() {
log.detachAppender(mockAppender);
}
// Assuming this is your method
public void yourMethod() {
log.info("hello world");
}
@Test
public void testYourLoggingEvent() {
//invoke your method
yourMethod();
// now verify our logging interaction
// essentially appending the event to mockAppender
verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture());
// Having a generic captor means we don't need to cast
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
// verify that info log level is called
assertThat(loggingEvent.getLevel(), is(Level.INFO));
// Check the message being logged is correct
assertThat(loggingEvent.getFormattedMessage(), containsString("hello world"));
}
}
When you say that
$_SERVER['DOCUMENT_ROOT']
contains this path:
D:/workspace
Then D:
is what you are looking for, isn't it?
In that case you could explode the string by slashes and return the first one:
$pathInPieces = explode('/', $_SERVER['DOCUMENT_ROOT']);
echo $pathInPieces[0];
This will output the server's root directory.
Update: When you use the constant DIRECTORY_SEPARATOR
instead of the hardcoded slash ('/'
) this code is also working under Windows.
Update 2: The $_SERVER
global variable is not always available. On command line (cli) for example. So you should use __DIR__
instead of $_SERVER['DOCUMENT_ROOT']
. __DIR__
returns the path of the php file itself.
See for example Angular 2 - Implementation of shared services
@Injectable()
export class MyGlobals {
readonly myConfigValue:string = 'abc';
}
@NgModule({
providers: [MyGlobals],
...
})
class MyComponent {
constructor(private myGlobals:MyGlobals) {
console.log(myGlobals.myConfigValue);
}
}
or provide individual values
@NgModule({
providers: [{provide: 'myConfigValue', useValue: 'abc'}],
...
})
class MyComponent {
constructor(@Inject('myConfigValue') private myConfigValue:string) {
console.log(myConfigValue);
}
}
I had this problem with Visual Studio 2017: It turns out that there are two class library projects - one for .Net and the other for C#. I created the one for .Net and when I tried to install a specific package (Nunit in my case) I got the error message.
Recreating the project as C# class library fixed the problem
There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data
argument as yadda
, but miss one of the places it is used in the function's body... Now data
refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError
if you didn't have a global name data
.
Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo
at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo
.
Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.
None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.
Java8:
My upgrage version from top answer:
/**
* Execute {@link AppWork} once per day.
* <p>
* Created by aalexeenka on 29.12.2016.
*/
public class OncePerDayAppWorkExecutor {
private static final Logger LOG = AppLoggerFactory.getScheduleLog(OncePerDayAppWorkExecutor.class);
private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
private final String name;
private final AppWork appWork;
private final int targetHour;
private final int targetMin;
private final int targetSec;
private volatile boolean isBusy = false;
private volatile ScheduledFuture<?> scheduledTask = null;
private AtomicInteger completedTasks = new AtomicInteger(0);
public OncePerDayAppWorkExecutor(
String name,
AppWork appWork,
int targetHour,
int targetMin,
int targetSec
) {
this.name = "Executor [" + name + "]";
this.appWork = appWork;
this.targetHour = targetHour;
this.targetMin = targetMin;
this.targetSec = targetSec;
}
public void start() {
scheduleNextTask(doTaskWork());
}
private Runnable doTaskWork() {
return () -> {
LOG.info(name + " [" + completedTasks.get() + "] start: " + minskDateTime());
try {
isBusy = true;
appWork.doWork();
LOG.info(name + " finish work in " + minskDateTime());
} catch (Exception ex) {
LOG.error(name + " throw exception in " + minskDateTime(), ex);
} finally {
isBusy = false;
}
scheduleNextTask(doTaskWork());
LOG.info(name + " [" + completedTasks.get() + "] finish: " + minskDateTime());
LOG.info(name + " completed tasks: " + completedTasks.incrementAndGet());
};
}
private void scheduleNextTask(Runnable task) {
LOG.info(name + " make schedule in " + minskDateTime());
long delay = computeNextDelay(targetHour, targetMin, targetSec);
LOG.info(name + " has delay in " + delay);
scheduledTask = executorService.schedule(task, delay, TimeUnit.SECONDS);
}
private static long computeNextDelay(int targetHour, int targetMin, int targetSec) {
ZonedDateTime zonedNow = minskDateTime();
ZonedDateTime zonedNextTarget = zonedNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec).withNano(0);
if (zonedNow.compareTo(zonedNextTarget) > 0) {
zonedNextTarget = zonedNextTarget.plusDays(1);
}
Duration duration = Duration.between(zonedNow, zonedNextTarget);
return duration.getSeconds();
}
public static ZonedDateTime minskDateTime() {
return ZonedDateTime.now(ZoneId.of("Europe/Minsk"));
}
public void stop() {
LOG.info(name + " is stopping.");
if (scheduledTask != null) {
scheduledTask.cancel(false);
}
executorService.shutdown();
LOG.info(name + " stopped.");
try {
LOG.info(name + " awaitTermination, start: isBusy [ " + isBusy + "]");
// wait one minute to termination if busy
if (isBusy) {
executorService.awaitTermination(1, TimeUnit.MINUTES);
}
} catch (InterruptedException ex) {
LOG.error(name + " awaitTermination exception", ex);
} finally {
LOG.info(name + " awaitTermination, finish");
}
}
}
Since don't know which version of automake you can use DESTDIR environment variable.
See Makefile to be sure.
For example:
export DESTDIR="$HOME/Software/LocalInstall" && make -j4 install
It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.
From version 0.8.0, dplyr
offers a handy function called group_split()
:
# On sample data from @Aus_10
df %>%
group_split(g)
[[1]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 2.04 0.627 A
2 0.530 -0.703 A
3 -0.475 0.541 A
4 1.20 -0.565 A
5 -0.380 -0.126 A
6 1.25 -1.69 A
7 -0.153 -1.02 A
8 1.52 -0.520 A
9 0.905 -0.976 A
10 0.517 -0.535 A
# … with 15 more rows
[[2]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 1.61 0.858 B
2 1.05 -1.25 B
3 -0.440 -0.506 B
4 -1.17 1.81 B
5 1.47 -1.60 B
6 -0.682 -0.726 B
7 -2.21 0.282 B
8 -0.499 0.591 B
9 0.711 -1.21 B
10 0.705 0.960 B
# … with 15 more rows
To not include the grouping column:
df %>%
group_split(g, keep = FALSE)
public static void linktest()
{
System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://toolsqa.wpengine.com/");
//List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
//int linkcount=allLinkElements.size();
//System.out.println(linkcount);
List<WebElement> link = driver.findElements(By.tagName("a"));
String data="HOME";
int linkcount=link.size();
System.out.println(linkcount);
for(int i=0;i<link.size();i++) {
if(link.get(i).getText().contains(data)) {
System.out.println("true");
}
}
}
No, it's not possible using just one selector. The :first-of-type
pseudo-class selects the first element of its type (div
, p
, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.
Unfortunately, CSS doesn't provide a :first-of-class
selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:
.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }
Explanations and illustrations for the workaround are given here and here.
Use a margin to space around an element.
.box {
margin: top right bottom left;
}
.box {
margin: 10px 5px 10px 5px;
}
This adds space outside of the element. So background colours, borders etc will not be included.
If you want to add spacing within an element use padding instead. It can be called in the same way as above.
Easiest solution, works if you have already a tag or not, and removes it automatically so it wont keep adding equal tags, have fun
function changeURL(tag)
{
if(window.location.href.indexOf("?") > -1) {
if(window.location.href.indexOf("&"+tag) > -1){
var url = window.location.href.replace("&"+tag,"")+"&"+tag;
}
else
{
var url = window.location.href+"&"+tag;
}
}else{
if(window.location.href.indexOf("?"+tag) > -1){
var url = window.location.href.replace("?"+tag,"")+"?"+tag;
}
else
{
var url = window.location.href+"?"+tag;
}
}
window.location = url;
}
THEN
changeURL("i=updated");
Firstly, the level name to use is FINE
, not DEBUG
. Let's assume for a minute that DEBUG
is actually valid, as it makes the following explanation make a bit more sense...
In the Handler specific properties
section, you're setting the logging level for those handlers to DEBUG
. This means the handlers will handle any log messages with the DEBUG
level or higher. It doesn't necessarily mean any DEBUG
messages are actually getting passed to the handlers.
In the Facility specific properties
section, you're setting the logging level for a few explicitly-named loggers to DEBUG
. For those loggers, anything at level DEBUG
or above will get passed to the handlers.
The default logging level is INFO
, and apart from the loggers mentioned in the Facility specific properties
section, all loggers will have that level.
If you want to see all FINE
messages, add this:
.level = FINE
However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:
your.package.level = FINE
See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE
instead of DEBUG
:
...
1catalina.org.apache.juli.FileHandler.level = FINE
...
and also gives you examples of setting additional logging levels:
# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE
Try this:
<body>
<div id="divMsg"></div>
</body>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>
He only asked about signed and unsigned. Don't know why people are adding extra stuff in this. Let me tell you the answer.
Unsigned: It consists of only non-negative values i.e 0 to 255.
Signed: It consist of both negative and positive values but in different formats like
And this explanation is about the 8-bit number system.
The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.
The formula is:
Where:
is the physical linear resolution
and:
is the logical linear resolution
Other devices report different device pixel ratios, including non-integer ones. For example, the Nokia Lumia 1020 reports 1.6667, the Samsumg Galaxy S4 reports 3, and the Apple iPhone 6 Plus reports 2.46 (source: dpilove). But this does not change anything in principle, as you should never design for any one specific device.
The CSS "pixel" is not even defined as "one picture element on some screen", but rather as a non-linear angular measurement of viewing angle, which is approximately of an inch at arm's length. Source: CSS Absolute Lengths
This has lots of implications when it comes to web design, such as preparing high-definition image resources and carefully applying different images at different device pixel ratios. You wouldn't want to force a low-end device to download a very high resolution image, only to downscale it locally. You also don't want high-end devices to upscale low resolution images for a blurry user experience.
If you are stuck with bitmap images, to accommodate for many different device pixel ratios, you should use CSS Media Queries to provide different sets of resources for different groups of devices. Combine this with nice tricks like background-size: cover
or explicitly set the background-size
to percentage values.
#element { background-image: url('lores.png'); }
@media only screen and (min-device-pixel-ratio: 2) {
#element { background-image: url('hires.png'); }
}
@media only screen and (min-device-pixel-ratio: 3) {
#element { background-image: url('superhires.png'); }
}
This way, each device type only loads the correct image resource. Also keep in mind that the px
unit in CSS always operates on logical pixels.
As more and more device types appear, it gets trickier to provide all of them with adequate bitmap resources. In CSS, media queries is currently the only way, and in HTML5, the picture element lets you use different sources for different media queries, but the support is still not 100 % since most web developers still have to support IE11 for a while more (source: caniuse).
If you need crisp images for icons, line-art, design elements that are not photos, you need to start thinking about SVG, which scales beautifully to all resolutions.
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
This doesn't work because NaN
isn't equal to anything, including NaN
. Use pd.isnull(df.var2)
instead.
You can directly assign a theme when you initiate the Builder:
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity(), R.style.MyAlertDialogTheme);
Then customize your theme in your values/styles.xml
<!-- Alert Dialog -->
<style name="MyAlertDialogTheme" parent="Theme.AppCompat.Dialog.Alert">
<item name="colorAccent">@color/colorAccent</item>
<item name="android:colorBackground">@color/alertDialogBackground</item>
<item name="android:windowBackground">@color/alertDialogBackground</item>
</style>
The answer you gave above works but it is confusing because you have used two names twice and you have an unnecessary line of code. you are doing a process that is not necessary.
it's a good idea when debugging code to get pen and paper and draw little boxes to represent memory spaces (i.e variables being stored) and then to draw arrows to indicate when a variable goes into a little box and when it comes out, if it gets overwritten or is a copy made etc.
if you do this with the code below you will see that
var selectBox = document.getElementById("selectBox");
gets put in a box and stays there you don't do anything with it afterwards.
and
var selectBox = document.getElementById("selectBox");
is hard to debug and is confusing when you have a select id of selectBox for the options list . ---- which selectBox do you want to manipulate / query / etc is it the local var selectBox that will disappear or is it the selectBox id you have assigned to the select tag
your code works until you add to it or modify it then you can easily loose track and get all mixed up
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
a leaner way that works also is:
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
and it's a good idea to use descriptive names that match the program and task you are working on am currently writing a similar program to accept and process postcodes using your code and modifying it with descriptive names the object is to make computer language as close to natural language as possible.
<script type="text/javascript">
function Mapit(){
var actualPostcode=getPostcodes.options[getPostcodes.selectedIndex].value;
alert(actualPostcode);
// alert is for debugging only next we go on to process and do something
// in this developing program it will placing markers on a map
}
</script>
<select id="getPostcodes" onchange="Mapit();">
<option>London North Inner</option>
<option>N1</option>
<option>London North Outer</option>
<option>N2</option>
<option>N3</option>
<option>N4</option>
// a lot more options follow
// with text in options to divide into areas and nothing will happen
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes
</select>
You don't need to download any new software. You can use Octave Online to open .m files.
I know this question is old, but it has been causing a lot of confusion for many reactjs users for a long time, including me.
Recently Dan Abramov (from the react team) just wrote up a great explanation as to why the nature of setState
is async:
https://github.com/facebook/react/issues/11527#issuecomment-360199710
setState
is meant to be asynchronous, and there are a few really good reasons for that in the linked explanation by Dan Abramov. This doesn't mean it will always be asynchronous - it mainly means that you just can't depend on it being synchronous. ReactJS takes into consideration many variables in the scenario that you're changing the state in, to decide when the state
should actually be updated and your component rerendered.
A simple example to demonstrate this, is that if you call setState
as a reaction to a user action, then the state
will probably be updated immediately (although, again, you can't count on it), so the user won't feel any delay, but if you call setState
in reaction to an ajax call response or some other event that isn't triggered by the user, then the state might be updated with a slight delay, since the user won't really feel this delay, and it will improve performance by waiting to batch multiple state updates together and rerender the DOM fewer times.
That should be possible using Socket.IO-client: https://github.com/LearnBoost/socket.io-client
So another way, which I prefer, is to just split the values, for example:
#/path/to/config.cfg
[Numbers]
first_row = 1,2,4,8,12,24,36,48
Could be loaded like this into a list of strings or integers, as follows:
import configparser
config = configparser.ConfigParser()
config.read('/path/to/config.cfg')
# Load into a list of strings
first_row_strings = config.get('Numbers', 'first_row').split(',')
# Load into a list of integers
first_row_integers = [int(x) for x in config.get('Numbers', 'first_row').split(',')]
This method prevents you from needing to wrap your values in brackets to load as JSON.
If you want to get the path of the workbook from where the macro is being executed - use Application.ThisWorkbook.Path
.
Application.ActiveWorkbook.Path
can sometimes produce unexpected results (e.g. if your macro switches between multiple workbooks).
Using the client manager affects all connections or sets a client machine specific alias.
Use the comma as above: this can be used in an app.config too
It's probably needed if you have firewalls between you and the server too...
Something that is frustrating is that when you are developing in Eclipse MyClass.class.getProtectionDomain().getCodeSource().getLocation()
returns the /bin
directory which is great, but when you compile it to a jar, the path includes the /myjarname.jar
part which gives you illegal file names.
To have the code work both in the ide and once it is compiled to a jar, I use the following piece of code:
URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
File applicationRootPath = new File(applicationRootPathURL.getPath());
File myFile;
if(applicationRootPath.isDirectory()){
myFile = new File(applicationRootPath, "filename");
}
else{
myFile = new File(applicationRootPath.getParentFile(), "filename");
}
Bootstrap 4.0 gives an option to modify modal data using jquery: https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content
Here is the script tag on the docs :
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
It works for the most part. Only call to modal was not working. Here is a modification on the script that works for me:
$(document).on('show.bs.modal', '#exampleModal',function(event){
... // same as in above script
})
Alternatively to a redirect, if it is calling your own code, you could use this:
actionContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Home", action = "Error" })
);
actionContext.Result.ExecuteResult(actionContext.Controller.ControllerContext);
It is not a pure redirect but gives a similar result without unnecessary overhead.
Floating hint EditText:
Add below dependency in gradle:
compile 'com.android.support:design:22.2.0'
In layout:
<android.support.design.widget.TextInputLayout
android:id="@+id/text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="UserName"/>
</android.support.design.widget.TextInputLayout>
Everyone seems to have missed the existence of the very useful YUV color space which was designed to represent perceived color differences in the human visual system. Distances in YUV represent differences in human perception. I needed this functionality for MagicCube4D which implements 4-dimensional Rubik's cubes and an unlimited numbers of other 4D twisty puzzles having arbitrary numbers of faces.
My solution starts by selecting random points in YUV and then iteratively breaking up the closest two points, and only converting to RGB when returning the result. The method is O(n^3) but that doesn't matter for small numbers or ones that can be cached. It can certainly be made more efficient but the results appear to be excellent.
The function allows for optional specification of brightness thresholds so as not to produce colors in which no component is brighter or darker than given amounts. IE you may not want values close to black or white. This is useful when the resulting colors will be used as base colors that are later shaded via lighting, layering, transparency, etc. and must still appear different from their base colors.
import java.awt.Color;
import java.util.Random;
/**
* Contains a method to generate N visually distinct colors and helper methods.
*
* @author Melinda Green
*/
public class ColorUtils {
private ColorUtils() {} // To disallow instantiation.
private final static float
U_OFF = .436f,
V_OFF = .615f;
private static final long RAND_SEED = 0;
private static Random rand = new Random(RAND_SEED);
/*
* Returns an array of ncolors RGB triplets such that each is as unique from the rest as possible
* and each color has at least one component greater than minComponent and one less than maxComponent.
* Use min == 1 and max == 0 to include the full RGB color range.
*
* Warning: O N^2 algorithm blows up fast for more than 100 colors.
*/
public static Color[] generateVisuallyDistinctColors(int ncolors, float minComponent, float maxComponent) {
rand.setSeed(RAND_SEED); // So that we get consistent results for each combination of inputs
float[][] yuv = new float[ncolors][3];
// initialize array with random colors
for(int got = 0; got < ncolors;) {
System.arraycopy(randYUVinRGBRange(minComponent, maxComponent), 0, yuv[got++], 0, 3);
}
// continually break up the worst-fit color pair until we get tired of searching
for(int c = 0; c < ncolors * 1000; c++) {
float worst = 8888;
int worstID = 0;
for(int i = 1; i < yuv.length; i++) {
for(int j = 0; j < i; j++) {
float dist = sqrdist(yuv[i], yuv[j]);
if(dist < worst) {
worst = dist;
worstID = i;
}
}
}
float[] best = randYUVBetterThan(worst, minComponent, maxComponent, yuv);
if(best == null)
break;
else
yuv[worstID] = best;
}
Color[] rgbs = new Color[yuv.length];
for(int i = 0; i < yuv.length; i++) {
float[] rgb = new float[3];
yuv2rgb(yuv[i][0], yuv[i][1], yuv[i][2], rgb);
rgbs[i] = new Color(rgb[0], rgb[1], rgb[2]);
//System.out.println(rgb[i][0] + "\t" + rgb[i][1] + "\t" + rgb[i][2]);
}
return rgbs;
}
public static void hsv2rgb(float h, float s, float v, float[] rgb) {
// H is given on [0->6] or -1. S and V are given on [0->1].
// RGB are each returned on [0->1].
float m, n, f;
int i;
float[] hsv = new float[3];
hsv[0] = h;
hsv[1] = s;
hsv[2] = v;
System.out.println("H: " + h + " S: " + s + " V:" + v);
if(hsv[0] == -1) {
rgb[0] = rgb[1] = rgb[2] = hsv[2];
return;
}
i = (int) (Math.floor(hsv[0]));
f = hsv[0] - i;
if(i % 2 == 0)
f = 1 - f; // if i is even
m = hsv[2] * (1 - hsv[1]);
n = hsv[2] * (1 - hsv[1] * f);
switch(i) {
case 6:
case 0:
rgb[0] = hsv[2];
rgb[1] = n;
rgb[2] = m;
break;
case 1:
rgb[0] = n;
rgb[1] = hsv[2];
rgb[2] = m;
break;
case 2:
rgb[0] = m;
rgb[1] = hsv[2];
rgb[2] = n;
break;
case 3:
rgb[0] = m;
rgb[1] = n;
rgb[2] = hsv[2];
break;
case 4:
rgb[0] = n;
rgb[1] = m;
rgb[2] = hsv[2];
break;
case 5:
rgb[0] = hsv[2];
rgb[1] = m;
rgb[2] = n;
break;
}
}
// From http://en.wikipedia.org/wiki/YUV#Mathematical_derivations_and_formulas
public static void yuv2rgb(float y, float u, float v, float[] rgb) {
rgb[0] = 1 * y + 0 * u + 1.13983f * v;
rgb[1] = 1 * y + -.39465f * u + -.58060f * v;
rgb[2] = 1 * y + 2.03211f * u + 0 * v;
}
public static void rgb2yuv(float r, float g, float b, float[] yuv) {
yuv[0] = .299f * r + .587f * g + .114f * b;
yuv[1] = -.14713f * r + -.28886f * g + .436f * b;
yuv[2] = .615f * r + -.51499f * g + -.10001f * b;
}
private static float[] randYUVinRGBRange(float minComponent, float maxComponent) {
while(true) {
float y = rand.nextFloat(); // * YFRAC + 1-YFRAC);
float u = rand.nextFloat() * 2 * U_OFF - U_OFF;
float v = rand.nextFloat() * 2 * V_OFF - V_OFF;
float[] rgb = new float[3];
yuv2rgb(y, u, v, rgb);
float r = rgb[0], g = rgb[1], b = rgb[2];
if(0 <= r && r <= 1 &&
0 <= g && g <= 1 &&
0 <= b && b <= 1 &&
(r > minComponent || g > minComponent || b > minComponent) && // don't want all dark components
(r < maxComponent || g < maxComponent || b < maxComponent)) // don't want all light components
return new float[]{y, u, v};
}
}
private static float sqrdist(float[] a, float[] b) {
float sum = 0;
for(int i = 0; i < a.length; i++) {
float diff = a[i] - b[i];
sum += diff * diff;
}
return sum;
}
private static double worstFit(Color[] colors) {
float worst = 8888;
float[] a = new float[3], b = new float[3];
for(int i = 1; i < colors.length; i++) {
colors[i].getColorComponents(a);
for(int j = 0; j < i; j++) {
colors[j].getColorComponents(b);
float dist = sqrdist(a, b);
if(dist < worst) {
worst = dist;
}
}
}
return Math.sqrt(worst);
}
private static float[] randYUVBetterThan(float bestDistSqrd, float minComponent, float maxComponent, float[][] in) {
for(int attempt = 1; attempt < 100 * in.length; attempt++) {
float[] candidate = randYUVinRGBRange(minComponent, maxComponent);
boolean good = true;
for(int i = 0; i < in.length; i++)
if(sqrdist(candidate, in[i]) < bestDistSqrd)
good = false;
if(good)
return candidate;
}
return null; // after a bunch of passes, couldn't find a candidate that beat the best.
}
/**
* Simple example program.
*/
public static void main(String[] args) {
final int ncolors = 10;
Color[] colors = generateVisuallyDistinctColors(ncolors, .8f, .3f);
for(int i = 0; i < colors.length; i++) {
System.out.println(colors[i].toString());
}
System.out.println("Worst fit color = " + worstFit(colors));
}
}
html {
overflow-y: scroll;
}
Is that what you want?
Unfortunately, Opera 9.64 seems to ignore that CSS declaration when applied to HTML
or BODY
, although it works for other block-level elements like DIV
.
LocalDate.parse( "2015-01-02" )
Java 8 and later has a new java.time framework that makes these other answers outmoded. This framework is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See the Tutorial.
The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them.
LocalDate
Like Joda-Time, java.time has a class LocalDate
to represent a date-only value without time-of-day and without time zone.
If your input string is in the standard ISO 8601 format of yyyy-MM-dd
, you can ask that class to directly parse the string with no need to specify a formatter.
The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values.
LocalDate localDate = LocalDate.parse( "2015-01-02" );
If you have a different format, specify a formatter from the java.time.format package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a Locale
specifying a human language for translation and cultural norms for deciding issues such as period versus comma.
Read the DateTimeFormatter
class doc for details on the codes used in the format pattern. They vary a bit from the old outmoded java.text.SimpleDateFormat
class patterns.
Note how the second argument to the parse
method is a method reference, syntax added to Java 8 and later.
String input = "January 2, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "MMMM d, yyyy" , Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );
Dump to console.
System.out.println ( "localDate: " + localDate );
localDate: 2015-01-02
Or rather than specify a formatting pattern, let java.time localize for you. Call DateTimeFormatter.ofLocalizedDate
, and be sure to specify the desired/expected Locale
rather than rely on the JVM’s current default which can change at any moment during runtime(!).
String input = "January 2, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG );
formatter = formatter.withLocale ( Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );
Dump to console.
System.out.println ( "input: " + input + " | localDate: " + localDate );
input: January 2, 2015 | localDate: 2015-01-02
Just use an <a>
by itself, set it to display: block;
and set width
and height
. Get rid of the <span>
and <div>
. This is the semantic way to do it. There is no need to wrap things in <divs>
(or any element) for layout. That is what CSS is for.
Demo: http://jsfiddle.net/ThinkingStiff/89Enq/
HTML:
<a id="music" href="Music.html">Music I Like</a>
CSS:
#music {
background-color: black;
color: white;
display: block;
height: 40px;
line-height: 40px;
text-decoration: none;
width: 100px;
text-align: center;
}
Output:
function CheckValidAmount() {
var amounttext = document.getElementById('txtRemittanceNumber').value;
if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
alert('Please enter only numbers into amount textbox.')
document.getElementById('txtRemittanceNumber').value = "10.00";
}
}
This is the function which will take decimal number with any number of decimal places and without any decimal places.
Thanks ... :)
Yeah. Just use binary serialization. You have to have each object use implements Serializable
but it's straightforward from there.
Your other option, if you want to avoid implementing the Serializable interface, is to use reflection and read and write data to/from a buffer using a process this one below:
/**
* Sets all int fields in an object to 0.
*
* @param obj The object to operate on.
*
* @throws RuntimeException If there is a reflection problem.
*/
public static void initPublicIntFields(final Object obj) {
try {
Field[] fields = obj.getClass().getFields();
for (int idx = 0; idx < fields.length; idx++) {
if (fields[idx].getType() == int.class) {
fields[idx].setInt(obj, 0);
}
}
} catch (final IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
use this below code :
int index,top;
@Override
protected void onPause() {
super.onPause();
index = mList.getFirstVisiblePosition();
View v = challengeList.getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
}
and whenever your refresh your data use this below code :
adapter.notifyDataSetChanged();
mList.setSelectionFromTop(index, top);
Here is the code
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .ok{_x000D_
display : none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div>_x000D_
<div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
h1 {
font-weight: bold;
color: #fff;
font-size: 32px;
}
h2 {
font-weight: bold;
color: #fff;
font-size: 24px;
}
Note that after color you can use a word (e.g. white
), a hex code (e.g. #fff
) or RGB (e.g. rgb(255,255,255)
) or RGBA (e.g. rgba(255,255,255,0.3)
).
As far as I understand getters and setters are to improve encapsulation. There is nothing complex about them in C#.
You define a property of on object like this:
int m_colorValue = 0;
public int Color
{
set { m_colorValue = value; }
get { return m_colorValue; }
}
This is the most simple use. It basically sets an internal variable or retrieves its value. You use a Property like this:
someObject.Color = 222; // sets a color 222
int color = someObject.Color // gets the color of the object
You could eventually do some processing on the value in the setters or getters like this:
public int Color
{
set { m_colorValue = value + 5; }
get { return m_colorValue - 30; }
}
if you skip set or get, your property will be read or write only. That's how I understand the stuff.
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
I typically return null. It provides a quick and easy mechanism to detect if something screwed up without throwing exceptions and using tons of try/catch all over the place.
I think this will be simple and fast -
var scrollWidth= window.innerWidth-$(document).width()
In your menu folder make a .menu xml file and add this xml
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="@string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView" />
In your fragment class overide this method and
implement SearchView.OnQueryTextListener in your fragment class
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
}
Now just setup your menu xml file in fragment class
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView)
MenuItemCompat.getActionView(item);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
The project I'm working on, we do something like this. We use the errorlevel
keyword so it kind of looks like:
call myExe.exe
if errorlevel 1 (
goto build_fail
)
That seems to work for us. Note that you can put in multiple commands in the parens like an echo or whatever. Also note that build_fail is defined as:
:build_fail
echo ********** BUILD FAILURE **********
exit /b 1
Using 2.7:
from functools import partial
from random import randint
for roll in iter(partial(randint, 1, 8), 1):
print 'you rolled: {}'.format(roll)
print 'oops you rolled a 1!'
you rolled: 7
you rolled: 7
you rolled: 8
you rolled: 6
you rolled: 8
you rolled: 5
oops you rolled a 1!
Then change the "oops" print to a raise SystemExit
Use sort -n
or sort --numeric-sort
.
Python documentation for sys.exit([arg])says:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise.
Moreover to retrieve the return value of the last executed program you could use the $? bash predefined variable.
Anyway if you put a string as arg in sys.exit() it should be printed at the end of your program output in a separate line, so that you can retrieve it just with a little bit of parsing. As an example consider this:
outputString=`python myPythonScript arg1 arg2 arg3 | tail -0`
I think this might help...
In order to break down user inputted dates (mm/dd/yyyy) in my scripts, I store the day, month, and year into an array, and then put the values into separate variables as follows:
DATE_ARRAY=(`echo $2 | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
PHP has a built in function called bool chmod(string $filename, int $mode )
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
chmod($file, 0777); //changed to add the zero
return true;
}
I'm giving this example because this actually work for my use case.
I was trying to use the AWS Rekognition API. The API returns a BoundingBox object:
BoundingBox boundingBox = faceDetail.getBoundingBox();
The code below uses it to crop the image:
import com.amazonaws.services.rekognition.model.BoundingBox;
private BufferedImage cropImage(BufferedImage image, BoundingBox box) {
Rectangle goal = new Rectangle(Math.round(box.getLeft()* image.getWidth()),Math.round(box.getTop()* image.getHeight()),Math.round(box.getWidth() * image.getWidth()), Math.round(box.getHeight() * image.getHeight()));
Rectangle clip = goal.intersection(new Rectangle(image.getWidth(), image.getHeight()));
BufferedImage clippedImg = image.getSubimage(clip.x, clip.y , clip.width, clip.height);
return clippedImg;
}
Write-Host "filesizecounter : " $filesizecounter
What is a smart pointer.
Long version, In principle:
https://web.stanford.edu/class/archive/cs/cs106l/cs106l.1192/lectures/lecture15/15_RAII.pdf
A modern C++ idiom:
RAII: Resource Acquisition Is Initialization.
? When you initialize an object, it should already have
acquired any resources it needs (in the constructor).
? When an object goes out of scope, it should release every
resource it is using (using the destructor).
key point:
? There should never be a half-ready or half-dead object.
? When an object is created, it should be in a ready state.
? When an object goes out of scope, it should release its resources.
? The user shouldn’t have to do anything more.
Raw Pointers violate RAII: It need user to delete manually when the pointers go out of scope.
RAII solution is:
Have a smart pointer class:
? Allocates the memory when initialized
? Frees the memory when destructor is called
? Allows access to underlying pointer
For smart pointer need copy and share, use shared_ptr:
? use another memory to store Reference counting and shared.
? increment when copy, decrement when destructor.
? delete memory when Reference counting is 0.
also delete memory that store Reference counting.
for smart pointer not own the raw pointer, use weak_ptr:
? not change Reference counting.
shared_ptr usage:
correct way:
std::shared_ptr<T> t1 = std::make_shared<T>(TArgs);
std::shared_ptr<T> t2 = std::shared_ptr<T>(new T(Targs));
wrong way:
T* pt = new T(TArgs); // never exposure the raw pointer
shared_ptr<T> t1 = shared_ptr<T>(pt);
shared_ptr<T> t2 = shared_ptr<T>(pt);
Always avoid using raw pointer.
For scenario that have to use raw pointer:
https://stackoverflow.com/a/19432062/2482283
For raw pointer that not nullptr, use reference instead.
not use T*
use T&
For optional reference which maybe nullptr, use raw pointer, and which means:
T* pt; is optional reference and maybe nullptr.
Not own the raw pointer,
Raw pointer is managed by some one else.
I only know that the caller is sure it is not released now.
You could try my Linked Tree Map implementation.
In bootstrap 4, you can add a .text-truncate
class to truncate the text with an ellipsis.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Inline level -->_x000D_
<span class="d-inline-block text-truncate" style="max-width: 190px;">_x000D_
I like big butts and I cannot lie_x000D_
</span>
_x000D_
While this isn't exactly specific to jQuery selectors/objects, in FireFox Quantum 58.x, you can find event handlers on an element using the Dev tools:
In LINQ2SQL you seldom need to join explicitly when using inner joins.
If you have proper foreign key relationships in your database you will automatically get a relation in the LINQ designer (if not you can create a relation manually in the designer, although you should really have proper relations in your database)
Then you can just access related tables with the "dot-notation"
var q = from child in context.Childs
where child.Parent.col2 == 4
select new
{
childCol1 = child.col1,
parentCol1 = child.Parent.col1,
};
will generate the query
SELECT [t0].[col1] AS [childCol1], [t1].[col1] AS [parentCol1]
FROM [dbo].[Child] AS [t0]
INNER JOIN [dbo].[Parent] AS [t1] ON ([t1].[col1] = [t0].[col1]) AND ([t1].[col2] = [t0].[col2])
WHERE [t1].[col2] = @p0
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [4]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
In my opinion this is much more readable and lets you concentrate on your special conditions and not the actual mechanics of the join.
Edit
This is of course only applicable when you want to join in the line with our database model. If you want to join "outside the model" you need to resort to manual joins as in the answer from Quintin Robinson
It's important to note that the order of parameters is actually important to spring. The BindingResult needs to come right after the Form that is being validated. Likewise, the [optional] Model parameter needs to come after the BindingResult. Example:
Valid:
@RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
final BindingResult bindingResult,
@RequestParam("pk") final long pk,
final Model model) {
}
Not Valid:
RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
@RequestParam("pk") final long pk,
final BindingResult bindingResult,
final Model model) {
}
Why make it so complicated? You can use this instead:
import UIKit
let PI = 3.14159265359
round( PI ) // 3.0 rounded to the nearest decimal
round( PI * 100 ) / 100 //3.14 rounded to the nearest hundredth
round( PI * 1000 ) / 1000 // 3.142 rounded to the nearest thousandth
See it work in Playground.
PS: Solution from: http://rrike.sh/xcode/rounding-various-decimal-places-swift/
I had a large enumerated type I wanted to convert it into an NSDictionary
lookup. I ended up using sed
from OSX terminal as:
$ sed -E 's/^[[:space:]]{1,}([[:alnum:]]{1,}).*$/ @(\1) : @"\1",/g' ObservationType.h
which can be read as: 'capture the first word on the line and output @(word) : @"word",'
This regex converts the enum in a header file named 'ObservationType.h' which contains:
typedef enum : int {
ObservationTypePulse = 1,
ObservationTypeRespRate = 2,
ObservationTypeTemperature = 3,
.
.
}
into something like:
@(ObservationTypePulse) : @"ObservationTypePulse",
@(ObservationTypeRespRate) : @"ObservationTypeRespRate",
@(ObservationTypeTemperature) : @"ObservationTypeTemperature",
.
.
which can then be wrapped in a method using modern objective-c syntax @{ }
(as explained by @yar1vn above) to create a NSDictionary
lookup :
-(NSDictionary *)observationDictionary
{
static NSDictionary *observationDictionary;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
observationDictionary = [[NSDictionary alloc] initWithDictionary:@{
@(ObservationTypePulse) : @"ObservationTypePulse",
@(ObservationTypeRespRate) : @"ObservationTypeRespRate",
.
.
}];
});
return observationDictionary;
}
The dispatch_once
boiler-plate is just to ensure that the static variable is initialised in a thread-safe manner.
Note: I found the sed regex expression on OSX odd - when I tried to use +
to match 'one or more' it didn't work and had to resort to using {1,}
as a replacement
You can use script like this for mac:
for f in $(curl -s -l -u user:pass ftp://your_ftp_server_ip/folder/)
do curl -O -u user:pass ftp://your_ftp_server_ip/folder/$f
done
Use LISTAGG function,
ex. SELECT LISTAGG(colmn) FROM table_name;
SELECT to_char(to_date(month,'yyyy-mm'),'Mon yyyy'), nos
FROM (SELECT to_char(credit_date,'yyyy-mm') MONTH,count(*) nos
FROM HCN
WHERE TRUNC(CREDIT_dATE) BEtween '01-jul-2014' AND '30-JUN-2015'
AND CATEGORYCODECFR=22
--AND CREDIT_NOTE_NO IS NOT NULL
AND CANCELDATE IS NULL
GROUP BY to_char(credit_date,'yyyy-mm')
ORDER BY to_char(credit_date,'yyyy-mm') ) mm
Output:
Jul 2014 49
Aug 2014 35
Sep 2014 57
Oct 2014 50
Nov 2014 45
Dec 2014 88
Jan 2015 131
Feb 2015 112
Mar 2015 76
Apr 2015 45
May 2015 49
Jun 2015 40
The idea of os.path.join()
is to make your program cross-platform (linux/windows/etc).
Even one slash ruins it.
So it only makes sense when being used with some kind of a reference point like
os.environ['HOME']
or os.path.dirname(__file__)
.
You can change the comment character to something besides # like this:
git config --global core.commentchar "@"
To list the Docker images
$ docker images
If your application wants to run in with port 80, and you can expose a different port to bind locally, say 8080:
$ docker run -d --restart=always -p 8080:80 image_name:version
I know that this is a very old post but just wanted to say that using flexbox on a parent element would disable margin collapsing for its child elements.
Working Example here - add /edit to the URL to play with the code
You just need to use JavaScript setInterval
function
$('html').addClass('js');_x000D_
_x000D_
$(function() {_x000D_
_x000D_
var timer = setInterval(showDiv, 5000);_x000D_
_x000D_
var counter = 0;_x000D_
_x000D_
function showDiv() {_x000D_
if (counter == 0) {_x000D_
counter++;_x000D_
return;_x000D_
}_x000D_
_x000D_
$('div', '#container')_x000D_
.stop()_x000D_
.hide()_x000D_
.filter(function() {_x000D_
return this.id.match('div' + counter);_x000D_
})_x000D_
.show('fast');_x000D_
counter == 3 ? counter = 0 : counter++;_x000D_
_x000D_
}_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<title>Sandbox</title>_x000D_
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />_x000D_
<style type="text/css" media="screen">_x000D_
body {_x000D_
background-color: #fff;_x000D_
font: 16px Helvetica, Arial;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.display {_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
border: 2px solid #000;_x000D_
}_x000D_
_x000D_
.js .display {_x000D_
display: none;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h2>Example of using setInterval to trigger display of Div</h2>_x000D_
<p>The first div will display after 10 seconds...</p>_x000D_
<div id='container'>_x000D_
<div id='div1' class='display' style="background-color: red;">_x000D_
div1_x000D_
</div>_x000D_
<div id='div2' class='display' style="background-color: green;">_x000D_
div2_x000D_
</div>_x000D_
<div id='div3' class='display' style="background-color: blue;">_x000D_
div3_x000D_
</div>_x000D_
<div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
EDIT:
In response to your comment about the container div, just modify this
$('div','#container')
to this
$('#div1, #div2, #div3')
-http-proxy can be set in eclipse this way:
You could use below gem to find the records between dates,
This gem quite easy to use and more clear By star am using this gem and the API more clear and documentation also well explained.
Post.between_times(Time.zone.now - 3.hours, # all posts in last 3 hours
Time.zone.now)
Here you could pass our field also Post.by_month("January", field: :updated_at)
Please see the documentation and try it.
user.no_of_logins += 1
session.commit()
You can read more about the generic concept of "loose coupling".
In short, it's a description of a relationship between two classes, where each class knows the very least about the other and each class could potentially continue to work just fine whether the other is present or not and without dependency on the particular implementation of the other class.
For me it was because I hadn't set an active
class on any of the slides.
If I am correct H2 is from the same guys who wrote HSQLDB. Its a lot better if you trust the benchmarks on their site. Also, there is some notion that sun community jumped too quickly into Derby.
I had this error occur for a different reason.
I created a template for save/cancel buttons that I wanted to appear at top and bottom of the page. It worked at first when I had my template defined inside of a <script type="text/html"> element.... but then I heard you could optionally create a template out of an ordinary DIV element instead.
(This worked better for me since I was using ASP.NET MVC and none of my @variableName Razor syntax was being executed at runtime from inside of the script element. So by changing to a DIV instead, I could still have the MVC Razor engine generate HTML inside my KnockoutJs template when the page loads.)
After I changed my template to use a DIV instead of a SCRIPT element, my code looked like this.... which worked fine on IE10. However, later when I tested it on IE8, it threw that....
"You cannot apply bindings multiple times to the same element" error.....
HTML
<div id="mainKnockoutDiv" class="measurementsDivContents hourlyMeasurements">
<div id="saveButtons_template" style="display: none;">
... my template content here ...
</div>
<!--ko template: { name: 'saveButtons_template' } -->
<!--/ko-->
Some_HTML_content_here....
<!--ko template: { name: 'saveButtons_template' } -->
<!--/ko-->
</div>
JavaScript
ko.applyBindings(viewModel, document.getElementById('mainKnockoutDiv'));
THE SOLUTION:
All I had to do was move my saveButtons_template DIV down to the bottom, so that it was outside of the mainKnockoutDiv. This solved the problem for me.
I suppose KnockoutJs was trying to bind my template DIV multiple times since it was located inside the applyBindings target area... and was not using the SCRIPT element.... and was being referenced as a template.
System.out.println(isLeapYear);
should work just fine.
Incidentally, in
else if ((year % 4 == 0) && (year % 100 == 0)) isLeapYear = false; else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)) isLeapYear = true;
the year % 400
part will never be reached because if (year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)
is true, then (year % 4 == 0) && (year % 100 == 0)
must have succeeded.
Maybe swap those two conditions or refactor them:
else if ((year % 4 == 0) && (year % 100 == 0))
isLeapYear = (year % 400 == 0);
Firstly run this query
SHOW VARIABLES LIKE '%char%';
You have character_set_server='latin1'
If so,go into your config file,my.cnf and add or uncomment these lines:
character-set-server = utf8
collation-server = utf8_unicode_ci
Restart the server. Yes late to the party,just encountered the same issue.
I have found this parameter -u with read.
"-u 1" means "read from stdin"
while read -r newline; do
((i++))
read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)
You could try this approach:
Get the current date.
Add the the number of years which is equal to the difference between the current date's year and the specified year.
Subtract the number of days that is the last obtained date's week day's number (and it will give us the last day of some week).
Add the number of weeks which is the difference between the last obtained date's week number and the specified week number, and that will yield the last day of the desired week.
Subtract 6 days to obtain the first day.
If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.
What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.
In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:
Front end code:
<div onclick="showHideModal();">
<asp:Calendar
OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server"
BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana"
Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%">
<OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle>
<DayHeaderStyle ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
<TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle>
<DayStyle BackColor="White"> </DayStyle>
<SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle>
</asp:Calendar>
</div>
Codebehind:
protected void DatepickerDateChange(object sender, EventArgs e)
{
if (toFromPicked.Value == "MainContent_fromDate")
{
fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
}
else
{
toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
}
}
By default, a grid item cannot be smaller than the size of its content.
Grid items have an initial size of min-width: auto
and min-height: auto
.
You can override this behavior by setting grid items to min-width: 0
, min-height: 0
or overflow
with any value other than visible
.
From the spec:
6.6. Automatic Minimum Size of Grid Items
To provide a more reasonable default minimum size for grid items, this specification defines that the
auto
value ofmin-width
/min-height
also applies an automatic minimum size in the specified axis to grid items whoseoverflow
isvisible
. (The effect is analogous to the automatic minimum size imposed on flex items.)
Here's a more detailed explanation covering flex items, but it applies to grid items, as well:
This post also covers potential problems with nested containers and known rendering differences among major browsers.
To fix your layout, make these adjustments to your code:
.month-grid {
display: grid;
grid-template: repeat(6, 1fr) / repeat(7, 1fr);
background: #fff;
grid-gap: 2px;
min-height: 0; /* NEW */
min-width: 0; /* NEW; needed for Firefox */
}
.day-item {
padding: 10px;
background: #DFE7E7;
overflow: hidden; /* NEW */
min-width: 0; /* NEW; needed for Firefox */
}
1fr
vs minmax(0, 1fr)
The solution above operates at the grid item level. For a container level solution, see this post:
To Whom, deailing with share hosting environment and still chance to have Current PHP less than 7.0 Who does not have dirname( __FILE__, 2 );
it is possible to use following.
function dirname_safe($path, $level = 0){
$dir = explode(DIRECTORY_SEPARATOR, $path);
$level = $level * -1;
if($level == 0) $level = count($dir);
array_splice($dir, $level);
return implode($dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}
print_r(dirname_safe(__DIR__, 2));
I would go with something like this JSFiddle:
HTML:
<a class="green" href="#">green text</a>
<a class="yellow" href="#">yellow text</a>
CSS:
body { background: #ccc }
/* Green */
a.green,
a.green:hover { color: green; }
/* Yellow */
a.yellow,
a.yellow:hover { color: yellow; }
Have you added the dll into your project references list? If not right click on the project "References" folder and selecet "Add Reference" then use browse to locate your science.dll, select it and click ok.
edit
I can't see the image of your VS instance that some people are referring to and I note that you now say that it works in Net4.0 and VS2010.
VS2008 projects support NET 3.5 by default. I expect that is the problem as your DLL may be NET 4.0 compliant but not NET 3.5.
The following is a very easy way to see the maximum elements and its positions. Here axis
is the domain; axis
= 0 means column wise maximum number and axis
= 1 means row wise max number for the 2D case. And for higher dimensions it depends upon you.
M = np.random.random((3, 4))
print(M)
print(M.max(axis=1), M.argmax(axis=1))
I urge you to read this blog post that directly addresses your problem.
Using custom model binders isn't really wise as Phil Haack pointed out (his blog post is linked in the upper blog post as well).
Basically you have three options:
Write a JsonValueProviderFactory
and use a client side library like json2.js
to communicate wit JSON directly.
Write a JQueryValueProviderFactory
that understands the jQuery JSON object transformation that happens in $.ajax
or
Use the very simple and quick jQuery plugin outlined in the blog post, that prepares any JSON object (even arrays that will be bound to IList<T>
and dates that will correctly parse on the server side as DateTime
instances) that will be understood by Asp.net MVC default model binder.
Of all three, the last one is the simplest and doesn't interfere with Asp.net MVC inner workings thus lowering possible bug surface. Using this technique outlined in the blog post will correctly data bind your strong type action parameters and validate them as well. So it is basically a win win situation.
This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.
The code for the button click is below
private void button1_Click(object sender, EventArgs e)
{
New_Form new_Form = new New_Form();
new_Form.Show();
}
Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer
this.Load += new System.EventHandler(this.OnPageLoad);
This OnPageLoad function runs when that form is loaded
In NewForm.cs ,
public partial class New_Form : Form
{
private Timer formClosingTimer;
private void OnPageLoad(object sender, EventArgs e)
{
formClosingTimer = new Timer(); // Creating a new timer
formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
formClosingTimer.Interval = 2000; // Time Interval in miliseconds
formClosingTimer.Start(); // Starting a timer
}
private void CloseForm(object sender, EventArgs e)
{
formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
this.Close(); // Closing the current form
}
}
In this new form , a timer is used to invoke a method which closes that form.
Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.
For your knowledge,
form.close()
will free the memory and we can never interact with that form again
form.hide()
will just hide the form, where the code part can still run
For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2
'entityManager.unwrap(Session.class)' is used to get session from EntityManager.
@Repository
@Transactional
public class EmployeeRepository {
@PersistenceContext
private EntityManager entityManager;
public Session getSession() {
Session session = entityManager.unwrap(Session.class);
return session;
}
......
......
}
Demo Application link.
Make the outer loop a while loop, and "Exit While" in the if statement.
I've had the same issue today and I've not done any intermediate merges so from your opening post only #1 might apply - however i have made commits both from an svn client in ubuntu as well as tortoisesvn in windows. Luckily in my case no changes to the trunk were made so I could just replace the trunk with the branch. Possibly different svn versions then? That's quite worrying.
If you use the svn move / copy /delete functions though no history is lost in my case - i svn moved the trunk and then svn moved the branch to trunk.
you could use something like:
[^0-9]+([0-9]+)[^0-9]+([0-9]+).+
Then get the first and second capture groups.
sift
is a powerful collection filter for operations like this and much more advanced ones. It works client side in the browser or server side in node.js.
var collection = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
var sifted = sift({id: {$not: 88}}, collection);
It supports filters like $in
, $nin
, $exists
, $gte
, $gt
, $lte
, $lt
, $eq
, $ne
, $mod
, $all
, $and
, $or
, $nor
, $not
, $size
, $type
, and $regex
, and strives to be API-compatible with MongoDB collection filtering.
Install MSYS2, it has svn in its repository (besides lots of other Unix goodies). MSYS2 installs without Windows Admin rights.
$ pacman -S svn
The tools can be used from cmd, too:
C:\>C:\msys64\usr\bin\svn.exe co http://somehost/somerepo/
Here you go:
$(document).ready(function(){
$('#submenu li').hover(function(){
$('#carousel').css('background-position', '10px 10px');
}, function(){
$('#carousel').css('background-position', '');
});
});
In WPF MVVM terms, a POCO class is one that does not Fire PropertyChanged events
Check this useful method:
URLUtil.guessUrl(urlString)
It makes google.com -> http://google.com
In Visual Studio and most other half decent IDEs you can simply do SHIFT+TAB. It does the opposite of just TAB.
I would think and hope that the IDEs you mention support this as well.
Further to my comment against @JBall's answer that helped me along the way, this is the final answer that works for me. I'm using MVC and Razor and I'm submitting a form using jQuery AJAX so I can update a partial view with some new results and I didn't want to do a complete postback (and page flicker).
Add the @Html.AntiForgeryToken()
inside the form as usual.
My AJAX submission button code (i.e. an onclick event) is:
//User clicks the SUBMIT button
$("#btnSubmit").click(function (event) {
//prevent this button submitting the form as we will do that via AJAX
event.preventDefault();
//Validate the form first
if (!$('#searchForm').validate().form()) {
alert("Please correct the errors");
return false;
}
//Get the entire form's data - including the antiforgerytoken
var allFormData = $("#searchForm").serialize();
// The actual POST can now take place with a validated form
$.ajax({
type: "POST",
async: false,
url: "/Home/SearchAjax",
data: allFormData,
dataType: "html",
success: function (data) {
$('#gridView').html(data);
$('#TestGrid').jqGrid('setGridParam', { url: '@Url.Action("GetDetails", "Home", Model)', datatype: "json", page: 1 }).trigger('reloadGrid');
}
});
I've left the "success" action in as it shows how the partial view is being updated that contains an MvcJqGrid and how it's being refreshed (very powerful jqGrid grid and this is a brilliant MVC wrapper for it).
My controller method looks like this:
//Ajax SUBMIT method
[ValidateAntiForgeryToken]
public ActionResult SearchAjax(EstateOutlet_D model)
{
return View("_Grid", model);
}
I have to admit to not being a fan of POSTing an entire form's data as a Model but if you need to do it then this is one way that works. MVC just makes the data binding too easy so rather than subitting 16 individual values (or a weakly-typed FormCollection) this is OK, I guess. If you know better please let me know as I want to produce robust MVC C# code.
This one-liner works:
var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')
If you are using Git Extensions you should be able to find your local changes in the Working directory
as shown below:
If you don't see any changes, it's probably because you are on a wrong sub-module. So check all the items with a submarine icon as shown below:
When you found some uncommitted change:
Select the line with Working directory
, navigate to Diff tab, Right click on rows with a pencil (or +
or -
) icon, choose Reset to first commit or commit or stash or whatever you want to do with it.
Use WORKSPACE environment variable to change workspace directory.
If doing using Jenkinsfile, use following code :
dir("${env.WORKSPACE}/aQA"){
sh "pwd"
}
Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.
With moment you can parse the date string you have:
var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")
That's for UTC, you'll have to convert the time zone from that point if you so desire.
Then you can get the day of the week:
dt.format('dddd');
Generally, you can use any state handling approach you want to trigger an update.
const forceUpdate: () => void = React.useState()[1].bind(null, {}) // see NOTE below
const forceUpdate = React.useReducer(() => ({}), {})[1] as () => void
Just wrap whatever approach you prefer like this
function useForceUpdate(): () => void {
return React.useReducer(() => ({}), {})[1] as () => void // <- paste here
}
"To trigger an update" means to tell React engine that some value has changed and that it should rerender your component.
[, setState]
from useState()
requires a parameter. We get rid of it by binding a fresh object {}
.
() => ({})
in useReducer
is a dummy reducer that returns a fresh object each time an action is dispatched.
{}
(fresh object) is required so that it triggers an update by changing a reference in the state.
PS: useState
just wraps useReducer
internally. source
NOTE: Using .bind with useState causes a change in function reference between renders. It is possible to wrap it inside useCallback as already explained here, but then it wouldn't be a sexy one-liner™. The Reducer version already keeps reference equality between renders. This is important if you want to pass the forceUpdate function in props.
const forceUpdate = React.useState()[1].bind(null, {}) // see NOTE above
const forceUpdate = React.useReducer(() => ({}))[1]
I came here because the Remove button was not available from Add/Remove programs. It was saying "Node.js cannot be removed".
This worked:
msiexec /uninstall <node.msi>
.str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"
Apart from a bare except:
clause (which as others have said you shouldn't use), you can simply catch Exception
:
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# Logs the error appropriately.
You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.
The advantage of except Exception
over the bare except
is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt
and SystemExit
: if you caught and swallowed those then you could make it hard for anyone to exit your script.
In my case, instead of using Button, I use androidx.appcompat.widget.AppCompatButton and it worked for me.
You're looking for case
:
case when action = 2 and state = 0 then 1 else 0 end as state
MySQL has an if
syntax (if(action=2 and state=0, 1, 0)
), but case
is more universal.
Note that the as state
there is just aliasing the column. I'm assuming this is in the column list of your SQL query.
Most of the answers above are either deprecated or the zoom works by retaining the current latitude and longitude and does not zoom to the exact location you want it to. Add the following code to your onMapReady() method.
@Override
public void onMapReady(GoogleMap googleMap) {
//Set marker on the map
googleMap.addMarker(new MarkerOptions().position(new LatLng(0.0000, 0.0000)).title("Marker"));
//Create a CameraUpdate variable to store the intended location and zoom of the camera
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(0.0000, 0.0000), 13);
//Animate the zoom using the animateCamera() method
googleMap.animateCamera(cameraUpdate);
}
Don't know if it's the best way but I'd do this:
=A1 & TEXT(A2,"mm/dd/yyyy")
That should format your date into your desired string.
Edit: That funny number you saw is the number of days between December 31st 1899 and your date. That's how Excel stores dates.
Use strstr(const char *s , const char *t)
and include<string.h>
You can write your own function which behaves same as strstr
and you can modify according to your requirement also
char * str_str(const char *s, const char *t)
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++)
{
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return (&s[i]);
}
return NULL;
}
Add following to your maven dependency
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
I always do OOP and use this class to maintain the session so u can use the function is_logged_in to check if the user is logged in or not, and if not you do what you wish to.
<?php
class Session
{
private $logged_in=false;
public $user_id;
function __construct() {
session_start();
$this->check_login();
if($this->logged_in) {
// actions to take right away if user is logged in
} else {
// actions to take right away if user is not logged in
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function login($user) {
// database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login() {
if(isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
?>
I have an extension method for Uri that:
uri.WithQuery(new { name = "value" })
string/string
pairs (e.g. Dictionary`2).string/object
pairs (e.g. RouteValueDictionary).The documented version can be found here.
The extension:
public static Uri WithQuery(this Uri uri, object values)
{
if (uri == null)
throw new ArgumentNullException(nameof(uri));
if (values != null)
{
var query = string.Join(
"&", from p in ParseQueryValues(values)
where !string.IsNullOrWhiteSpace(p.Key)
let k = HttpUtility.UrlEncode(p.Key.Trim())
let v = HttpUtility.UrlEncode(p.Value)
orderby k
select string.IsNullOrEmpty(v) ? k : $"{k}={v}");
if (query.Length != 0 || uri.Query.Length != 0)
uri = new UriBuilder(uri) { Query = query }.Uri;
}
return uri;
}
The query parser:
private static IEnumerable<KeyValuePair<string, string>> ParseQueryValues(object values)
{
// Check if a name/value collection.
var nvc = values as NameValueCollection;
if (nvc != null)
return from key in nvc.AllKeys
from val in nvc.GetValues(key)
select new KeyValuePair<string, string>(key, val);
// Check if a string/string dictionary.
var ssd = values as IEnumerable<KeyValuePair<string, string>>;
if (ssd != null)
return ssd;
// Check if a string/object dictionary.
var sod = values as IEnumerable<KeyValuePair<string, object>>;
if (sod == null)
{
// Check if a non-generic dictionary.
var ngd = values as IDictionary;
if (ngd != null)
sod = ngd.Cast<dynamic>().ToDictionary<dynamic, string, object>(
p => p.Key.ToString(), p => p.Value as object);
// Convert object properties to dictionary.
if (sod == null)
sod = new RouteValueDictionary(values);
}
// Normalize and return the values.
return from pair in sod
from val in pair.Value as IEnumerable<string>
?? new[] { pair.Value?.ToString() }
select new KeyValuePair<string, string>(pair.Key, val);
}
Here are the tests:
var uri = new Uri("https://stackoverflow.com/yo?oldKey=oldValue");
// Test with a string/string dictionary.
var q = uri.WithQuery(new Dictionary<string, string>
{
["k1"] = string.Empty,
["k2"] = null,
["k3"] = "v3"
});
Debug.Assert(q == new Uri(
"https://stackoverflow.com/yo?k1&k2&k3=v3"));
// Test with a string/object dictionary.
q = uri.WithQuery(new Dictionary<string, object>
{
["k1"] = "v1",
["k2"] = new[] { "v2a", "v2b" },
["k3"] = null
});
Debug.Assert(q == new Uri(
"https://stackoverflow.com/yo?k1=v1&k2=v2a&k2=v2b&k3"));
// Test with a name/value collection.
var nvc = new NameValueCollection()
{
["k1"] = string.Empty,
["k2"] = "v2a"
};
nvc.Add("k2", "v2b");
q = uri.WithQuery(nvc);
Debug.Assert(q == new Uri(
"https://stackoverflow.com/yo?k1&k2=v2a&k2=v2b"));
// Test with any dictionary.
q = uri.WithQuery(new Dictionary<int, HashSet<string>>
{
[1] = new HashSet<string> { "v1" },
[2] = new HashSet<string> { "v2a", "v2b" },
[3] = null
});
Debug.Assert(q == new Uri(
"https://stackoverflow.com/yo?1=v1&2=v2a&2=v2b&3"));
// Test with an anonymous object.
q = uri.WithQuery(new
{
k1 = "v1",
k2 = new[] { "v2a", "v2b" },
k3 = new List<string> { "v3" },
k4 = true,
k5 = null as Queue<string>
});
Debug.Assert(q == new Uri(
"https://stackoverflow.com/yo?k1=v1&k2=v2a&k2=v2b&k3=v3&k4=True&k5"));
// Keep existing query using a name/value collection.
nvc = HttpUtility.ParseQueryString(uri.Query);
nvc.Add("newKey", "newValue");
q = uri.WithQuery(nvc);
Debug.Assert(q == new Uri(
"https://stackoverflow.com/yo?newKey=newValue&oldKey=oldValue"));
// Merge two query objects using the RouteValueDictionary.
var an1 = new { k1 = "v1" };
var an2 = new { k2 = "v2" };
q = uri.WithQuery(
new RouteValueDictionary(an1).Concat(
new RouteValueDictionary(an2)));
Debug.Assert(q == new Uri(
"https://stackoverflow.com/yo?k1=v1&k2=v2"));
You need to read from req.Body
. The ParseForm
method is reading from the req.Body
and then parsing it in standard HTTP encoded format. What you want is to read the body and parse it in JSON format.
Here's your code updated.
package main
import (
"encoding/json"
"log"
"net/http"
"io/ioutil"
)
type test_struct struct {
Test string
}
func test(rw http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
panic(err)
}
log.Println(string(body))
var t test_struct
err = json.Unmarshal(body, &t)
if err != nil {
panic(err)
}
log.Println(t.Test)
}
func main() {
http.HandleFunc("/test", test)
log.Fatal(http.ListenAndServe(":8082", nil))
}
correct syntax at command line should be
echo -n "compute sha1" | openssl sha1
otherwise you'll hash the trailing newline character as well.
Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]);
Try with: javac -encoding ISO-8859-1 file_name.java
Found a one-liner that works in Chrome 66 from: http://www.yournewdesigner.com/css-experiments/javascript-window-close-firefox.html
TLDR: tricks the browser into believing JavaScirpt opened the current tab/window
window.open('', '_parent', '').close();
So for completeness
<input type="button" name="close" value="close" onclick="window.close();">
Though let it also be noted that readers may want to place this into a function that fingerprints which browsers require such trickery, because Firefox 59 doesn't work with the above.
FYI: In .NET, Hashtable
is thread safe for use by multiple reader threads and a single writing thread, while in Dictionary
public static members are thread safe, but any instance members are not guaranteed to be thread safe.
We had to change all our Dictionaries back to Hashtable
because of this.
As far as I know, you can't ask apt
for what their current sources are. However, you can do what you want using shell tools.
Getting a list of repositories:
grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/* >> current.repos.list
Applying the list:
apt-add-repository << current.repos.list
Regarding getting the repository from a package (installed or available), this will do the trick:
apt-cache policy package_name | grep -m1 http | awk '{ print $2 " " $3 }'
However, that will show you the repository of the latest version available of that package, and you may have more repositories for the same package with older versions. Remove all the grep/awk stuff if you want to see the full list.
If you are on SQL Server 2008 you can also use
CRYPT_GEN_RANDOM(2) % 10000
Which seems somewhat simpler (it is also evaluated once per row as newid
is - shown below)
DECLARE @foo TABLE (col1 FLOAT)
INSERT INTO @foo SELECT 1 UNION SELECT 2
UPDATE @foo
SET col1 = CRYPT_GEN_RANDOM(2) % 10000
SELECT * FROM @foo
Returns (2 random probably different numbers)
col1
----------------------
9693
8573
Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.
CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
BEGIN
DECLARE @Result INT
SET @Result = CRYPT_GEN_RANDOM(2)
RETURN CASE
WHEN @Result < 60000
OR @@NESTLEVEL = 32 THEN @Result % 10000
ELSE dbo.RandomNumber()
END
END
Open Source: CMU Sphinx
Shareware: http://www.e-speaking.com/ (Windows)
Commercial: Dragon NaturallySpeaking (Windows)
Only this regex worked for me:
sed 's/\\0//g'
So as you get your data do this: $ get_data | sed 's/\\0//g'
which will output your data without 0x00
That worked for me in WPF application:
string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();
use the --expression option
grep searchterm myfile.csv | sed --expression='s/replaceme/withthis/g'
Use the attr
method of jQuery like this:
alert($('input').attr('name'));
Note that you can also use attr
to set the attribute values by specifying second argument:
$('input').attr('name', 'new_name')
Using location.go(url)
is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree()
.
Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute})
but without reloading the component, it can be rewritten as:
const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString()
this.location.go(url);
I had the same problem. mysql -u root -p
worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password
, if you did not set one. More info here.
One interesting thing to point here; the usual way of using OR and AND too will work in this case, but with a small change. Instead of "and" and instead of "or", rather use Ampersand(&) and Pipe Operator(|) and it will work.
When we use 'and':
ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) and (ar<6), 'yo', ar)
Output:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
When we use Ampersand(&):
ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) & (ar<6), 'yo', ar)
Output:
array(['3', 'yo', 'yo', '14', '2', 'yo', '3', '7'], dtype='<U11')
And this is same in the case when we are trying to apply multiple filters in case of pandas Dataframe. Now the reasoning behind this has to do something with Logical Operators and Bitwise Operators and for more understanding about same, I'd suggest to go through this answer or similar Q/A in stackoverflow.
A user asked, why is there a need for giving (ar>3) and (ar<6) inside the parenthesis. Well here's the thing. Before I start talking about what's happening here, one needs to know about Operator precedence in Python.
Similar to what BODMAS is about, python also gives precedence to what should be performed first. Items inside the parenthesis are performed first and then the bitwise operator comes to work. I'll show below what happens in both the cases when you do use and not use "(", ")".
Case1:
np.where( ar>3 & ar<6, 'yo', ar)
np.where( np.array([3,4,5,14,2,4,3,7])>3 & np.array([3,4,5,14,2,4,3,7])<6, 'yo', ar)
Since there are no brackets here, the bitwise operator(&
) is getting confused here that what are you even asking it to get logical AND of, because in the operator precedence table if you see, &
is given precedence over <
or >
operators. Here's the table from from lowest precedence to highest precedence.
It's not even performing the <
and >
operation and being asked to perform a logical AND operation. So that's why it gives that error.
One can check out the following link to learn more about: operator precedence
Now to Case 2:
If you do use the bracket, you clearly see what happens.
np.where( (ar>3) & (ar<6), 'yo', ar)
np.where( (array([False, True, True, True, False, True, False, True])) & (array([ True, True, True, False, True, True, True, False])), 'yo', ar)
Two arrays of True and False. And you can easily perform logical AND operation on them. Which gives you:
np.where( array([False, True, True, False, False, True, False, False]), 'yo', ar)
And rest you know, np.where, for given cases, wherever True, assigns first value(i.e. here 'yo') and if False, the other(i.e. here, keeping the original).
That's all. I hope I explained the query well.
If anyone is interested, you can have the the offset information for all the consumer groups with the following command:
kafka-consumer-groups --bootstrap-server localhost:9092 --all-groups --describe
The parameter --all-groups is available from Kafka 2.4.0
Obviously @Ian Ringrose
's central thesis that you should be using a library for this is the best single answer here (hence a +1), but for minimal throwaway or demo code here's a concrete illustration of @SLaks
's subtle comment on @Jon Skeet
's more granular (+1'd) answer:
public List<XXX> Load( <<args>> )
{
using ( var connection = CreateConnection() )
using ( var command = Create<<ListXXX>>Command( <<args>>, connection ) )
{
connection.Open();
using ( var reader = command.ExecuteReader() )
return reader.Cast<IDataRecord>()
.Select( x => new XXX( x.GetString( 0 ), x.GetString( 1 ) ) )
.ToList();
}
}
As in @Jon Skeet
's answer, the
.Select( x => new XXX( x.GetString( 0 ), x.GetString( 1 ) ) )
bit can be extracted into a helper (I like to dump them in the query class):
public static XXX FromDataRecord( this IDataRecord record)
{
return new XXX( record.GetString( 0 ), record.GetString( 1 ) );
}
and used as:
.Select( FromDataRecord )
UPDATE Mar 9 13: See also Some excellent further subtle coding techniques to split out the boilerplate in this answer
SQL Server now supports the FORMAT function starting from version 2012, so:
SELECT FORMAT(id, '0000') FROM TableA
will do the trick.
If your id or column is in a varchar
and represents a number you convert first:
SELECT FORMAT(CONVERT(INT,id), '0000') FROM TableA
Also you can use the following class -
org.springframework.extensions.surf.util.ISO8601DateFormat
Date date = ISO8601DateFormat.parse("date in iso8601");
Link to the Java Doc - Hierarchy For Package org.springframework.extensions.surf.maven.plugin.util
If the child entity is used readonly, then it's possible to simply lie and set optional=false
.
Then ensure that every use of that mapped entity is preloaded via queries.
public class App {
...
@OneToOne(mappedBy = "app", fetch = FetchType.LAZY, optional = false)
private Attributes additional;
and
String sql = " ... FROM App a LEFT JOIN FETCH a.additional aa ...";
... maybe even persisting would work...
el.scrollIntoView()
This solution will not hurt your brain having to think about scrollTop
or scrollHeight
, has smooth scrolling built in, and even works in IE.
scrollIntoView() has options you can pass it like scrollIntoView({behavior: 'smooth'})
to get smooth scrolling.
methods: {
scrollToElement() {
const el = this.$el.getElementsByClassName('scroll-to-me')[0];
if (el) {
// Use el.scrollIntoView() to instantly scroll to the element
el.scrollIntoView({behavior: 'smooth'});
}
}
}
Then if you wanted to scroll to this element on page load you could call this method like this:
mounted() {
this.scrollToElement();
}
Else if you wanted to scroll to it on a button click or some other action you could call it the same way:
<button @click="scrollToElement">scroll to me</button>
The scroll works all the way down to IE 8. The smooth scroll effect does not work out of the box in IE or Safari. If needed there is a polyfill available for this here as @mostafaznv mentioned in the comments.
Another way to do this in PHP 5.6+ would be to use the ...
token
$a = array('a', 'b');
$b = array('c', 'd');
array_push($a, ...$b);
// $a is now equals to array('a','b','c','d');
This will also work with any Traversable
$a = array('a', 'b');
$b = new ArrayIterator(array('c', 'd'));
array_push($a, ...$b);
// $a is now equals to array('a','b','c','d');
A warning though:
$b
is an empty array or not traversable e.g. not an array$b
is not traversable