Change:
data: JSON.stringify({ model: source })
To:
data: {model: JSON.stringify(source)}
And in your controller you do this:
public void PartSourceAPI(string model)
{
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = js.Deserialize<PartSourceModel>(model);
}
If the url you use in jquery is /api/PartSourceAPI
then the controller name must be api
and the action(method) should be PartSourceAPI
For Windows (7), the same folder is located at,
%APPDATA%\Subversion\auth
Type in the above in the Run(Win key + R) dialog box and hit Enter,
To check the existing username open the below file as a text file,
%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx
Be sure that dirBar has the __init__.py
file -- this makes a directory into a Python package.
goto this file
node_modules\@angular-devkit\build-angular\src\dev-server\schema.json
and search port
"port": {
"type": "number",
"description": "Port to listen on.",
"default": 4200
},
change default value whatever you want and restart the server
You can get much more detailed information than the bash built-in time
(which Robert Gamble mentions) using time(1). Normally this is /usr/bin/time
.
Editor's note:
To ensure that you're invoking the external utility time
rather than your shell's time
keyword, invoke it as /usr/bin/time
.
time
is a POSIX-mandated utility, but the only option it is required to support is -p
.
Specific platforms implement specific, nonstandard extensions: -v
works with GNU's time
utility, as demonstrated below (the question is tagged linux); the BSD/macOS implementation uses -l
to produce similar output - see man 1 time
.
Example of verbose output:
$ /usr/bin/time -v sleep 1
Command being timed: "sleep 1"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 1%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 210
Voluntary context switches: 2
Involuntary context switches: 1
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
You can also include the assignment in the header file if you use header guards. I have used this technique for a C++ library I have created. Another way to achieve the same result is to use static methods. For example...
class Foo
{
public:
int GetMyStatic() const
{
return *MyStatic();
}
private:
static int* MyStatic()
{
static int mStatic = 0;
return &mStatic;
}
}
The above code has the "bonus" of not requiring a CPP/source file. Again, a method I use for my C++ libraries.
One more possible reason if you are using Tycho and Maven to build bundles, that you have wrong execution environment (Bundle-RequiredExecutionEnvironment
) in the manifest file (manifest.mf
) defined. For example:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Engine Plug-in
Bundle-SymbolicName: com.foo.bar
Bundle-Version: 4.6.5.qualifier
Bundle-Activator: com.foo.bar.Activator
Bundle-Vendor: Foobar Technologies Ltd.
Require-Bundle: org.eclipse.core.runtime,
org.jdom;bundle-version="1.0.0",
org.apache.commons.codec;bundle-version="1.3.0",
bcprov-ext;bundle-version="1.47.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.5
Export-Package: ...
...
Import-Package: ...
...
In my case everything else was ok. The compiler plugins (normal maven and tycho as well) were set correctly, still m2 generated old compliance level because of the manifest. I thought I share the experience.
If you're like me running in a restricted environment without administrative privileges, that means your only way to get node up and running is to grab the executable (node.exe) without using the installer. You also cannot change the path variable which makes it that much more challenging.
Here's what I did (for Windows)
npm install -g express
Running the installers through npm will now auto install packages where they need to be located (node_modules and the root)
Don't forget you will not be able to set the path variable if you do not have proper permissions. So your best route is to open a command prompt in the node.exe directory (shift right-click "Open command window here")
A better and optimised solution to display multiple validation messages for a single element would be like this.
<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
<span class="error" ng-message="required"> <your message> </span>
<span class="error" ng-message="size"> <your message> </span>
<span class="error" ng-message="filetype"> <your message> </span>
</div>
Controller Code should be the one suggested by @ Ben Lesh
If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:
alias df-gb='df -BG'
So if you type:
df-gb
into a terminal, you'll get your intended output of the disk usage in GB.
EDIT: or even use just df -h
to get it in a standard, human readable format.
Take a look at this answer:
from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).
print A.T # Transpose of A.
print A*x # Matrix multiplication of A and x.
print A.I # Inverse of A.
print linalg.solve(A, x) # Solve the linear equation system.
<gradient android:startColor="#ffdd00"
android:endColor="@color/colorPrimary"
android:centerColor="#ffff" />
<corners android:radius="33dp"/>
<padding
android:bottom="7dp"
android:left="7dp"
android:right="7dp"
android:top="7dp"
/>
I know this is a bit late, but I made a clean little function with a little ES6 syntax
function getHost(href){
return Object.assign(document.createElement('a'), { href }).host;
}
It could also be writen in ES5 like
function getHost(href){
return Object.assign(document.createElement('a'), { href: href }).host;
}
Of course IE doesn't support Object.assign
, but in my line of work, that doesn't matter.
If you need exact your example, you should add format to ToString()
string test = DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy"), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
But it's better to use straight formatting:
string test = DateTime.Now.ToString("yyyy-MM-dd")
I would expect that the JVM gracefully interrupts (thread.interrupt()
) all the running threads created by the application, at least for signals SIGINT (kill -2)
and SIGTERM (kill -15)
.
This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.
But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
.
As other users commented, the usage of shutdown hooks seems mandatory.
So, how do I would handle it?
Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM
from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).
As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException
if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException
is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.
So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Interrupting threads");
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
for (Thread th : runningThreads) {
if (th != Thread.currentThread()
&& !th.isDaemon()
&& th.getClass().getName().startsWith("org.brutusin")) {
System.out.println("Interrupting '" + th.getClass() + "' termination");
th.interrupt();
}
}
for (Thread th : runningThreads) {
try {
if (th != Thread.currentThread()
&& !th.isDaemon()
&& th.isInterrupted()) {
System.out.println("Waiting '" + th.getName() + "' termination");
th.join();
}
} catch (InterruptedException ex) {
System.out.println("Shutdown interrupted");
}
}
System.out.println("Shutdown finished");
}
});
Complete test application at github: https://github.com/idelvall/kill-test
HTML--
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css--
.active{
background:red;
}
button.btn:active{
background:red;
}
jQuery--
jQuery("#my_styles .btn").click(function(){
jQuery("#my_styles .btn").removeClass('active');
jQuery(this).toggleClass('active');
});
view the live demo on jsfiddle
You can also use array concatenation:
a = [2, 3]
[1] + a
=> [1, 2, 3]
This creates a new array and doesn't modify the original.
FrameLayout
is not the better way to do this:
Use RelativeLayout
instead.
You can position the elements anywhere you like.
The element that comes after, has the higher z-index than the previous one (i.e. it comes over the previous one).
Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
app:srcCompat="@drawable/ic_information"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a text."
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_margin="8dp"
android:padding="5dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#A000"
android:textColor="@android:color/white"/>
</RelativeLayout>
You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.
dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);
Check this
EDIT
As per the comment posted by Frank and Mat, you can also enable it with Null
exec dbms_output.enable(NULL);
buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).
If all you need is the stdout
output, then take a look at subprocess.check_output()
:
import subprocess
batcmd="dir"
result = subprocess.check_output(batcmd, shell=True)
Because you were using os.system()
, you'd have to set shell=True
to get the same behaviour. You do want to heed the security concerns about passing untrusted arguments to your shell.
If you need to capture stderr
as well, simply add stderr=subprocess.STDOUT
to the call:
result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)
to redirect the error output to the default output stream.
If you know that the output is text, add text=True
to decode the returned bytes value with the platform default encoding; use encoding="..."
instead if that codec is not correct for the data you receive.
Try to use this :
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < chBoxListTables.Items.Count; i++)
if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
{
txtBx.text += chBoxListTables.Items[i].ToString() + " \n";
}
}
You need install the postgreSQL dev package with header of PostgreSQL
sudo apt-get install libpq-dev
This might help
temp = ([[1,2,3,4,5,6,.....,7]])
You can try:
System.arraycopy(sourceArray, 0, targetArray, 0, targetArray.length);// copies whole array
// copies elements 1 and 2 from sourceArray to targetArray
System.arraycopy(sourceArray, 1, targetArray, 0, 2);
See javadoc for System.
As @Ian explained, the problem is that jQuery's click()
is not the same as the native one.
Therefore, consider using vanilla-js instead of jQuery:
var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
Try this:
$(document).ready(function() {
// When the document is ready
// Do something
});
Use this for print key hash in kotlin
try {
val info = context.getPackageManager().getPackageInfo(context.packageName,
PackageManager.GET_SIGNATURES);
for (signature in info.signatures) {
val md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
Log.d("Key hash ", android.util.Base64.encodeToString(md.digest(), android.util.Base64.DEFAULT))
}
}catch (e:Exception){
}
What about this?
public static Date formatStrictDate(int year, int month, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
Technically it's undefined, but in reality most (all?) compilers treat it exactly the same as using a reinterpret_cast
from one type to the other, the result of which is implementation defined. I wouldn't lose sleep over your current code.
jQuery's attr
method returns the value of the attribute:
The
.attr()
method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's.each()
or.map()
method.
All you need is:
$('html').attr('lang') == 'fr-FR'
However, you might want to do a case-insensitive match:
$('html').attr('lang').toLowerCase() === 'fr-fr'
jQuery's val
method returns the value of a form element.
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. In the case of<select multiple="multiple">
elements, the.val()
method returns an array containing each selected option; if no option is selected, it returnsnull
.
I was having a similar problem trying to install a package called AED. I tried using the install.packages() command:
install.packages('FILE_PATH', repos=NULL, type = "source")
but kept getting the following warning message:
Warning message:
In install.packages("/Users/blahblah/R-2.14.0/AED", :
installation of package ‘/Users/blahblah/R-2.14.0/AED’ had
non-zero exit status
It turned out the folder 'AED' had another folder inside of it that hadn't been uncompressed. I just uncompressed it and tried installing the package again and it worked.
I'm too newbie to comment zeantsoi post ;(. So here his what I needed to do to solved on OSX on 10.9.1 the
IOError: decoder jpeg not available
1) install Xcode tools (open your terminal and execute: xcode-select --install
) - taken from this post: Can't install PIL after Mac OS X 10.9
2) install libpng and libjpeg package (combo installer) from this link: http://ethan.tira-thompson.com/Mac_OS_X_Ports.html
3) reboot (not sure it was mandatory)
4) Re-install PIL with run pip install -I PIL
(as I had initially installed PIL before having the issue)
Hope this help and don't confuse more ...
_oho
I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.
I accomplished something similar using jQuery Waypoints.
There's a lot of moving parts, and quite a bit of logic (that I hope to get on GitHub some day soon), but essentially what you could do is...
fixed
.table.fixed
that make it invisible.sticky
to table.fixed
table.sticky.fixed
that position it just below the navbar and also make just the thead
content visible. This also has a z-index
so it is laid above the rest of the content..sticky
from the table.fixed
You have to duplicate the entire table DOM in order to ensure column widths line up appropriately.
If that sounds really complicated, you might want to try playing around with the DataTables plugin and the FixedHeader extension: https://datatables.net/extensions/fixedheader/
Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)
Yes - their performance characteristics differ significantly. It would probably be better to call them SortedList
and SortedTree
as that reflects the implementation more closely.
Look at the MSDN docs for each of them (SortedList
, SortedDictionary
) for details of the performance for different operations in different situtations. Here's a nice summary (from the SortedDictionary
docs):
The
SortedDictionary<TKey, TValue>
generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this, it is similar to theSortedList<TKey, TValue>
generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:
SortedList<TKey, TValue>
uses less memory thanSortedDictionary<TKey, TValue>
.
SortedDictionary<TKey, TValue>
has faster insertion and removal operations for unsorted data, O(log n) as opposed to O(n) forSortedList<TKey, TValue>
.If the list is populated all at once from sorted data,
SortedList<TKey, TValue>
is faster thanSortedDictionary<TKey, TValue>
.
(SortedList
actually maintains a sorted array, rather than using a tree. It still uses binary search to find elements.)
var _login = function (loginData) {_x000D_
_x000D_
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
_x000D_
var deferred = $q.defer();_x000D_
_x000D_
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
_x000D_
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
_x000D_
_authentication.isAuth = true;_x000D_
_authentication.userName = loginData.userName;_x000D_
_x000D_
deferred.resolve(response);_x000D_
_x000D_
}).error(function (err, status) {_x000D_
_logOut();_x000D_
deferred.reject(err);_x000D_
});_x000D_
_x000D_
return deferred.promise;_x000D_
_x000D_
};_x000D_
_x000D_
After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter
to a separate sheet.
With .Range("A1:A" & LastRow)
.Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
.Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
Sheets("Sheet2").activate
DestinationRange.PasteSpecial
End With
In this block, the AutoFilter
finds all of the rows that contain the value of strSearch
and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.
I was searching for the same issue and was able to center align the text in a NSAttributedString this way:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];
Not sure if this is still relevant, but I use this way
Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean 'put this at the top of the module
Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
GetUserID = Left$(strUserName, lngLen - 1)
Else
GetUserID = ""
End If
Exit Function
End Function
This next bit I save file as PDF, but can change to suit
Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)
ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Firstly,Object is created and then we assign it 's address to pointers.Constructors are called at the time of object creation and used to initializ the value of data members. Pointer to object comes into scenario after object creation. Thats why, C++ do not allows us to make constructors as virtual . .another reason is that, There is nothing like pointer to constructor , which can point to virtual constructor,because one of the property of virtual function is that it can be used by pointers only.
Python 2, using lambda
>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
From the MySQL manual
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
The animate(..)
function' signature is:
.animate( properties, options );
And it says the following about the parameter properties
:
properties A map of CSS properties that the animation will move toward.
text
is not a CSS property, this is why the function isn't working as you expected.
Do you want to fade the text out? Do you want to move it? I might be able to provide an alternative.
Have a look at the following fiddle.
int a = 1;
char * c = (char*)(&a); //In C++ should be intermediate cst to void*
That's because $_POST
is pre-populated with form data.
To get JSON data (or any raw input), use php://input
.
$json = json_decode(file_get_contents("php://input"));
This worked
apt-get install php7.0-zip
and no need to restart php7.0-fpm
manually.
Unpacking
php7.0-zip
(7.0.16-4+deb.sury.org~trusty+1
) ...
Processing triggers forphp7.0-fpm
(7.0.11-1+deb.sury.org~trusty+1
) ...
php7.0-fpm
stop/waiting
php7.0-fpm
start/running, process 1572
php7.0-fpm
stop/waiting
php7.0-fpm
start/running, process 1777
Setting upphp7.0-zip
(7.0.16-4+deb.sury.org~trusty+1
) ...
locale: Cannot setLC_ALL
to default locale: No such file or directoryCreating config file
/etc/php/7.0/mods-available/zip.ini
with new version
Processing triggers forphp7.0-fpm
(7.0.11-1+deb.sury.org~trusty+1
) ...
php7.0-fpm
stop/waiting
php7.0-fpm
start/running, process 2354
php7.0-fpm
stop/waiting
php7.0-fpm
start/running, process 2397
As @Nakilon said, their is a comparing tool built in github if that's what you use.
To use it, append the url of the repo with "/compare".
In my opinion db4o is the easiest way to go. Here you can find a tutorial: http://community.versant.com/documentation/reference/db4o-7.12/java/tutorial/
And here you can download the library:
http://www.db4o.com/community/download.aspx?file=db4o-8.0-java.zip
(Just put the db4o-8.0...-all-java5.jar in the lib directory into your project's libs folder. If there is no libs folder in you project create it)
As db4o is a object oriented database system you can directly save you objects into the database and later get them back.
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
There is no notion of method overloading in Python. But you can achieve a similar effect by specifying optional and keyword arguments
First check the type of compression using the file
command:
file name_name.tgz
O/P- If output is " XZ compressed data"
Then use tar xf <archive name>
to unzip the file, e.g.
tar xf archive.tar.xz
tar xf archive.tar.gz
tar xf archive.tar
tar xf archive.tgz
You can also simply write
if (dt.Rows.Count == 0)
{
//DataTable does not contain records
}
yes....` from Xml
android:button="@drawable/yourdrawable"
and from Java
myRadioButton.setButtonDrawable(resourceId or Drawable);
`
This answer seems relevant since the OP makes reference to a need for a multi-OS solution. This Github help article details available approaches for handling lines endings cross-OS. There are global and per-repo approaches to managing cross-os line endings.
Global approach
Configure Git line endings handling on Linux or OS X:
git config --global core.autocrlf input
Configure Git line endings handling on Windows:
git config --global core.autocrlf true
Per-repo approach:
In the root of your repo, create a .gitattributes
file and define line ending settings for your project files, one line at a time in the following format: path_regex line-ending-settings
where line-ending-settings
is one of the following:
The text
value can be configured further to instruct Git on how to handle line endings for matching files:
text
- Changes line endings to OS native line endings.text eol=crlf
- Converts line endings to CRLF
on checkout.text eol=lf
- Converts line endings to LF
on checkout.text=auto
- Sensible default that leaves line handle up to Git's discretion.Here is the content of a sample .gitattributes file:
# Set the default behavior for all files.
* text=auto
# Normalized and converts to
# native line endings on checkout.
*.c text
*.h text
# Convert to CRLF line endings on checkout.
*.sln text eol=crlf
# Convert to LF line endings on checkout.
*.sh text eol=lf
# Binary files.
*.png binary
*.jpg binary
More on how to refresh your repo after changing line endings settings here. Tldr:
backup your files with Git, delete every file in your repository (except the .git directory), and then restore the files all at once. Save your current files in Git, so that none of your work is lost.
git add . -u
git commit -m "Saving files before refreshing line endings"
Remove the index and force Git to rescan the working directory.
rm .git/index
Rewrite the Git index to pick up all the new line endings.
git reset
Show the rewritten, normalized files.
In some cases, this is all that needs to be done. Others may need to complete the following additional steps:
git status
Add all your changed files back, and prepare them for a commit. This is your chance to inspect which files, if any, were unchanged.
git add -u
It is perfectly safe to see a lot of messages here that read[s] "warning: CRLF will be replaced by LF in file."
Rewrite the .gitattributes file.
git add .gitattributes
Commit the changes to your repository.
git commit -m "Normalize all the line endings"
This homebrew function have precision down to a 10th of a second or less.
function sleep (a)
local sec = tonumber(os.clock() + a);
while (os.clock() < sec) do
end
end
If you get an OutOfMemoryError then it's usually too late to call the garbage collector...
Here is quote from Android Developer:
Most of the time, garbage collection occurs because of tons of small, short-lived objects and some garbage collectors, like generational garbage collectors, can optimize the collection of these objects so that the application does not get interrupted too often. The Android garbage collector is unfortunately not able to perform such optimizations and the creation of short-lived objects in performance critical code paths is thus very costly for your application.
So to my understanding, there is no urgent need to call the gc. It's better to spend more effort in avoiding the unnecessary creation of objects (like creation of objects inside loops)
For me the following lines of code did the trick
mysqldump --quote-names -q -u username1 --password='password1' originalDB | mysql -u username2 --password='password2' duplicateDB
Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-
npm install jquery --save
Then, import $ from "jquery";
Worth mentioning that the handlebar library https://github.com/jknack/handlebars.java can trivialize many transformation tasks include toCSV.
I got this error when I tried to install ruby 2.3.1 using rvm. It first told me to run brew update
, which I did, and then when I tried running rvm install ruby-2.3.1
, I received the error in this SO question.
The fix was to first run brew upgrade
, apparently according to this superuser.com question you need to do both brew update
&& brew upgrade
. Once that was done, I could finally install ruby 2.3.1.
Simplest solution is to go at the end of the month (we always know that months have at least 28 days) and add enough days to move to the next moth:
>>> from datetime import datetime, timedelta
>>> today = datetime.today()
>>> today
datetime.datetime(2014, 4, 30, 11, 47, 27, 811253)
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
datetime.datetime(2014, 5, 30, 11, 47, 27, 811253)
Also works between years:
>>> dec31
datetime.datetime(2015, 12, 31, 11, 47, 27, 811253)
>>> today = dec31
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
Just keep in mind that it is not guaranteed that the next month will have the same day, for example when moving from 31 Jan to 31 Feb it will fail:
>>> today
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: day is out of range for month
So this is a valid solution if you need to move to the first day of the next month, as you always know that the next month has day 1 (.replace(day=1)
). Otherwise, to move to the last available day, you might want to use:
>>> today
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
>>> next_month = (today.replace(day=28) + timedelta(days=10))
>>> import calendar
>>> next_month.replace(day=min(today.day,
calendar.monthrange(next_month.year, next_month.month)[1]))
datetime.datetime(2016, 2, 29, 11, 47, 27, 811253)
Actually you only need to execute:
sudo chmod +x ./gradlew
It works for me! And if it is too slow, you can execute:
./gradlew clean build
Why so many negative votes
The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.
If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction
may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.
In Typescript with relative path to the icon:
import path from 'path';
route.get('/favicon.ico', (_req, res) => res.sendFile(path.join(__dirname, '../static/myicon.png')));
After installing the gems, if you want to know where a particular gem is. Try typing:
gem list
You will be able to see the list of gems you have installed. Now use bundle show
and name the gem you want to know the path for, like this:
bundle show <gemName>
Or (as of younger versions of bundler):
bundle info <gemName>
Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)
https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search
You can use this simple ES6 method
const lastChar = (str) => str.split('').reverse().join(',').replace(',', '')[str.length === str.length + 1 ? 1 : 0];_x000D_
_x000D_
_x000D_
// example_x000D_
console.log(lastChar("linto.yahoo.com."));
_x000D_
This will work in every browsers.
I have created a horizontal ListView in every row of ListView if you want single You can do the following
Here I am just creating horizontalListView of Thumbnail of Videos Like this
The idea is just continuously add the ImageView to the child of LinearLayout in HorizontalscrollView
Note: remember to fire .removeAllViews(); before next time load other wise it will add duplicate child
Cursor mImageCursor = db.getPlaylistVideoImage(playlistId);
mVideosThumbs.removeAllViews();
if (mImageCursor != null && mImageCursor.getCount() > 0) {
for (int index = 0; index < mImageCursor.getCount(); index++) {
mImageCursor.moveToPosition(index);
ImageView iv = (ImageView) imageViewInfalter.inflate(
R.layout.image_view, null);
name = mImageCursor.getString(mImageCursor
.getColumnIndex("LogoDefaultName"));
logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
if (logoFile.exists()) {
Uri uri = Uri.fromFile(logoFile);
iv.setImageURI(uri);
}
iv.setScaleType(ScaleType.FIT_XY);
mVideosThumbs.addView(iv);
}
mImageCursor.close();
mImageCursor = null;
} else {
ImageView iv = (ImageView) imageViewInfalter.inflate(
R.layout.image_view, null);
String name = "";
File logoFile;
name = mImageCursor.getString(mImageCursor
.getColumnIndex("LogoMediumName"));
logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
if (logoFile.exists()) {
Uri uri = Uri.fromFile(logoFile);
iv.setImageURI(uri);
}
}
My xml for HorizontalListView
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/linearLayoutTitle"
android:background="@drawable/shelf"
android:paddingBottom="@dimen/Playlist_TopBottom_margin"
android:paddingLeft="@dimen/playlist_RightLeft_margin"
android:paddingRight="@dimen/playlist_RightLeft_margin"
android:paddingTop="@dimen/Playlist_TopBottom_margin" >
<LinearLayout
android:id="@+id/linearLayoutVideos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
and Also my Image View as each child
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imageViewThumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="20dp"
android:adjustViewBounds="true"
android:background="@android:color/transparent"
android:contentDescription="@string/action_settings"
android:cropToPadding="true"
android:maxHeight="200dp"
android:maxWidth="240dp"
android:padding="@dimen/playlist_image_padding"
android:scaleType="centerCrop"
android:src="@drawable/loading" />
To learn More you can follow the following links which have some easy samples
.eq() -An integer indicating the 0-based position of the element.
Ex:
Consider a page with a simple list on it:
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
</ul>
We can apply this method to the set of list items:
$( "li" ).eq( 2 ).css( "background-color", "red" );
It sets result
to the (unsigned) value resulting from putting the 8 bits of value
in the lowest 8 bits of result
.
The reason something like this is necessary is that byte
is a signed type in Java. If you just wrote:
int result = value;
then result
would end up with the value ff ff ff fe
instead of 00 00 00 fe
. A further subtlety is that the &
is defined to operate only on int
values1, so what happens is:
value
is promoted to an int
(ff ff ff fe
).0xff
is an int
literal (00 00 00 ff
).&
is applied to yield the desired value for result
.(The point is that conversion to int
happens before the &
operator is applied.)
1Well, not quite. The &
operator works on long
values as well, if either operand is a long
. But not on byte
. See the Java Language Specification, sections 15.22.1 and 5.6.2.
Easy and simple. You don't need create a new FormData or do an Ajax to send image. You can put dragged files in your input field.
$dropzone.ondrop = function (e) {
e.preventDefault();
input.files = e.dataTransfer.files;
}
var $dropzone = document.querySelector('.dropzone');
var input = document.getElementById('file-upload');
$dropzone.ondragover = function (e) {
e.preventDefault();
this.classList.add('dragover');
};
$dropzone.ondragleave = function (e) {
e.preventDefault();
this.classList.remove('dragover');
};
$dropzone.ondrop = function (e) {
e.preventDefault();
this.classList.remove('dragover');
input.files = e.dataTransfer.files;
}
_x000D_
.dropzone {
padding: 10px;
border: 1px dashed black;
}
.dropzone.dragover {
background-color: rgba(0, 0, 0, .3);
}
_x000D_
<div class="dropzone">Drop here</div>
<input type="file" id="file-upload" style="display:none;">
_x000D_
Simply put, hash-based collections aren't indexed so you have to do it manually.
It happened to me when I had a same port used in ssh tunnel SOCKS to run Proxy in 8080 port and my server and my firefox browser proxy was set to that port and got this issue.
Try going to Project -> Properties -> Java Build Path -> Order & Export
And Confirm Android Private Libraries are checked for your project and for all other library projects you are using in your Application.
As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.
In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field
class HealthConditions extends React.Component {
constructor(props) {
super(props);
this.state = {
inputLinkClicked: false
}
}
handleAddSecondInput() {
this.setState({
inputLinkClicked: true
})
}
render() {
return(
<main id="wrapper" className="" data-reset-cookie-tab>
<div id="content" role="main">
<div className="inner-block">
<H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>
<InputField label="Name of condition"
InputType="text"
InputId="id-condition"
InputName="condition"
/>
{
this.state.inputLinkClicked?
<InputField label=""
InputType="text"
InputId="id-condition2"
InputName="condition2"
/>
:
<div></div>
}
<button
type="button"
className="make-button-link"
data-add-button=""
href="#"
onClick={this.handleAddSecondInput}
>
Add a condition
</button>
<FormButton buttonLabel="Next"
handleSubmit={this.handleSubmit}
linkto={
this.state.illnessOrDisability === 'true' ?
"/404"
:
"/add-your-details"
}
/>
<BackLink backLink="/add-your-details" />
</div>
</div>
</main>
);
}
}
It is because TypeScript 2.7 includes a strict class checking where all the properties should be initialized in the constructor. A workaround is to add
the !
as a postfix to the variable name:
makes!: any[];
//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]
The reason why I add this answer is that I want to explain the relationship of .
and text()
.
The first thing is when using []
, there are only two types of data:
[number]
to select a node from node-set[bool]
to filter a node-set from node-setIn this case, the value is evaluated to boolean by function boolean()
, and there is a rule:
Filters are always evaluated with respect to a context.
When you need to compare text()
or .
with a string "Data"
, it first uses string()
function to transform those to string type, than gets a boolean result.
There are two important rule about string()
:
The string()
function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.
text()
is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]
.
When it is evaluated by string(["Data"])
, it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.
If you want the string()
function to concatenate all child text, you must then pass a single node instead of a node-set.
For example, we get a node-set ['a', 'b']
, you can pass there parent node to string(parent)
, this will return 'ab'
, and of cause string(.)
in you case will return an concatenated string "Data"
.
Both way will get same result only when there is a text node.
Use the Java 8 way of converting a Map<String, Object>
to Map<String, String>
. This solution handles null
values.
Map<String, String> keysValuesStrings = keysValues.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().toString()));
You would want to use CSS to achieve that.
say you have a table with the attribute id="my_table"
You would want to write the following in your css file
#my_table{
margin-top:10px //moves your table 10pixels down
margin-left:10px //moves your table 10pixels right
}
if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px
to the style attribute in your table element like so
<table style="margin-top:10px; margin-left:10px;">
....
</table>
There are a lot of resources on the net describing CSS and HTML in detail
If you are using Spring4/SpringBoot 1.x, then it's worth mentioning that you can add "text" (json) parts as well . This can be done via MockMvcRequestBuilders.fileUpload().file(MockMultipartFile file) (which is needed as method .multipart()
is not available in this version):
@Test
public void test() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/files")
// file-part
.file(makeMultipartFile( "file-part" "some/path/to/file.bin", "application/octet-stream"))
// text part
.file(makeMultipartTextPart("json-part", "{ \"foo\" : \"bar\" }", "application/json"))
.andExpect(status().isOk())));
}
private MockMultipartFile(String requestPartName, String filename,
String contentType, String pathOnClassPath) {
return new MockMultipartFile(requestPartName, filename,
contentType, readResourceFile(pathOnClasspath);
}
// make text-part using MockMultipartFile
private MockMultipartFile makeMultipartTextPart(String requestPartName,
String value, String contentType) throws Exception {
return new MockMultipartFile(requestPartName, "", contentType,
value.getBytes(Charset.forName("UTF-8")));
}
private byte[] readResourceFile(String pathOnClassPath) throws Exception {
return Files.readAllBytes(Paths.get(Thread.currentThread().getContextClassLoader()
.getResource(pathOnClassPath).toUri()));
}
}
Here I have converted Federico A. Ramponi's answer to PHP if anybody is interested:
<?php
# deg2rad and rad2deg are already within PHP
# Semi-axes of WGS-84 geoidal reference
$WGS84_a = 6378137.0; # Major semiaxis [m]
$WGS84_b = 6356752.3; # Minor semiaxis [m]
# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
function WGS84EarthRadius($lat)
{
global $WGS84_a, $WGS84_b;
$an = $WGS84_a * $WGS84_a * cos($lat);
$bn = $WGS84_b * $WGS84_b * sin($lat);
$ad = $WGS84_a * cos($lat);
$bd = $WGS84_b * sin($lat);
return sqrt(($an*$an + $bn*$bn)/($ad*$ad + $bd*$bd));
}
# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
function boundingBox($latitudeInDegrees, $longitudeInDegrees, $halfSideInKm)
{
$lat = deg2rad($latitudeInDegrees);
$lon = deg2rad($longitudeInDegrees);
$halfSide = 1000 * $halfSideInKm;
# Radius of Earth at given latitude
$radius = WGS84EarthRadius($lat);
# Radius of the parallel at given latitude
$pradius = $radius*cos($lat);
$latMin = $lat - $halfSide / $radius;
$latMax = $lat + $halfSide / $radius;
$lonMin = $lon - $halfSide / $pradius;
$lonMax = $lon + $halfSide / $pradius;
return array(rad2deg($latMin), rad2deg($lonMin), rad2deg($latMax), rad2deg($lonMax));
}
?>
Putting #pragma once
at the top of your header file will ensure that it is only included once. Note that #pragma once
is not standard C99, but supported by most modern compilers.
An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */
)
Refs usage in React 16.3+ changed.
The following solution uses ES6 and follows best practices for binding as well as setting the ref through a method.
To see it in action:
Class Implementation:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
/**
* Component that alerts if you click outside of it
*/
export default class OutsideAlerter extends Component {
constructor(props) {
super(props);
this.wrapperRef = React.createRef();
this.setWrapperRef = this.setWrapperRef.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
/**
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.current.contains(event.target)) {
alert('You clicked outside of me!');
}
}
render() {
return <div ref={this.wrapperRef}>{this.props.children}</div>;
}
}
OutsideAlerter.propTypes = {
children: PropTypes.element.isRequired,
};
Hooks Implementation:
import React, { useRef, useEffect } from "react";
/**
* Hook that alerts clicks outside of the passed ref
*/
function useOutsideAlerter(ref) {
useEffect(() => {
/**
* Alert if clicked on outside of element
*/
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
alert("You clicked outside of me!");
}
}
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref]);
}
/**
* Component that alerts if you click outside of it
*/
export default function OutsideAlerter(props) {
const wrapperRef = useRef(null);
useOutsideAlerter(wrapperRef);
return <div ref={wrapperRef}>{props.children}</div>;
}
Short & Sweet:
/**
* Get a diff between two dates
*
* @param oldDate the old date
* @param newDate the new date
* @return the diff value, in the days
*/
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
try {
return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Usage:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);
Output:
dateDifference: 2
Kotlin Version:
@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
return try {
DurationUnit.DAYS.convert(
format.parse(newDate).time - format.parse(oldDate).time,
DurationUnit.MILLISECONDS
)
} catch (e: Exception) {
e.printStackTrace()
0
}
}
p
is not how you put text in a
. That is the problem. The only solution is to put the text between <a>
and </a>
. For example:
<a href="https://stackoverflow.com/posts/64201994/edit" style="text-align:center;">Stack Overflow</a>
You can check this sample code to understand how you can access the relative path using the java sample code
import java.io.File;
public class MainClass {
public static void main(String[] args) {
File relative = new File("html/javafaq/index.html");
System.out.println("relative: ");
System.out.println(relative.getName());
System.out.println(relative.getPath());
}
}
Here getPath will display the relative path of the file.
Besides Carl's answer, the "standard" C++ way is not to use a C int
array, but rather something like a C++ STL std::vector<int> list
which you can query for list.size()
.
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '
.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
Something that commonly happens is that the manifest file isn't named properly. Double check the name (and extension) and be sure that it doesn't end with .txt (for example).
In order to determine this, make sure you aren't hiding file extensions:
Also, note that the naming of the manifest file is, in fact, case sensitive, i.e. manifest.json != MANIFEST.JSON.
Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.
max-width:something px;
max-height:something px;
The other option would be to use the devlopr tools and see if you can remove the natural padding.
padding: 0;
According to oracle online documentation
ORA-12541: TNS:no listener
Cause: The connection request could not be completed because the listener is not running.
Action: Ensure that the supplied destination address matches one of the addresses used by
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on
the remote machine.
ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20) this is perfect for change to datatype
Try to add this hotfix: hotfixv4.microsoft.com/Windows%207/Windows%20Server2008%20R2%20SP1/sp2/Fix362872/7600/free/427221_intl_i386_zip.exe
PLEASE NOTE: THE ANSWER BELOW IS HORRIBLY OUTDATED, AND MIGHT NOT BE ENTIRELY CORRECT ANYMORE.
You can program in C/C++ using the Android NDK. You'll have to wrap your c++ codebase in a static library and load that through a Java wrapper & JNI.
The standard NDK does not support RTTI and a lot of the functionality of standard c++ is also not available such as std::string, etc. To solve this you can recompile the NDK. Dmitry Moskalchuk supplies a modified version of the NDK that supports this at http://www.crystax.net/android/ndk-r3.php. This modified version works on all Android phones that run on an ARM processor.
Depending on the kind of application you should decide to use Java or C/C++. I'd use C/C++ for anything that requires above average computational power and games -- Java for the rest.
Just pick one language and write the majority of your application in that language; JNI calls can decrease your performance by a lot. Java isn't that hard though -- if you know how to program in C/C++. The advantage of Java is that the application can run on any device running Android, where as NDK applications depend on the architecture it was compiled for.
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
In my case, installing visual studio SP1 unbroke the uninstall/repair functionality.
DBeaver Community Edition (dbeaver.io) makes it trivial to connect to a database, then import a CSV file for upload to a PostgreSQL database. It also makes it easy to issue queries, retrieve data, and download result sets to CSV, JSON, SQL, or other common data formats.
It is a FOSS multi-platform database tool for SQL programmers, DBAs and analysts that supports all popular databases: MySQL, PostgreSQL, SQLite, Oracle, DB2, SQL Server, Sybase, MS Access, Teradata, Firebird, Hive, Presto, etc. It's a viable FOSS competitor to TOAD for Postgres, TOAD for SQL Server, or Toad for Oracle.
I have no affiliation with DBeaver. I love the price (FREE!) and full functionality, but I wish they would open up this DBeaver/Eclipse application more and make it easy to add analytics widgets to DBeaver / Eclipse, rather than requiring users to pay for the $199 annual subscription just to create graphs and charts directly within the application. My Java coding skills are rusty and I don't feel like taking weeks to relearn how to build Eclipse widgets, (only to find that DBeaver has probably disabled the ability to add third-party widgets to the DBeaver Community Edition.)
Can DBeaver power users who are Java developers provide some insight about the steps to create analytics widgets to add into the Community Edition of DBeaver?
SpringApplication implicitly registers a shutdown hook with the JVM to ensure that ApplicationContext is closed gracefully on exit. That will also call all bean methods annotated with @PreDestroy
. That means we don't have to explicitly use the registerShutdownHook()
method of a ConfigurableApplicationContext
in a boot application, like we have to do in spring core application.
@SpringBootConfiguration
public class ExampleMain {
@Bean
MyBean myBean() {
return new MyBean();
}
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ExampleMain.class, args);
MyBean myBean = context.getBean(MyBean.class);
myBean.doSomething();
//no need to call context.registerShutdownHook();
}
private static class MyBean {
@PostConstruct
public void init() {
System.out.println("init");
}
public void doSomething() {
System.out.println("in doSomething()");
}
@PreDestroy
public void destroy() {
System.out.println("destroy");
}
}
}
I'm only familiar with Mongo and Couch, but there's also one named Persistence.
OK, I've worked out what's going on. Leonidas is right, it's not just the hash that gets encrypted (in the case of the Cipher class method), it's the ID of the hash algorithm concatenated with the digest:
DigestInfo ::= SEQUENCE {
digestAlgorithm AlgorithmIdentifier,
digest OCTET STRING
}
Which is why the encryption by the Cipher and Signature are different.
Step 1: Here is one simple example. You have to create a SQL file from the dump file using SQLFILE
option.
Step 2: Grep for CREATE USER
in the generated SQL file (here tables.sql)
Example here:
$ impdp directory=exp_dir dumpfile=exp_user1_all_tab.dmp logfile=imp_exp_user1_tab sqlfile=tables.sql
Import: Release 11.2.0.3.0 - Production on Fri Apr 26 08:29:06 2013
Copyright (c) 1982, 2011, Oracle and/or its affiliates. All rights reserved.
Username: / as sysdba
Processing object type SCHEMA_EXPORT/PRE_SCHEMA/PROCACT_SCHEMA Job "SYS"."SYS_SQL_FILE_FULL_01" successfully completed at 08:29:12
$ grep "CREATE USER" tables.sql
CREATE USER "USER1" IDENTIFIED BY VALUES 'S:270D559F9B97C05EA50F78507CD6EAC6AD63969E5E;BBE7786A5F9103'
Lot of datapump options explained here http://www.acehints.com/p/site-map.html
Iterate through a copy of the list:
>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
print item
if item == "b":
a.remove(item)
a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']
Asynchronous way to achieve it.
void inputStreamToOutputStream(final InputStream inputStream, final OutputStream out) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
int d;
while ((d = inputStream.read()) != -1) {
out.write(d);
}
} catch (IOException ex) {
//TODO make a callback on exception.
}
}
});
t.setDaemon(true);
t.start();
}
The installation process adds the phpMyAdmin Apache configuration file into the /etc/apache2/conf-enabled/ directory, where it is read automatically. The only thing you need to do is explicitly enable the mbstring PHP extension, Because sometimes you forgot to enable the mbstring mode so simply type the below command to enabled the mbstring mode...
sudo phpenmod mbstring
Afterward, restart Apache for your changes to be recognized:
sudo systemctl restart apache2
This problem is often created when adding a column or using an existing column as a primary key. It is not created due to a primary key existing that was never actually created or due to damage to the table.
What the error actually denotes is that a pending key value is blank.
The solution is to populate the column with unique values and then try to create the primary key again. There can be no blank, null or duplicate values, or this misleading error will appear.
def querySet_to_list(qs):
"""
this will return python list<dict>
"""
return [dict(q) for q in qs]
def get_answer_by_something(request):
ss = Answer.objects.filter(something).values()
querySet_to_list(ss) # python list return.(json-able)
this code convert django queryset to python list
If you have the to your project and the Copy Local flag is in true, the solution should be just the project. That copy the DLL to the bin folder.
To remove the left-most word, you'll need to use either RIGHT or SUBSTRING. Assuming you know how many characters are involved, that would look either of the following:
SELECT RIGHT('Hello World', 5)
SELECT SUBSTRING('Hello World', 6, 100)
If you don't know how many characters that first word has, you'll need to find out using CHARINDEX, then substitute that value back into SUBSTRING:
SELECT SUBSTRING('Hello World', CHARINDEX(' ', 'Hello World') + 1, 100)
This finds the position of the first space, then takes the remaining characters to the right.
If each part have the same lines number, for example 22, here my solution:
split --numeric-suffixes=2 --additional-suffix=.txt -l 22 file.txt file
and you obtain file2.txt with the first 22 lines, file3.txt the 22 next line…
Thank @hamruta-takawale, @dror-s and @stackoverflowuser2010
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
In many cases, particularly with text classification it is not enough just to store the classifier but you'll need to store the vectorizer as well so that you can vectorize your input in future.
import pickle
with open('model.pkl', 'wb') as fout:
pickle.dump((vectorizer, clf), fout)
future use case:
with open('model.pkl', 'rb') as fin:
vectorizer, clf = pickle.load(fin)
X_new = vectorizer.transform(new_samples)
X_new_preds = clf.predict(X_new)
Before dumping the vectorizer, one can delete the stop_words_ property of vectorizer by:
vectorizer.stop_words_ = None
to make dumping more efficient. Also if your classifier parameters is sparse (as in most text classification examples) you can convert the parameters from dense to sparse which will make a huge difference in terms of memory consumption, loading and dumping. Sparsify the model by:
clf.sparsify()
Which will automatically work for SGDClassifier but in case you know your model is sparse (lots of zeros in clf.coef_) then you can manually convert clf.coef_ into a csr scipy sparse matrix by:
clf.coef_ = scipy.sparse.csr_matrix(clf.coef_)
and then you can store it more efficiently.
Just using this will add "mynewclass" to the element with the id myElement and revert it on the next call.
<div id="showhide" class="meta-info" onclick="changeclass(this);">
function changeclass(element) {
$(element).toggleClass('mynewclass');
}
Or for a slighly more jQuery way (you would run this after the DOM is loaded)
<div id="showhide" class="meta-info">
$('#showhide').click(function() {
$(this).toggleClass('mynewclass');
});
See a working example of this here: http://jsfiddle.net/S76WN/
file_get_contents() will not work if your server has allow_url_fopen turned off. Most shared web hosts have it turned off by default due to security risks. Also, in PHP6, the allow_url_fopen option will no longer exist and all functions will act as if it is permenantly set to off. So this is a very bad method to use.
Your best option to use if you are accessing the file through http is cURL
$total_ratings
is an array.
Code > Preferences > Keyboard Shortcuts
emmet wrap
you can use undocumented wm_concat
function.
select col1, wm_concat(distinct col2) col2_list
from tab1
group by col1;
this function returns clob column, if you want you can use dbms_lob.substr
to convert clob to varchar2.
function get_mime($file) {
if (function_exists("finfo_file")) {
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mime = finfo_file($finfo, $file);
finfo_close($finfo);
return $mime;
} else if (function_exists("mime_content_type")) {
return mime_content_type($file);
} else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
// http://stackoverflow.com/a/134930/1593459
$file = escapeshellarg($file);
$mime = shell_exec("file -bi " . $file);
return $mime;
} else {
return false;
}
}
For me, nothing of this does work - mime_content_type
is deprecated, finfo
is not installed, and shell_exec
is not allowed.
for those like me who are looking to send objects other than primitives, since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
If the file is coming off the disk and as others have stated, use the BaseName
and Extension
properties:
PS C:\> dir *.xlsx | select BaseName,Extension
BaseName Extension
-------- ---------
StackOverflow.com Test Config .xlsx
If you are given the file name as part of string (say coming from a text file), I would use the GetFileNameWithoutExtension
and GetExtension
static methods from the System.IO.Path class:
PS C:\> [System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
Test Config
PS H:\> [System.IO.Path]::GetExtension("Test Config.xlsx")
.xlsx
Several ways to accomplish that but be aware that your DB date_format option & date_order option settings could affect the incoming format:
Select
cast('2008-09-16' as date)
convert(date,'16/09/2008',103)
date('2008-09-16')
from dummy;
This one will preserve rectangular shape, so that subsequent transposes will get the right result:
import itertools
def transpose(list_of_lists):
return list(itertools.izip_longest(*list_of_lists,fillvalue=' '))
Use @RequestParam in your method arguments so Spring can bind them, also use the @RequestMapping.params array to narrow the method that will be used by spring. Sample code:
@RequestMapping("/userGrid",
params = {"_search", "nd", "rows", "page", "sidx", "sort"})
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "_search") String search,
@RequestParam(value = "nd") int nd,
@RequestParam(value = "rows") int rows,
@RequestParam(value = "page") int page,
@RequestParam(value = "sidx") int sidx,
@RequestParam(value = "sort") Sort sort) {
// Stuff here
}
This way Spring will only execute this method if ALL PARAMETERS are present saving you from null checking and related stuff.
For a start, your answer
variable should be of type char
, not char*
.
As for the if
statement:
if (answer == ('Y' || 'y'))
This is first evaluating 'Y' || 'y'
which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if
statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.
You could use the more correct:
if ((answer == 'Y') || (answer == 'y'))
but you really should be using:
if (toupper(answer) == 'Y')
since that's the more portable way to achieve the same end.
*a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.
I needed a function that splits a clob and makes sure the function is usable in sql.
create or replace type vchar_tab is table of varchar2(4000)
/
create or replace function split(
p_list in clob,
p_separator in varchar2 default '|'
) return vchar_tab pipelined is
C_SQL_VCHAR_MAX constant integer:=4000;
C_MAX_AMOUNT constant integer:=28000;
C_SEPARATOR_LEN constant integer:=length(p_separator);
l_amount integer:=C_MAX_AMOUNT;
l_offset integer:=1;
l_buffer varchar2(C_MAX_AMOUNT);
l_list varchar2(32767);
l_index integer;
begin
if p_list is not null then
loop
l_index:=instr(l_list, p_separator);
if l_index > C_SQL_VCHAR_MAX+1 then
raise_application_error(-20000, 'item is too large for sql varchar2: len='||(l_index-1));
elsif l_index > 0 then -- found an item, pipe it
pipe row (substr(l_list, 1, l_index-1));
l_list:=substr(l_list, l_index+C_SEPARATOR_LEN);
elsif length(l_list) > C_SQL_VCHAR_MAX then
raise_application_error(-20001, 'item is too large for sql varchar2: length exceeds '||length(l_list));
elsif l_amount = C_MAX_AMOUNT then -- more to read from the clob
dbms_lob.read(p_list, l_amount, l_offset, l_buffer);
l_list:=l_list||l_buffer;
else -- read through the whole clob
if length(l_list) > 0 then
pipe row (l_list);
end if;
exit;
end if;
end loop;
end if;
return;
exception
when no_data_needed then -- this happens when you don't fetch all records
null;
end;
/
Test:
select *
from table(split('ASDF|IUYT|KJHG|ASYD'));
Hi all Please try this property
$( "p span" ).last().addClass( "highlight" );
Thanks
Like this:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item ["title"] = id;
item ["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
Explanation
You are looking for an array of objects
. So, you create a blank array. Create an object for each input
by using 'title' and 'email' as keys. Then you add each of the objects to the array.
If you need a string, then do
jsonString = JSON.stringify(jsonObj);
Sample Output
[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}]
Put those properties files in src/test/resources
. Files in src/test/resources
are available within Eclipse automatically via eclipse:eclipse
but will not be included in the packaged JAR by Maven.
typeof will serve the purpose I think
if(typeof foo != "undefined"){}
You can also overload the Function prototype:
// partially applies the specified arguments to a function, returning a new function
Function.prototype.curry = function( ) {
var func = this;
var slice = Array.prototype.slice;
var appliedArgs = slice.call( arguments, 0 );
return function( ) {
var leftoverArgs = slice.call( arguments, 0 );
return func.apply( this, appliedArgs.concat( leftoverArgs ) );
};
};
// can do other fancy things:
// flips the first two arguments of a function
Function.prototype.flip = function( ) {
var func = this;
return function( ) {
var first = arguments[0];
var second = arguments[1];
var rest = Array.prototype.slice.call( arguments, 2 );
var newArgs = [second, first].concat( rest );
return func.apply( this, newArgs );
};
};
/*
e.g.
var foo = function( a, b, c, d ) { console.log( a, b, c, d ); }
var iAmA = foo.curry( "I", "am", "a" );
iAmA( "Donkey" );
-> I am a Donkey
var bah = foo.flip( );
bah( 1, 2, 3, 4 );
-> 2 1 3 4
*/
You can do:
$ pip install "package>=0.2,<0.3"
And pip
will look for the best match, assuming the version is at least 0.2, and less than 0.3.
This also applies to pip requirements files. See the full details on version specifiers in PEP 440.
file_get_contents()
is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.
fopen()
with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.
Try SASS http://sass-lang.com/ or LESS http://lesscss.org/
I love SASS and use it for all my projects.
The solution discussed here worked well for me. This solution uses built-in cuda functions and is very simple to implement.
The relevant code is copied below:
#include <stdio.h>
#include <stdlib.h>
__global__ void foo(int *ptr)
{
*ptr = 7;
}
int main(void)
{
foo<<<1,1>>>(0);
// make the host block until the device is finished with foo
cudaDeviceSynchronize();
// check for error
cudaError_t error = cudaGetLastError();
if(error != cudaSuccess)
{
// print the CUDA error message and exit
printf("CUDA error: %s\n", cudaGetErrorString(error));
exit(-1);
}
return 0;
}
With Python 3.2 and later, you can use int.to_bytes
and int.from_bytes
: https://docs.python.org/3/library/stdtypes.html#int.to_bytes
Another thing to try is to re-install ca-certificates
as detailed here.
# yum reinstall ca-certificates
...
# update-ca-trust force-enable
# update-ca-trust extract
And another thing to try is to explicitly allow the one site's certificate in question as described here (especially if the one site is your own server and you already have the .pem in reach).
# cp /your/site.pem /etc/pki/ca-trust/source/anchors/
# update-ca-trust extract
I was running into this exact SO error after upgrading to PHP 5.6 on CentOS 6 trying to access the server itself which has a cheapsslsecurity certificate which maybe it needed to be updated, but instead I installed a letsencrypt certificate and with these two steps above it did the trick. I don't know why the second step was necessary.
Useful Commands
View openssl version:
# openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013
View PHP cli ssl current settings:
# php -i | grep ssl
openssl
Openssl default config => /etc/pki/tls/openssl.cnf
openssl.cafile => no value => no value
openssl.capath => no value => no value
There are 4 main factors into why you would want to use synchronized
or java.util.concurrent.Lock
.
Note: Synchronized locking is what I mean when I say intrinsic locking.
When Java 5 came out with ReentrantLocks, they proved to have quite a noticeble throughput difference then intrinsic locking. If youre looking for faster locking mechanism and are running 1.5 consider j.u.c.ReentrantLock. Java 6's intrinsic locking is now comparable.
j.u.c.Lock has different mechanisms for locking. Lock interruptable - attempt to lock until the locking thread is interrupted; timed lock - attempt to lock for a certain amount of time and give up if you do not succeed; tryLock - attempt to lock, if some other thread is holding the lock give up. This all is included aside from the simple lock. Intrinsic locking only offers simple locking
Possibly, most easy way will be to use:
https://github.com/ukushu/DataExporter
especially in case of your data of datatable containing /r/n
characters or separator symbol inside of your dataTable cells. Almost all of other answers will not work with such cells.
only you need is to write the following code:
Csv csv = new Csv("\t");//Needed delimiter
var columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).ToArray();
csv.AddRow(columnNames);
foreach (DataRow row in dt.Rows)
{
var fields = row.ItemArray.Select(field => field.ToString()).ToArray;
csv.AddRow(fields);
}
csv.Save();
Why hasn't anyone suggested Activator.CreateInstance
?
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx
T obj = (T)Activator.CreateInstance(typeof(T));
import cv2
camera = cv2.VideoCapture(0)
while True:
return_value,image = camera.read()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow('image',gray)
if cv2.waitKey(1)& 0xFF == ord('s'):
cv2.imwrite('test.jpg',image)
break
camera.release()
cv2.destroyAllWindows()
Remember that
log(n!) = log(1) + log(2) + ... + log(n-1) + log(n)
You can get the upper bound by
log(1) + log(2) + ... + log(n) <= log(n) + log(n) + ... + log(n)
= n*log(n)
And you can get the lower bound by doing a similar thing after throwing away the first half of the sum:
log(1) + ... + log(n/2) + ... + log(n) >= log(n/2) + ... + log(n)
= log(n/2) + log(n/2+1) + ... + log(n-1) + log(n)
>= log(n/2) + ... + log(n/2)
= n/2 * log(n/2)
in my case, the file
command tells a wrong encoding, so i tried converting with all the possible encodings, and found out the right one.
execute this script and check the result file.
for i in `iconv -l`
do
echo $i
iconv -f $i -t UTF-8 yourfile | grep "hint to tell converted success or not"
done &>/tmp/converted
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
Just use the break statement;
For eg:this just prints "Breaking..."
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}
You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet");
by DocumentElement
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope); //call the eb service Method
} catch (Exception e) {
e.printStackTrace();
} //Next task is to get Response and format that response
SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");
for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
{
obj3 = (SoapObject) obj2.getProperty(i);
obj3.getProperty(0).toString(); //value of column 1
obj3.getProperty(1).toString(); //value of column 2
//like that you will get value from each column
}
If you have any problem regarding this you can write me..
Everyone
to the user list.Just in case you want to do this dynamically;
function enableScrollwheel(map) {
if(map) map.setOptions({ scrollwheel: true });
}
function disableScrollwheel(map) {
if(map) map.setOptions({ scrollwheel: false });
}
Sometimes you have to show something "complex" over the map (or the map is a small part of the layout), and this scroll zooming gets in the middle, but once you have a clean map, this way of zooming is nice.
Throw a new exception on server using:
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
I believe that the StatusDescription is returned to the Ajax call...
Example:
Try
Dim file As String = Request.QueryString("file")
If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist")
Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString()
sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder)
file = IO.Path.Combine(sTmpFolder, file)
If IO.File.Exists(file) Then
IO.File.Delete(file)
End If
Catch ex As Exception
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
End Try
Deprecated answer (Spring Data JPA <=1.6.x):
@Modifying
annotation to the rescue. You will need to provide your custom SQL behaviour though.
public interface UserRepository extends JpaRepository<User, Long> {
@Modifying
@Query("delete from User u where u.firstName = ?1")
void deleteUsersByFirstName(String firstName);
}
Update:
In modern versions of Spring Data JPA (>=1.7.x) query derivation for delete
, remove
and count
operations is accessible.
public interface UserRepository extends CrudRepository<User, Long> {
Long countByFirstName(String firstName);
Long deleteByFirstName(String firstName);
List<User> removeByFirstName(String firstName);
}
Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.
if(!(borrar() === false))
or
if(borrar() === true)
This is unlikely to be the source of your problem - but if you happen to be working in .NET you'll end up with a bunch of obj/
folders. Sometimes it is helpful to delete all of these obj/
folders in order to resolve a pesky build issue.
I received the same fatal: bad object HEAD
on my current branch (master) and was unable to run git status
or to checkout any other branch (I always got an error refs/remote/[branch] does not point to a valid object
).
If you want to delete all of your obj
folders, don't get lazy and allow .git/objects
into the mix. That folder is where all of the actual contents of your git commits go.
After being close to giving up I decided to look at which files were in my recycle bin, and there it was. Restored the file and my local repository was like new.
Another solution I have found to a similar error but the same error message is to increase the number of service handlers found. (My instance of this error was caused by too many connections in the Weblogic Portal Connection pools.)
SQL*Plus
and login as SYSTEM
. You should know what password you’ve used during the installation of Oracle DB XE.alter system set processes=150 scope=spfile;
in SQL*PlusFrom here:
I have had this issue before, you need more than the standard 755
or 644
permission to store the $_SESSION
information. You need to be able to write to that file as that is how it remembers.
If you want to convert string to double data type then most choose parseDouble() method. See the example code:
String str = "123.67";
double d = parseDouble(str);
You will get the value in double. See the StringToDouble tutorial at tutorialData.
nothing new but still want to share my method:
+(NSString*) getDateStringFromSrcFormat:(NSString *) srcFormat destFormat:(NSString *)
destFormat scrString:(NSString *) srcString
{
NSString *dateString = srcString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setDateFormat:@"MM-dd-yyyy"];
[dateFormatter setDateFormat:srcFormat];
NSDate *date = [dateFormatter dateFromString:dateString];
// Convert date object into desired format
//[dateFormatter setDateFormat:@"yyyy-MM-dd"];
[dateFormatter setDateFormat:destFormat];
NSString *newDateString = [dateFormatter stringFromDate:date];
return newDateString;
}
To cater for the schema as well, use this format in SQL 2014
if exists(select 1 from sys.views V inner join sys.[schemas] S on v.schema_id = s.schema_id where s.name='dbo' and v.name = 'someviewname' and v.type = 'v')
drop view [dbo].[someviewname];
go
And just throwing it out there, to do stored procedures, because I needed that too:
if exists(select 1
from sys.procedures p
inner join sys.[schemas] S on p.schema_id = s.schema_id
where
s.name='dbo' and p.name = 'someprocname'
and p.type in ('p', 'pc')
drop procedure [dbo].[someprocname];
go
All inputs should be replaced with custom directive that reads a single global variable to toggle readonly status.
// template
<your-input [readonly]="!childmessage"></your-input>
// component value
childmessage = false;
You would have got this Exception while doing a GET
on http://localhost:8080/projectname/login
As Vinay has correctly stated you can definitely use
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String displayLogin(Model model) {
model.addAttribute("login", new Login());
return "login";
}
But I am going to provide some alternative syntax which I think you were trying with Spring 3.0.
You can also achieve the above functionality with
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String displayLogin(Login loginModel) {
return "login";
}
and it login.jsp
(assuming you are using InternalResourceViewResolver
) you can have
<form:form method="POST" action="login.htm" modelAttribute="login">
Notice : modelAttribute is login
and not loginModel
. It is as per the class name you provide in argument. But if you want to use loginModel
as modelAttribute is jsp you can do the following
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String displayLogin(@ModelAttribute("loginModel")Login loginModel) {
return "login";
}
and jsp would have
<form:form method="POST" action="login.htm" modelAttribute="loginModel">
I know there are just different ways for doing the same thing. But the most important point to note here -
Imp Note: When you add your model class in your methods argument (like public String displayLogin(Login loginModel)
) it is automatically created and added to your Model object (which is why you can directly access it in JSP without manually putting it in model). Then it will search your request if request has attributes that it can map with the new ModelObject create. If yes Spring will inject values from request parameters to your custom model object class (Login in this case).
You can test this by doing
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String displayLogin(Login loginModel, Model model) {
System.out.println(model.asMap().get("login").equals(loginModel));
return "login";
}
Note : Above creating of new custom model object may not hold true if you have given @SessionAttributes({"login"})
. In this case it will get from session and populate values.
for the above problem ur password in the system should matches with the password u have passed in the program because when u run the program it checks system's password as u have given root as a user so gives u an error and at the same time the record is not deleted from the database.
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
class Delete
{
public static void main(String []k)
{
String url="jdbc:mysql://localhost:3306/student";
String user="root";
String pass="jacob234";
try
{
Connection myConnection=DriverManager.getConnection(url,user,pass);
Statement myStatement=myConnection.createStatement();
String deleteQuery="delete from students where id=2";
myStatement.executeUpdate(deleteQuery);
System.out.println("delete completed");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Keep ur system password as jacob234 and then run the code.
I would just use online tools.
first do print_r(your_array)
Second copy the result and paste in http://phillihp.com/toolz/php-array-beautifier/
Error Code
FROM
dbo.Category C LEFT OUTER JOIN
dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN
dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN
dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN
dbo.trainer ON dbo.trainer.TopicID =dbo.SubModule.subModuleID
Solution Code
FROM
dbo.Category C LEFT OUTER JOIN
dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN
dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN
dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN
dbo.trainer ON dbo.trainer.TopicID = SM.subModuleID
as you can see, in error code, dbo.SubModule
is already defined as SM, but I am using dbo.SubModule
in next line, hence there was an error.
use declared name instead of actual name. Problem solved.
Kdiff3 conflict resolution algorithm is really impressive.
Even when subversion indicates a conflict, Kdiff3 solves it automatically. There's versions for Windows and Linux with the same interface. It is possible to integrate it with Tortoise and with your linux shell.
It is in the list of my favorite open source software. One of the first tools I install in any machine.
You can configure it as the default diff tool in Subversion, Git, Mercurial, and ClearCase. It also solves almost all the ClearCase conflicts. In Windows, it has a nice integration with windows explorer: select two files and right click to compare them, or right click to 'save to later' a file, and then select another one to compare.
The merged file is editable. Has slick keyboard shortcuts.
You can also use it compare and merge directories. See:
An advanced feature is to use regular expressions for defining automatic merges.
My only annoyance is that it is a little difficult to compile if it isn't present in your favorite distro repository.
The most useful shortcut in Vim, IMHO, is the * key.
Put the cursor on a word and hit the * key and you will jump to the next instance of that word.
The # key does the same, but it jumps to the previous instance of the word.
It is truly a time saver.
In order to get "the current date" (as in today's date), you can use LocalDate.now()
and pass that into the java.sql.Date
method valueOf(LocalDate)
.
import java.sql.Date;
...
Date date = Date.valueOf(LocalDate.now());
Internal is the default modifier
To Use Jquery in Angular2(4)
Follow these setps
install the Jquery and Juqry type defination
For Jquery Installation npm install jquery --save
For Jquery Type defination Installation npm install @types/jquery --save-dev
and then simply import the jquery
import { Component } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
console.log($(window)); // jquery is accessible
}
For SQL Server 2000, this should tell you only the #temp tables in your session. (Adapted from my example for more modern versions of SQL Server here.) This assumes you don't name your tables with three consecutive underscores, like CREATE TABLE #foo___bar
:
SELECT
name = SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1),
t.id
FROM tempdb..sysobjects AS t
WHERE t.name LIKE '#%[_][_][_]%'
AND t.id =
OBJECT_ID('tempdb..' + SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1));
Note that exit codes != 0 are used to report error. So, it's better to do:
retVal=$?
if [ $retVal -ne 0 ]; then
echo "Error"
fi
exit $retVal
instead of
# will fail for error codes > 1
retVal=$?
if [ $retVal -eq 1 ]; then
echo "Error"
fi
exit $retVal
The easiest way is to use Math library.
Use Math.pow(a, b)
and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
In 6.1.0-beta.1 KeyValuePipe was introduced https://github.com/angular/angular/pull/24319
<div *ngFor="let item of {'b': 1, 'a': 1} | keyvalue">
{{ item.key }} - {{ item.value }}
</div>
Another approach is to create NgForIn
directive that will be used like:
<div *ngFor="let key in obj">
<b>{{ key }}</b>: {{ obj[key] }}
</div>
ngforin.directive.ts
@Directive({
selector: '[ngFor][ngForIn]'
})
export class NgForIn<T> extends NgForOf<T> implements OnChanges {
@Input() ngForIn: any;
ngOnChanges(changes: NgForInChanges): void {
if (changes.ngForIn) {
this.ngForOf = Object.keys(this.ngForIn) as Array<any>;
const change = changes.ngForIn;
const currentValue = Object.keys(change.currentValue);
const previousValue = change.previousValue ? Object.keys(change.previousValue) : undefined;
changes.ngForOf = new SimpleChange(previousValue, currentValue, change.firstChange);
super.ngOnChanges(changes);
}
}
}
Consider the outcome of the tool 'stat':
File: `infolog.txt'
Size: 694 Blocks: 8 IO Block: 4096 regular file
Device: 801h/2049d Inode: 11635578 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ fdr) Gid: ( 1000/ fdr)
Access: 2009-01-01 22:04:15.000000000 -0800
Modify: 2009-01-01 22:05:05.000000000 -0800
Change: 2009-01-01 22:05:05.000000000 -0800
You can see here the three dates for Access/modify/change. There is no created date. You can only really be sure when the file contents were modified (the "modify" field) or its inode changed (the "change" field).
Examples of when both fields get updated:
"Modify" will be updated if someone concatenated extra information to the end of the file.
"Change" will be updated if someone changed permissions via chmod.
Please, place your command in a parameter like the mentioned below.
Runtime.getRuntime().exec("cmd.exe /c start cmd /k \" parameter \"");
First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.
void foo(int*& x, int**& y) {
// modifying x or y here will modify a or b in main
}
int main() {
int val = 42;
int *a = &val;
int **b = &a;
foo(a, b);
return 0;
}
If you really only want to see trailing spaces, this ST2 plugin will do the trick: https://github.com/SublimeText/TrailingSpaces
Do you mean you want the script's own path so you can reference a file next to the script? Try this:
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Write-host "My directory is $dir"
You can get a lot of info from $MyInvocation and its properties.
If you want to reference a file in the current working directory, you can use Resolve-Path or Get-ChildItem:
$filepath = Resolve-Path "somefile.txt"
EDIT (based on comment from OP):
# temporarily change to the correct folder
Push-Location $folder
# do stuff, call ant, etc
# now back to previous directory
Pop-Location
There's probably other ways of achieving something similar using Invoke-Command as well.
Position absolute fixes it for me. I suggest also adding a semi-colon if you haven't already.
.container {
width: 22.5%;
size: 22.5% 22.5%;
margin-top: 0%;
border-radius: 10px;
background-color: floralwhite;
display:inline-block;
min-height: 20%;
position: absolute;
height: 50%;
}
I've used them as static variables for a function. For example, given the following C code:
int fn(int i)
{
static f = 1;
f += i;
return f;
}
I can implement the function similarly in Python:
def fn(i):
fn.f += i
return fn.f
fn.f = 1
This would definitely fall into the "abuses" end of the spectrum.
Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class
TweenAnimationBuilder<Duration>(
duration: Duration(minutes: 3),
tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
onEnd: () {
print('Timer ended');
},
builder: (BuildContext context, Duration value, Widget child) {
final minutes = value.inMinutes;
final seconds = value.inSeconds % 60;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('$minutes:$seconds',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30)));
}),
and You also get onEnd call back which notifies you when the animation completes;
here's the output
I think the BOOST_FOREACH presented above is nice and clean, however, there is another option using BOOST as well.
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
std::map<int, int> m;
std::vector<int> keys;
using namespace boost::lambda;
transform( m.begin(),
m.end(),
back_inserter(keys),
bind( &std::map<int,int>::value_type::first, _1 )
);
copy( keys.begin(), keys.end(), std::ostream_iterator<int>(std::cout, "\n") );
Personally, I don't think this approach is as clean as the BOOST_FOREACH approach in this case, but boost::lambda can be really clean in other cases.
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
You need to find the bin folder and then open a command prompt on that folder Then just type mongo.exe and press enter to start the shell
Or you can supply the full path to mongo.exe from any folder to start the shell:
c:\MongoDB\bin\mongo.exe
Then if you have multiple databases, you can do enter command >use <database_name>
to use that db
Let me know if it helps or have issues
With java lambdas (available since java 8) you can simply convert javax.swing.filechooser.FileFilter
to java.io.FileFilter
in one line.
javax.swing.filechooser.FileFilter swingFilter = new FileNameExtensionFilter("jpeg files", "jpeg");
java.io.FileFilter ioFilter = file -> swingFilter.accept(file);
new File("myDirectory").listFiles(ioFilter);
My main advice would be to steer clear of the HAVING
clause (see below):
WITH HighEarners AS
( SELECT EmpId, DeptId
FROM EMPLOYEE
WHERE Salary > 1000 ),
DeptmentHighEarnerTallies AS
( SELECT DeptId, COUNT(*) AS HighEarnerTally
FROM HighEarners
GROUP
BY DeptId )
SELECT DeptName
FROM DEPARTMENT NATURAL JOIN DeptmentHighEarnerTallies
WHERE HighEarnerTally > 2;
The very early SQL implementations lacked derived tables and HAVING
was a workaround for one of its most obvious drawbacks (how to select on the result of a set function from the SELECT
clause). Once derived tables had become a thing, the need for HAVING
went away. Sadly, HAVING
itself didn't go away (and never will) because nothing is ever removed from standard SQL. There is no need to learn HAVING
and I encourage fledgling coders to avoid using this historical hangover.
Here is the code to mock this functionality using PowerMockito API.
Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);
You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .
@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
// your testing code
}
=SUMPRODUCT((A1:A5="FRANCE")*B1:D5)
You can get access token using FB.getAuthResponse()['accessToken']
:
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Edit:
Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse();
If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log
lines or use a log-failsafe script such as:
if (typeof(console) == "undefined") { console = {}; }
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }
You can use the following to set the text from the code:
toggleButton.setText(textOff);
// Sets the text for when the button is first created.
toggleButton.setTextOff(textOff);
// Sets the text for when the button is not in the checked state.
toggleButton.setTextOn(textOn);
// Sets the text for when the button is in the checked state.
To set the text using xml, use the following:
android:textOff="The text for the button when it is not checked."
android:textOn="The text for the button when it is checked."
This information is from here
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
For Laravel 5.x we can redirect with just
return redirect()->to($url);
Aside from using %
, age of empires III
to lower case is age of empires iii
so your query should be:
select *
from games
where lower(title) like 'age of empires iii%'
You have to use setState
to set a property that will render the <Redirect>
inside your render()
method.
E.g.
class MyComponent extends React.Component {
state = {
redirect: false
}
handleSubmit () {
axios.post(/**/)
.then(() => this.setState({ redirect: true }));
}
render () {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/somewhere'/>;
}
return <RenderYourForm/>;
}
You can also see an example in the official documentation: https://reacttraining.com/react-router/web/example/auth-workflow
That said, I would suggest you to put the API call inside a service or something. Then you could just use the history
object to route programatically. This is how the integration with redux works.
But I guess you have your reasons to do it this way.
Use <location>
configuration tag, and <allow users="?"/>
to allow anonymous only or <allow users="*"/>
for all:
<configuration>
<location path="Path/To/Public/Folder">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
Too bad Oracle has limitations like these. Sure, the result for a column not in the GROUP BY would be random, but sometimes you want that. Silly Oracle, you can do this in MySQL/MSSQL.
BUT there is a work around for Oracle:
While the following line does not work
SELECT unique_id_col, COUNT(1) AS cnt FROM yourTable GROUP BY col_A;
You can trick Oracle with some 0's like the following, to keep your column in scope, but not group by it (assuming these are numbers, otherwise use CONCAT)
SELECT MAX(unique_id_col) AS unique_id_col, COUNT(1) AS cnt
FROM yourTable GROUP BY col_A, (unique_id_col*0 + col_A);
You can use a scope watch:
$scope.$watch('user', function(newValue, oldValue) {
// access new and old value here
console.log("Your former user.name was "+oldValue.name+", you're current user name is "+newValue.name+".");
});
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch
If push request is shows Rejected, then try first pull from your github account and then try push.
Ex:
In my case it was giving an error-
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/ashif8984/git-github.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
****So what I did was-****
$ git pull
$ git push
And the code was pushed successfully into my Github Account.
For those who want isoWeek
to be the default you can modify moment's behaviour as such:
const moment = require('moment');
const proto = Object.getPrototypeOf(moment());
const {startOf, endOf} = proto;
proto.startOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return startOf.call(this, period);
};
proto.endOf = function(period) {
if (period === 'week') {
period = 'isoWeek';
}
return endOf.call(this, period);
};
Now you can simply use someDate.startOf('week')
without worrying you'll get sunday or having to think about whether to use isoweek
or isoWeek
etc.
Plus you can store this in a variable like const period = 'week'
and use it safely in subtract()
or add()
operations, e.g. moment().subtract(1, period).startOf(period);
. This won't work with period being isoWeek
.