You can go to your /var/lib/pgsql/data/pg_hba.conf file and add trust in place of Ident It worked for me.
local all all trust
host all 127.0.0.1/32 trust
For further details refer to this issue Ident authentication failed for user
I got this error when trying to checkout a branch via:
git checkout branchX
which I had not checked out before. It only worked when explicitly stating the remote:
git checkout --track origin/branchX
The reason for this was, that I had 2 different remotes (origin + sth. else) configured in git config. As I didn't need the second remote, I removed it and voilá, it worked. The alternative to set the default remote via:
checkout.defaultRemote=origin
did not work for me
I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add
and then just did git reset
. This basically just added and then unstaged my changes but cleared the unmerged paths.
If you're just interested in the properties and data types from the database, you can use Model.inspect
.
irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
reset_password_token: string, reset_password_sent_at: datetime,
remember_created_at: datetime, sign_in_count: integer,
current_sign_in_at: datetime, last_sign_in_at: datetime,
current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
updated_at: datetime)"
Alternatively, having run rake db:create
and rake db:migrate
for your development environment, the file db/schema.rb
will contain the authoritative source for your database structure:
ActiveRecord::Schema.define(version: 20130712162401) do
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
end
You can also use rsync
rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out
I can confirm that this is not fixable by unregistering and registering the MSCOMCTRL.OCX like before. I have been trying to pin down which update is the source of the problem and it looks like it's either IE10 or IE10 in combination with some other update that's causing the problem. If I can get more time to invest in this I'll update my post but in the meantime uninstalling IE10 resolves the issue.
What about x *= -1;
? Do you really want a library function for this?
Since the question specified rounding for doubles specifically, this seems way simpler than dealing with big integer or excessive string or numerical operations.
"%.2f".format(0.714999999999).toDouble
Private Sub CommandButton1_Click()
Dim fso As Object
Dim fldrname As String
Dim fldrpath As String
Set fso = CreateObject("scripting.filesystemobject")
fldrname = Format(Now(), "dd-mm-yyyy")
fldrpath = "C:\Temp\" & fldrname
If Not fso.FolderExists(fldrpath) Then
fso.createfolder (fldrpath)
End If
End Sub
I was unable to resolve my problem with any of the other answers. I resolved the issue by checking to see if the host matched and returning a 403 if it did not. (I had some random website pointing to my web servers content. I'm guessing to hijack search rank)
server {
listen 443;
server_name example.com;
if ($host != "example.com") {
return 403;
}
...
}
for numerical solution, you can use fsolve:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html#scipy.optimize.fsolve
from scipy.optimize import fsolve
import math
def equations(p):
x, y = p
return (x+y**2-4, math.exp(x) + x*y - 3)
x, y = fsolve(equations, (1, 1))
print equations((x, y))
My advice is to make a big view model:
public BigViewModel
{
public LoginViewModel LoginViewModel{get; set;}
public RegisterViewModel RegisterViewModel {get; set;}
}
In your Index.cshtml, if for example you have 2 partials:
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
@model .BigViewModel
@await Html.PartialAsync("_LoginViewPartial", Model.LoginViewModel)
@await Html.PartialAsync("_RegisterViewPartial ", Model.RegisterViewModel )
and in controller:
model=new BigViewModel();
model.LoginViewModel=new LoginViewModel();
model.RegisterViewModel=new RegisterViewModel();
I created the bimap library (https://github.com/alethes/bimap) which implements a powerful, flexible and efficient JavaScript bidirectional map interface. It has no dependencies and is usable both on the server-side (in Node.js, you can install it with npm install bimap
) and in the browser (by linking to lib/bimap.js).
Basic operations are really simple:
var bimap = new BiMap;
bimap.push("k", "v");
bimap.key("k") // => "v"
bimap.val("v") // => "k"
bimap.push("UK", ["London", "Manchester"]);
bimap.key("UK"); // => ["London", "Manchester"]
bimap.val("London"); // => "UK"
bimap.val("Manchester"); // => "UK"
Retrieval of the key-value mapping is equally fast in both directions. There are no costly object/array traversals under the hood so the average access time remains constant regardless of the size of the data.
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
Assuming that I
is your input image and F
is its Fourier Transform (i.e. F = fft2(I)
)
You can use this code:
F = fftshift(F); % Center FFT
F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1
imshow(F,[]); % Display the result
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
use return before calling the function, while you click the submit button, two events(form posting as you used submit button and function call for onclick) will happen, to prevent form posting you have to return false, you have did it, also you have to specify the return i.e, to expect a value from the function,
this is a code:
input type="submit" name="continue" value="submit" onClick="**return** checkform();"
The comment by @s29 should be an answer:
One way to add a directory to the virtual environment is to install virtualenvwrapper (which is useful for many things) and then do
mkvirtualenv myenv
workon myenv
add2virtualenv . #for current directory
add2virtualenv ~/my/path
If you want to remove these path edit the file myenvhomedir/lib/python2.7/site-packages/_virtualenv_path_extensions.pth
Documentation on virtualenvwrapper can be found at http://virtualenvwrapper.readthedocs.org/en/latest/
Specific documentation on this feature can be found at http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html?highlight=add2virtualenv
The problem appears to be to find the most recent, single-commit cut between both branches on one side, and the earliest common ancestor on the other (probably the initial commit of the repo). This matches my intuition of what the "branching off" point is.
That in mind, this is not at all easy to compute with normal git shell commands, since git rev-list
-- our most powerful tool -- doesn't let us restrict the path by which a commit is reached. The closest we have is git rev-list --boundary
, which can give us a set of all the commits that "blocked our way". (Note: git rev-list --ancestry-path
is interesting but I don't how to make it useful here.)
Here is the script: https://gist.github.com/abortz/d464c88923c520b79e3d. It's relatively simple, but due to a loop it's complicated enough to warrant a gist.
Note that most other solutions proposed here can't possibly work in all situations for a simple reason: git rev-list --first-parent
isn't reliable in linearizing history because there can be merges with either ordering.
git rev-list --topo-order
, on the other hand, is very useful -- for walking commits in topographic order -- but doing diffs is brittle: there are multiple possible topographic orderings for a given graph, so you are depending on a certain stability of the orderings. That said, strongk7's solution probably works damn well most of the time. However it's slower that mine as a result of having to walk the entire history of the repo... twice. :-)
An empty array is defined by omitting values, like so:
v=[[],[]]
a=[]
b=[1,2]
a.push(b)
b==a[0]
It's suggested that you do not use return false
, as 3 things occur as a result:
So in this type of situation, you should really only use event.preventDefault();
Archive of article - jQuery Events: Stop (Mis)Using Return False
Another thing that people may find useful when using the develop
method is the --user
option to install without sudo. Ex:
python setup.py develop --user
instead of
sudo python setup.py develop
Most of the solutions here don't take into account any kind of responsive text box.
The amount of text on the last line of the paragraph is dictated by the size of the viewers browser, and so it becomes very difficult.
I think in short, if you want any kind of browser/mobile responsiveness, this isn't possible :(
declare @T table(id int)
insert into @T values
(1),
(2),
(12),
(123),
(1234)
select right('0000'+convert(varchar(4), id), 4)
from @T
Result
----
0001
0002
0012
0123
1234
The ftplib
module in the Python standard library can be compared to assembler. Use a high level library like: https://pypi.python.org/pypi/ftputil
More info
To find a compiler, you'll have 1 per .net version installed, type in a command prompt.
dir c:\Windows\Microsoft.NET\vbc.exe /a/s
Windows Forms
For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).
Compile line in a command prompt.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"
Text for VBS2EXE.vb
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
End With
sc.addcode(Scrpt)
End Sub
End Class
Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.
/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.
/win32manifest: The provided file is embedded in the manifest section of the output PE.
In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.
The command line
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"
The manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0"
processorArchitecture="*" name="VBS2EXE" type="win32" />
<description>Script to Exe</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security> <requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"
uiAccess="false" /> </requestedPrivileges>
</security> </trustInfo> </assembly>
Hopefully it will now ONLY run as admin.
Give Access To a Host's Objects
Here's an example giving the vbscript access to a .NET object.
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state"
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With
sc.addcode(Scrpt)
End Sub
End Class
To Embed version info
Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.
Download ResHacker from http://www.angusj.com/resourcehacker
Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.
Type
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"
To get the details about the error I had to add ASPNETCORE_ENVIRONMENT
environment variable for the corresponding Application Pool system.applicationHost/applicationPools
.
Note: the web application in my case was ASP.NET Core 2
web application hosted on IIS 10
. It can be done via Configuration Editor
in IIS Manager
(see Editing Collections with Configuration Editor to figure out where to find this editor in IIS Manager
).
The important difference between constructors and methods is that constructors initialize objects that are being created with the new
operator, while methods perform operations on objects that already exist.
Constructors can't be called directly; they are called implicitly when the new
keyword creates an object. Methods can be called directly on an object that has already been created with new
.
The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public
), and they have method bodies in braces.
Constructors must be named with the same name as the class name. They can't return anything, even void
(the object itself is the implicit return).
Methods must be declared to return something, although it can be void
.
@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:
$rest = curl_exec($crl);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($crl));
}
curl_close($crl);
print_r($rest);
EDIT 1
To debug you can set CURLOPT_HEADER
to true to check HTTP response with firebug::net or similar.
curl_setopt($crl, CURLOPT_HEADER, true);
EDIT 2
About Curl error: SSL certificate problem, verify that the CA cert is OK
try adding this headers (just to debug, in a production enviroment you should keep these options in true
):
curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
test
is a non-destructive and
, it doesn't return the result of the operation but it sets the flags register accordingly. To know what it really tests for you need to check the following instruction(s). Often out is used to check a register against 0, possibly coupled with a jz
conditional jump.
new Integer(i).toString()
first creates a (redundant) wrapper object around i
(which itself may be a wrapper object Integer
).
Integer.toString(i)
is preferred because it doesn't create any unnecessary objects.
My solution is to use FontAwesome and then add library images as text! You just need the Unicodes and they are found here: FontAwesome Reference File forUnicodes
Here is an example state filter:
<select name='state' style='height: 45px; font-family:Arial, FontAwesome;'>
<option value=''> All States</option>
<option value='enabled' style='color:green;'> Enabled</option>
<option value='paused' style='color:orange;'> Paused</option>
<option value='archived' style='color:red;'> Archived</option>
</select>
Note the font-family:Arial, FontAwesome; is required to be assigned in style for select like given in the example!
you can do like:
case text1:
case text4: {
//blah
break;
}
You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?
<div class="from" ng-show="message.from">From: {{message.from.name}}</div>
This should work
function validate() {
if ($('#remeber').is(':checked')) {
alert("checked");
} else {
alert("You didn't check it! Let me check it for you.");
}
}
Or you can have extension for optional text of UITextField:
how to use:
if emailTextField.text.isEmailValid() {
print("email is valid")
}else{
print("wrong email address")
}
extension:
extension Optional where Wrapped == String {
func isEmailValid() -> Bool{
guard let email = self else { return false }
let emailPattern = "[A-Za-z-0-9.-_]+@[A-Za-z0-9]+\\.[A-Za-z]{2,3}"
do{
let regex = try NSRegularExpression(pattern: emailPattern, options: .caseInsensitive)
let foundPatters = regex.numberOfMatches(in: email, options: .anchored, range: NSRange(location: 0, length: email.count))
if foundPatters > 0 {
return true
}
}catch{
//error
}
return false
}
}
To conver in Object Array
Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);
To convert as post type
Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);
To read it as List of objects TypeToken can be used
List<Post> posts=(List<Post>)gson.fromJson(jsonString,
new TypeToken<List<Post>>(){}.getType());
You can use the zfill()
method to pad a string with zeros:
In [3]: str(1).zfill(2)
Out[3]: '01'
Here is an old version I have that works on version 1.0 of the .NET framework and does not need generic types.
public static Array RemoveAt(Array source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");
Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
This is used like this:
class Program
{
static void Main(string[] args)
{
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
x[i] = (i+1).ToString();
string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);
for (int i = 0; i < y.Length; i++)
Console.WriteLine(y[i]);
}
}
make sure the Enable Column Recording
is checked.
I'm missing the translation call tr
in the answers.
One of the simplest solutions, which allows for later internationalization:
if (QMessageBox::Yes == QMessageBox::question(this,
tr("title"),
tr("Message/Question")))
{
// do stuff
}
It is generally a good Qt
habit to put code-level Strings within a tr("Your String")
call.
(QMessagebox
as above works within any QWidget
method)
EDIT:
you can use QMesssageBox
outside a QWidget
context, see @TobySpeight's answer.
If you're even outside a QObject
context, replace tr
with qApp->translate("context", "String")
- you'll need to #include <QApplication>
I put an MD5 hash of the file's contents in its URL. That way I can set a very long expiration date, and don't have to worry about users having old JS or CSS.
I also calculate this once per file at runtime (or on file system changes) so there's nothing funny to do at design time or during the build process.
If you're using ASP.NET MVC then you can check out the code in my other answer here.
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
In C++ std::string the length() and size() method gives you the number of bytes, and not necessarily the number of characters !. Same with the c-Style sizeof() function!
For most of the printable 7bit-ASCII Characters this is the same value, but for characters that are not 7bit-ASCII it's definitely not. See the following example to give you real results (64bit linux).
There is no simple c/c++ function that can really count the number of characters. By the way, all of this stuff is implementation dependent and may be different on other environments (compiler, win 16/32, linux, embedded, ...)
See following example:
#include <string>
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
/* c-Style char Array */
const char * Test1 = "1234";
const char * Test2 = "ÄÖÜ€";
const char * Test3 = "aß?";
/* c++ string object */
string sTest1 = "1234";
string sTest2 = "ÄÖÜ€";
string sTest3 = "aß?";
printf("\r\nC Style Resluts:\r\n");
printf("Test1: %s, strlen(): %d\r\n",Test1, (int) strlen(Test1));
printf("Test2: %s, strlen(): %d\r\n",Test2, (int) strlen(Test2));
printf("Test3: %s, strlen(): %d\r\n",Test3, (int) strlen(Test3));
printf("\r\nC++ Style Resluts:\r\n");
cout << "Test1: " << sTest1 << ", Test1.size(): " <<sTest1.size() <<" sTest1.length(): " << sTest1.length() << endl;
cout << "Test1: " << sTest2 << ", Test2.size(): " <<sTest2.size() <<" sTest1.length(): " << sTest2.length() << endl;
cout << "Test1: " << sTest3 << ", Test3.size(): " <<sTest3.size() << " sTest1.length(): " << sTest3.length() << endl;
return 0;
}
The output of the example is this:
C Style Results:
Test1: ABCD, strlen(): 4
Test2: ÄÖÜ€, strlen(): 9
Test3: aß?, strlen(): 10
C++ Style Results:
Test1: ABCD, sTest1.size(): 4 sTest1.length(): 4
Test2: ÄÖÜ€, sTest2.size(): 9 sTest2.length(): 9
Test3: aß?, sTest3.size(): 10 sTest3.length(): 10
If you are developing a cordova app, make sure to change the version and bundle identifier in the config.xml
as well
Easy Function in C#:
public static string GetTempFileName(string extension = "csv")
{
return Path.ChangeExtension(Path.GetTempFileName(), extension);
}
I did this with std::function and std::bind..
I wrote this EventManager class that stores a vector of handlers in an unordered_map that maps event types (which are just const unsigned int, I have a big namespace-scoped enum of them) to a vector of handlers for that event type.
In my EventManagerTests class, I set up an event handler, like this:
auto delegate = std::bind(&EventManagerTests::OnKeyDown, this, std::placeholders::_1);
event_manager.AddEventListener(kEventKeyDown, delegate);
Here's the AddEventListener function:
std::vector<EventHandler>::iterator EventManager::AddEventListener(EventType _event_type, EventHandler _handler)
{
if (listeners_.count(_event_type) == 0)
{
listeners_.emplace(_event_type, new std::vector<EventHandler>());
}
std::vector<EventHandler>::iterator it = listeners_[_event_type]->end();
listeners_[_event_type]->push_back(_handler);
return it;
}
Here's the EventHandler type definition:
typedef std::function<void(Event *)> EventHandler;
Then back in EventManagerTests::RaiseEvent, I do this:
Engine::KeyDownEvent event(39);
event_manager.RaiseEvent(1, (Engine::Event*) & event);
Here's the code for EventManager::RaiseEvent:
void EventManager::RaiseEvent(EventType _event_type, Event * _event)
{
if (listeners_.count(_event_type) > 0)
{
std::vector<EventHandler> * vec = listeners_[_event_type];
std::for_each(
begin(*vec),
end(*vec),
[_event](EventHandler handler) mutable
{
(handler)(_event);
}
);
}
}
This works. I get the call in EventManagerTests::OnKeyDown. I have to delete the vectors come clean up time, but once I do that there are no leaks. Raising an event takes about 5 microseconds on my computer, which is circa 2008. Not exactly super fast, but. Fair enough as long as I know that and I don't use it in ultra hot code.
I'd like to speed it up by rolling my own std::function and std::bind, and maybe using an array of arrays rather than an unordered_map of vectors, but I haven't quite figured out how to store a member function pointer and call it from code that knows nothing about the class being called. Eyelash's answer looks Very Interesting..
Have a go at the below as I was struggling to
bcp "SELECT CAST(BINARYCOL AS VARCHAR(MAX)) FROM OLTP_TABLE WHERE ID=123123 AND COMPANYID=123"
queryout "C:\Users\USER\Documents\ps_scripts\res.txt" -c -S myserver.db.com -U admin -P password
Reference: original post
Here is a variation of @SiegeX's answer which works with traditional Bourne shell (which has no support for +=
assignments).
password=''
while IFS= read -r -s -n1 pass; do
if [ -z "$pass" ]; then
echo
break
else
printf '*'
password="$password$pass"
fi
done
I use them all the time. The only thing I worry about is giving away IP in log files. If your function names are really good you might be making a trade secret easier to uncover. It's sort of like shipping with debug symbols, only more difficult to find things. In 99.999% of the cases nothing bad will come of it.
Also you can use 'ODBC' + 'SQL Server Import and Export Wizard'. Below link describes it: https://www.mssqltips.com/sqlservertutorial/2205/mysql-to-sql-server-data-migration/
Hovercraft Full Of Eels' answer is very good, but i had to change it a bit in order to get it working on my program:
int y1 = (int) ((this.height - 2 * BORDER_GAP) - (values.get(i) * yScale - BORDER_GAP));
instead of
int y1 = (int) (scores.get(i) * yScale + BORDER_GAP);
because if i used his way the graphic would be upside down
(you'd see it if you used hardcoded values (e.g 1,3,5,7,9) instead of random values)
I went to a bunch of SQL Server 2008 talks in PASS 2008, the only 'killer feature' from my point of view is extended events.
There are lots of great improvements, but that was the only one that got close to being a game changer for me. Table value parameters and merge were probably my next favourite. Day-to-day, IntelliSense is a huge win.. But this isn't really specific to SQL Server 2008, just the SQL Server 2008 toolset (other tools can give you similar IntelliSense against SQL Server 2005, 2000, etc.).
The KILL SESSION
command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.
Check the status to confirm:
SELECT sid, serial#, status, username FROM v$session;
You could also use IMMEDIATE clause:
ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;
The IMMEDIATE
clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.
Update If you want to kill all the sessions, you could just prepare a small script.
SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;
Spool the above to a .sql
file and execute it, or, copy paste the output and run it.
The dot operator .
does not need to be escaped inside of a character class []
.
Just to continue to all the answers that were given here, especially @James Lanes
the size of the integer type can be expressed by this formula:
total range = (2 ^ bit system)
lower limit = -(2 ^ bit system)*0.5 upper limit = ((2 ^ bit system)*0.5) - 1
Put your query (e.g. db.someCollection.find().pretty()
) to a javascript file, let's say query.js
. Then run it in your operating system's shell using command:
mongo yourDb < query.js > outputFile
Query result will be in the file named 'outputFile'.
By default Mongo prints out first 20 documents IIRC. If you want more you can define new value to batch size in Mongo shell, e.g.
DBQuery.shellBatchSize = 100
.
Converting the lists to Guava's Multiset works very well. They are compared regardless of their order and duplicate elements are taken into account as well.
static <T> boolean equalsIgnoreOrder(List<T> a, List<T> b) {
return ImmutableMultiset.copyOf(a).equals(ImmutableMultiset.copyOf(b));
}
assert equalsIgnoreOrder(ImmutableList.of(3, 1, 2), ImmutableList.of(2, 1, 3));
assert !equalsIgnoreOrder(ImmutableList.of(1), ImmutableList.of(1, 1));
As it is described at decimal as:
The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.
You can use a decimal as follows:
decimal myMoney = 300.5m;
Assuming a as double and we need a rounded number with no decimal place . Use Math.round() function.
This goes as my solution .
double a = 0.99999;
int rounded_a = (int)Math.round(a);
System.out.println("a:"+rounded_a );
Output :
a:1
http://php.net/manual/en/function.unlink.php
Unlink can safely remove a single file; just make sure the file you are removing it actually a file and not a directory ('.' or '..')
if (is_file($filepath))
{
unlink($filepath);
}
// I'd modify this slightly to be more resilient to a bad parameter
// it will handle your case and better handle other cases given to it:
int index = 25;
if (index >= 0 && index < array.Length)
{
// Array element found
}
Press Ctrl + Shift + P.
Before Eclipse Juno you need to place the cursor just beyond an opening or closing brace.
In Juno cursor can be anywhere in the code block.
You want to 'inherit' from Person's prototype object:
var Person = function (name) {
this.name = name;
this.type = 'human';
};
Person.prototype.info = function () {
console.log("Name:", this.name, "Type:", this.type);
};
var Robot = function (name) {
Person.apply(this, arguments);
this.type = 'robot';
};
Robot.prototype = Person.prototype; // Set prototype to Person's
Robot.prototype.constructor = Robot; // Set constructor back to Robot
person = new Person("Bob");
robot = new Robot("Boutros");
person.info();
// Name: Bob Type: human
robot.info();
// Name: Boutros Type: robot
after Swift 3 release, also the @escaping has to be added
func delay(_ delay: Double, closure: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
closure()
}
}
Most people already tried to answer your questions.
If you are still debugging, have you thought about using:
Double.TryParse(String, Double);
This will help you in determining what is wrong in each of the string first before you do the actual parsing.
If you have a culture-related problem, you might consider using:
Double.TryParse(String, NumberStyles, IFormatProvider, Double);
This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.
If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx
Hope that helps.
Using Sieve of Eratosthenes, computation is quite faster compare to "known-wide" prime numbers algorithm.
By using pseudocode from it's wiki (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), I be able to have the solution on C#.
public bool IsPrimeNumber(int val) {
// Using Sieve of Eratosthenes.
if (val < 2)
{
return false;
}
// Reserve place for val + 1 and set with true.
var mark = new bool[val + 1];
for(var i = 2; i <= val; i++)
{
mark[i] = true;
}
// Iterate from 2 ... sqrt(val).
for (var i = 2; i <= Math.Sqrt(val); i++)
{
if (mark[i])
{
// Cross out every i-th number in the places after i (all the multiples of i).
for (var j = (i * i); j <= val; j += i)
{
mark[j] = false;
}
}
}
return mark[val];
}
IsPrimeNumber(1000000000) takes 21s 758ms.
NOTE: Value might vary depend on hardware specifications.
If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:
'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"
Regular expressions have word boundaries, such as \b
which matches start or end of a word. Thus,
'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"
In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:
'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"
You can use try catch block to help with not found images
getProductImage(id) {
var images = require.context('@/assets/', false, /\.jpg$/)
let productImage = ''
try {
productImage = images(`./product${id}.jpg`)
} catch (error) {
productImage = images(`./no_image.jpg`)
}
return productImage
},
Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.
There is a possibility to find the PHP version of other domain by checking "X-Powered-By" response header in the browser through developer tools as other already mentioned it. If it is not exposed through the php.ini configuration there is no way you can get it unless you have access to the server.
CONVERT(DateTime, ExpireDate, 121) AS ExpireDate
will do what is needed, result:
2012-04-24 00:00:00.000
To output an object to the console, you have to stringify the object first:
success:function(data){
console.log(JSON.stringify(data));
}
from PIL import Image
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')
yields
I solved this error in pom.xml by adding the below code
spring-rest-demo org.apache.maven.plugins maven-war-plugin 2.6I had the same issue and could fix it with the solution from dougwilson: from Apr 5, 2017, Github.
index.js
to index.pug
'/'
route: res.render('index.pug')
- instead of res.render('index')
DEBUG=express:view
Now it works like a charm.It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.
Just go with Apache Commons
The code commented works as well, just choose which do you prefer
import numpy as np
from PIL import Image
def convert_from_cv2_to_image(img: np.ndarray) -> Image:
# return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
return Image.fromarray(img)
def convert_from_image_to_cv2(img: Image) -> np.ndarray:
# return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
return np.asarray(img)
This is a bit confusing, but follow these steps to save the session.
To open the session, double click on particular saved session.
The problem is that you made a Tiny mistake!
This is the JS code I use:
var jobName = document.getElementById("txtJob").value;
You should not use name="". instead use id="".
This is a limitation of XmlSerializer
. Note that BinaryFormatter
and DataContractSerializer
do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.
Since you are using xml, you might consider using DataContractSerializer
and marking your class with [DataContract]
/[DataMember
], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute]
- everything becomes elements).
Update: if you really want to know, BinaryFormatter
et al use FormatterServices.GetUninitializedObject()
to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:
Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.
I have my own serialization engine, but I don't intend making it use FormatterServices
; I quite like knowing that a constructor (any constructor) has actually executed.
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
.bashrc
is not meant to be executed but sourced. Try this instead:
. ~/.bashrc
Cheers!
Html code
<div id="coloredBy">
Colored By Santa
</div>
javascript code
document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff
I think this is very easy to use
Expanding on Ehsan's Answer....
If you are using .Net framework 4.5 then you can have a simple method to verify email address using EmailAddressAttribute
Class in code.
private static bool IsValidEmailAddress(string emailAddress)
{
return new System.ComponentModel.DataAnnotations
.EmailAddressAttribute()
.IsValid(emailAddress);
}
If you are considering REGEX to verify email address then read:
I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack
ANSWER AS OF June 2019
Install the XML Tools
plugin from the Plugin Admin (in Notepad++ 7.7 at least)
Then click Plugins -> XML Tools -> Pretty Print (XML Only with Line breaks)
That did it for me.
Here's a good mnemonic. Apply uses Arrays and Always takes one or two Arguments. When you use Call you have to Count the number of arguments.
Use the command where
in prompt to find the current executable in path
C:\> where tsc
C:\Users\user\AppData\Roaming\npm\tsc
C:\Users\user\AppData\Roaming\npm\tsc.cmd
You need to create the instance of the RuntimeException, using new
the same way you would to create an instance of most other classes:
throw new RuntimeException(msg);
Function MySheet()
' uncomment the below line to make it Volatile
'Application.Volatile
MySheet = Application.Caller.Worksheet.Name
End Function
This should be the function you are looking for
One of my options didn't have a value: <option>-----</option>
. I was trying to use if (!$(this).val()) { .. }
but I was getting strange results. Turns out if you don't have a value
attribute on your <option>
element, it returns the text inside of it instead of an empty string. If you don't want val()
to return anything for your option, make sure to add value=""
.
I had a similar problem that inspired me to develop an app that could help to capture traffic from an Android device. The app features SSH server that allows you to have traffic in Wireshark on the fly (sshdump wireshark component). As the app uses an OS feature called VPNService to capture traffic, it does not require the root access.
The app is in early Beta. If you have any issues/suggestions, do not hesitate to let me know.
You cannot concatenate a string
with an int
. You would need to convert your int
to a string
using the str
function, or use formatting
to format your output.
Change: -
print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")
to: -
print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))
or: -
print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")
or as per the comment, use ,
to pass different strings to your print
function, rather than concatenating using +
: -
print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")
.gitignore
to match the file you want to ignoregit rm --cached /path/to/file
See also:
pd.set_option('display.max_rows', 500)
df
Does not work in Jupyter!
Instead use:
pd.set_option('display.max_rows', 500)
df.head(500)
Here's a nice solution using Guava's com.google.common.primitives.Bytes
:
byte[] c = Bytes.concat(a, b);
The great thing about this method is that it has a varargs signature:
public static byte[] concat(byte[]... arrays)
which means that you can concatenate an arbitrary number of arrays in a single method call.
In Netbeans, you can instruct Maven to check javadoc on every project open :
Tools
| Options
| Java
icon | Maven
tab | Dependencies
category | Check Javadoc
drop down set to Every Project Open
.
Close and reopen Netbeans and you will see Maven download javadocs in the status bar.
Just wanted to provide a different option for this. In my case, I usually work on my individual branches then merge to master, and the individual commits I do to my local are not that important.
Due to a git hook that checks for the appropriate ticket number on Jira but was case sensitive, I was prevented from pushing my code. Also, the commit was done long ago and I didn't want to count how many commits to go back on the rebase.
So what I did was to create a new branch from latest master and squash all commits from problem branch into a single commit on new branch. It was easier for me and I think it's good idea to have it here as future reference.
From latest master:
git checkout -b new-branch
Then
git merge --squash problem-branch
git commit -m "new message"
As posted by 'Dan' in a similar thread, there is a possible fix if you're not using a sprite:
How do I make background-size work in IE?
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";
However, this scales the entire image to fit in the allocated area. So if your using a sprite, this may cause issues.
Caution
The filter has a flaw, any links inside the allocated area are no longer clickable.
My use case was to save range to variable and then select it later on
Dim targetRange As Range
Set targetRange = Sheets("Sheet").Range("Name")
Application.Goto targetRange
Set targetRangeQ = Nothing ' reset
http: //localhost:8080/web
Where
http ://localhost/web
Where
In responsive.less, you can comment out the line that imports responsive-1200px-min.less.
// Large desktops
@import "responsive-1200px-min.less";
Like so:
// Large desktops
// @import "responsive-1200px-min.less";
I just got this exact error in .Net Core 2.2 Entity Framework because I didn't have the set;
in my DbContext
like so:
public DbSet<Account> Account { get; }
changed to:
public DbSet<Account> Account { get; set;}
However, it didn't show the exception until I tried to use a linq query with Where()
and Select()
as others had mentioned above.
I was trying to set the DbSet
as read only. I'll keep trying...
Try the following:
INSERT INTO table1
SELECT 'A string', 5, idTable2 idTable2 FROM table2 WHERE ...
I came across the same problem, and found that easier way is to undock the developer tool's video to a separate window! (Using the right hand top corner toolbar button of developer tools window) and in the new window , simply say select all and copy and paste to excel!!
In a relational database system, a one-to-many
table relationship looks as follows:
Note that the relationship is based on the Foreign Key column (e.g., post_id
) in the child table.
So, there is a single source of truth when it comes to managing a one-to-many
table relationship.
Now, if you take a bidirectional entity relationship that maps on the one-to-many
table relationship we saw previously:
If you take a look at the diagram above, you can see that there are two ways to manage this relationship.
In the Post
entity, you have the comments
collection:
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
And, in the PostComment
, the post
association is mapped as follows:
@ManyToOne(
fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;
Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.
The mappedBy
attribute tells that the @ManyToOne
side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).
Now, even if you defined the mappedBy
attribute and the child-side @ManyToOne
association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.
The best way to do that is to add these two utility methods:
public void addComment(PostComment comment) {
comments.add(comment);
comment.setPost(this);
}
public void removeComment(PostComment comment) {
comments.remove(comment);
comment.setPost(null);
}
The addComment
and removeComment
methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.
The use
operator is for giving aliases to names of classes, interfaces or other namespaces. Most use
statements refer to a namespace or class that you'd like to shorten:
use My\Full\Namespace;
is equivalent to:
use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo
If the use
operator is used with a class or interface name, it has the following uses:
// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;
// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;
The use
operator is not to be confused with autoloading. A class is autoloaded (negating the need for include
) by registering an autoloader (e.g. with spl_autoload_register
). You might want to read PSR-4 to see a suitable autoloader implementation.
To cover the entire viewport, you can use:
<iframe src="mypage.html" style="position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;">
Your browser doesn't support iframes
</iframe>
And be sure to set the framed page's margins to 0, e.g., - Actually, this is not necessary with this solution.body { margin: 0; }
.
I am using this successfully, with an additional display:none
and JS to show it when the user clicks the appropriate control.
Note: To fill the parent's view area instead of the entire viewport, change position:fixed
to position:absolute
.
As of Visual Studio 2012, Microsoft no longer provides the built-in deployment package. If you wish to use this package, you will need to use VS2010.
In 2013 you have several options:
In my projects I create my own installers from scratch, which, since I do not use Windows Installer, have the advantage of being super fast, even on old machines.
That picture indeed shows that your 8081 is not in use. If suggestions above haven't helped, and your mobile device is connected to your computer via usb (and you have Android 5.0 (Lollipop) or above) you could try:
$ adb reconnect
This is not necessary in most cases, but just in case, let's reset your connection with your mobile and restart adb server. Finally:
$ adb reverse tcp:8081 tcp:8081
So, whenever your mobile device tries to access any port 8081 on itself it will be routed to the 8081 port on your PC.
Or, one could try
$ killall node
See below, would welcome anyones feedback on the below code.
not common between two arrays:
List<String> l3 =list1.stream().filter(x -> !list2.contains(x)).collect(Collectors.toList());
Common between two arrays:
List<String> l3 =list1.stream().filter(x -> list2.contains(x)).collect(Collectors.toList());
Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Browser (webapi):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
Since sudo will not work with redirection >
, I like the tee
command for this purpose
echo "" | sudo tee fileName
Following code is working for me.
Usings:
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
Code:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
string data = JObject.Parse(json)["id"].ToString();
}
}
}
//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}
The question itself has already been addressed above. Just adding part of the default values.
As per http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html
The default value of Xmx will depend on platform and amount of memory available in the system.
For references you can call
rails generate migration AddUserIdColumnToTable user:references
If in the future you need to add a general index you can launch this
rails g migration AddOrdinationNumberToTable ordination_number:integer:index
Generate code:
class AddOrdinationNumberToTable < ActiveRecord::Migration
def change
add_column :tables, :ordination_number, :integer
add_index :tables, :ordination_number, unique: true
end
end
Select multiple lines by clicking first line then holding shift and clicking last line. Then press:
CTRL+SHIFT+L
or on MAC: CMD+SHIFT+L (as per comments)
Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.
Now you can edit multiple lines, move cursors etc. for all selected lines.
For next/return events on multiple UITextfield inside UITableViewCell in this method I had taken UITextField in storyboard.
@interface MyViewController () {
NSInteger currentTxtRow;
}
@end
@property (strong, nonatomic) NSIndexPath *currentIndex;//Current Selected Row
@implementation MyViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextField *txtDetails = (UITextField *)[cell.contentView viewWithTag:100];
txtDetails.delegate = self;
txtDetails.placeholder = self.arrReciversDetails[indexPath.row];
return cell;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
self.currentIndex = [self.tableView indexPathForRowAtPoint:point];//Get Current UITableView row
currentTxtRow = self.currentIndex.row;
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
currentTxtRow += 1;
self.currentIndex = [NSIndexPath indexPathForRow:currentTxtRow inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndex];
UITextField *currentTxtfield = (UITextField *)[cell.contentView viewWithTag:100];
if (currentTxtRow < 3) {//Currently I have 3 Cells each cell have 1 UITextfield
[currentTxtfield becomeFirstResponder];
} else {
[self.view endEditing:YES];
[currentTxtfield resignFirstResponder];
}
}
To grab the text from textfield-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
switch (self.currentIndex.row) {
case 0:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
case 1:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
case 2:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
default:
break;
}
}
I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.
But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.
Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.
Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?
This seems to be related to Unable to install Python libraries
See Dominique Barton's answer:
Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.
On Debian-based systems I'd try:
apt-get update && apt-get upgrade python-pip
On Red Hat Linux-based systems:
yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)
On Mac:
sudo easy_install -U pip
You can also try to update
openssl
separately.
I have found the above answer to be the best solution, but I don't like the leading space before the percent sign. I have seen somewhat complicated solutions, but I just use this Replace addition to the answer above instead of using other rounding solutions.
String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)
I know the post is kinda old, but I have found a solution easy that works on Debian based distribution without compiling nginx from source.
First install nginx-extras package
sudo apt install nginx-extras
Then load the nginx http headers more module by editing nginx.conf and adding the following line inside the server block
load_module modules/ngx_http_headers_more_filter_module.so;
Once it's done you'll have access to both more_set_headers and more_clear_headers directives.
I found one solution. The basic idea is to make a table and in thead section place the data of header in tr and by css force to show that tr only in print not in screen then your normal header should be force to show only in screen not in print. 100% working on many pages print. sample code is here
<style>
@media screen {
.only_print{
display:none;
}
}
@media print {
.no-print {
display: none !important;
}
}
TABLE{border-collapse: collapse;}
TH, TD {border:1px solid grey;}
</style>
<div class="no-print"> <!-- This is header for screen and will not be printed -->
<div>COMPANY NAME FOR SCREEN</div>
<div>DESCRIPTION FOR SCREEN</div>
</div>
<table>
<thead>
<tr class="only_print"> <!-- This is header for print and will not be shown on screen -->
<td colspan="100" style="border: 0px;">
<div>COMPANY NAME FOR PRINT</div>
<div>DESCRIPTION FOR PRINT</div>
</td>
</tr>
<!-- From here Actual Data of table start -->
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1-1</td>
<td>1-2</td>
<td>1-3</td>
</tr>
<tr>
<td>2-1</td>
<td>2-2</td>
<td>2-3</td>
</tr>
</tbody>
</table>
You can use a fieldset tag.
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form>_x000D_
<fieldset>_x000D_
<legend>Personalia:</legend>_x000D_
Name: <input type="text"><br>_x000D_
Email: <input type="text"><br>_x000D_
Date of birth: <input type="text">_x000D_
</fieldset>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Check this link: HTML Tag
There are multiple answers to this question, partly due to ambiguous question - the title is talking about classes loaded by the JVM, whereas the contents of the question says "may or may not be loaded by the JVM".
Assuming that OP needs classes that are loaded by the JVM by a given classloader, and only those classes - my need as well - there is a solution (elaborated here) that goes like this:
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
public class CPTest {
private static Iterator list(ClassLoader CL)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
Class CL_class = CL.getClass();
while (CL_class != java.lang.ClassLoader.class) {
CL_class = CL_class.getSuperclass();
}
java.lang.reflect.Field ClassLoader_classes_field = CL_class
.getDeclaredField("classes");
ClassLoader_classes_field.setAccessible(true);
Vector classes = (Vector) ClassLoader_classes_field.get(CL);
return classes.iterator();
}
public static void main(String args[]) throws Exception {
ClassLoader myCL = Thread.currentThread().getContextClassLoader();
while (myCL != null) {
System.out.println("ClassLoader: " + myCL);
for (Iterator iter = list(myCL); iter.hasNext();) {
System.out.println("\t" + iter.next());
}
myCL = myCL.getParent();
}
}
}
One of the neat things about it is that you can choose an arbitrary classloader you want to check. It is however likely to break should internals of classloader class change, so it is to be used as one-off diagnostic tool.
To reload, you can try this:
window.location.reload(true);
C++98 doesn't provide a direct syntax for anything but zeroing (or for non-POD elements, value-initializing) the array. For that you just write C(): arr() {}
.
I thing Roger Pate is wrong about the alleged limitations of C++0x aggregate initialization, but I'm too lazy to look it up or check it out, and it doesn't matter, does it? EDIT: Roger was talking about "C++03", I misread it as "C++0x". Sorry, Roger. ?
A C++98 workaround for your current code is to wrap the array in a struct
and initialize it from a static constant of that type. The data has to reside somewhere anyway. Off the cuff it can look like this:
class C
{
public:
C() : arr( arrData ) {}
private:
struct Arr{ int elem[3]; };
Arr arr;
static Arr const arrData;
};
C::Arr const C::arrData = {{1, 2, 3}};
Try this and don't add anything Order allow,deny
and others:
AddHandler cgi-script .cgi .py
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Require all granted
Allow from all
</Directory>
sudo a2enmod cgi
sudo service apache2 restart
Terminology : The difference between TRUE north and Magnetic North is known as "variation" not declination. The difference between what your compass reads and the magnetic heading is known as "deviation" and varies with heading. A compass swing identifies device errors and allows corrections to be applied if the device has correction built in. A magnetic compass will have a deviation card which describes the device error on any heading.
Declination : A term used in Astro navigation : Declination is like latitude. It reports how far a star is from the celestial equator. To find the declination of a star follow an hour circle "straight down" from the star to the celestial equator. The angle from the star to the celestial equator along the hour circle is the star's declination.
There is a typo error in define arguments, change DB_HOST into DB_SERVER and DB_USER into DB_USERNAME:
<?php
define("DB_SERVER", "localhost");
define("DB_USERNAME", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "databasename");
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
?>
Scan the string for ://
. If it does not have it, prepend http://
to the string... Everything else just use the string as is.
This will work unless you have a rubbish input string.
Some things that seemed to help using VS2010:
From the MySql site.
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
First, convert the timestamp using the built-in eloquent functionality, as described in this answer.
Then you can just use Carbon's min()
or max()
function for comparison. For example:
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $dt1->min($dt2);
This will echo
the lesser of the two dates, which in this case is $dt1
.
If you are simply after a pretty solution and don't need to save a few nanoseconds, how about some LINQ sugar?
var input = "test1test2test3";
var replacements = new Dictionary<string, string> { { "1", "*" }, { "2", "_" }, { "3", "&" } };
var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Read the input continuously within the loop so that the variable line
is assigned a value other than the initial value
while ((line = br.readLine()) !=null) {
...
}
Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files
function redirectHome($theMsg, $url = null, $seconds = 3) {
if ($url === null) {
$url = 'index.php';
$link = 'Homepage';
} else {
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] !== '') {
$url = $_SERVER['HTTP_REFERER'];
$link = 'Previous Page';
} else {
$url = 'index.php';
$link = 'Homepage';
}
}
echo $theMsg;
echo "<div class='alert alert-info'>You Will Be Redirected to $link After $seconds Seconds.</div>";
header("refresh:$seconds;url=$url");
exit();
}
This solution is easy to use, it is used as a normal dictionary, but you can use the sum function.
class SumDict(dict):
def __add__(self, y):
return {x: self.get(x, 0) + y.get(x, 0) for x in set(self).union(y)}
A = SumDict({'a': 1, 'c': 2})
B = SumDict({'b': 3, 'c': 4}) # Also works: B = {'b': 3, 'c': 4}
print(A + B) # OUTPUT {'a': 1, 'b': 3, 'c': 6}
Fastest that I found here for PHP 7.2
on Ububntu 18.04
preg_replace('/^(\w+\\\)*/', '', static::class)
Disclaimer: I have been exposed to a significant amount of F77
The modern equivalent of goto
(arguable, only my opinion, etc) is explicit exception handling:
Edited to highlight the code reuse better.
Pretend pseudocode in a fake python-like language with goto
:
def myfunc1(x)
if x == 0:
goto LABEL1
return 1/x
def myfunc2(z)
if z == 0:
goto LABEL1
return 1/z
myfunc1(0)
myfunc2(0)
:LABEL1
print 'Cannot divide by zero'.
Compared to python:
def myfunc1(x):
return 1/x
def myfunc2(y):
return 1/y
try:
myfunc1(0)
myfunc2(0)
except ZeroDivisionError:
print 'Cannot divide by zero'
Explicit named exceptions are a significantly better way to deal with non-linear conditional branching.
You have several options ;)
$memcache_enabled = class_exists('Memcache');
$memcache_enabled = extension_loaded('memcache');
$memcache_enabled = function_exists('memcache_connect');
$(document.body)
is using the global reference document
to get a reference to the body
, whereas $('body')
is a selector in which jQuery will get the reference to the <body>
element on the document
.
No major difference that I can see, not any noticeable performance gain from one to the other.
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Since Java 11:
String[] strings = list.toArray(String[]::new);
let course = {
name: 'Angular',
};
let newCourse= Object.assign({}, course);
newCourse.name= 'React';
console.log(course.name); // writes Angular
console.log(newCourse.name); // writes React
For Nested Object we can use of 3rd party libraries, for deep copying objects. In case of lodash, use _.cloneDeep()
let newCourse= _.cloneDeep(course);
To quickly and safely compare any two files:
if cmp --silent -- "$FILE1" "$FILE2"; then
echo "files contents are identical"
else
echo "files differ"
fi
It's readable, efficient, and works for any file names including "` $()
It's not good for several reasons:
eval
The simplest thing would be to add a name
attribute to your <a>
element, then you could do:
document.myelement.onclick = function() {
window.popup('/map/', 300, 300, 'map');
return false;
};
although modern best practise would be to use an id
instead of a name, and use addEventListener()
instead of using onclick
since that allows you to bind multiple functions to a single event.
You can just make the field readonly while form loading. While the field get focus you can change that field to be editable. This is simplest way to avoid auto complete.
<input name="password" id="password" type="password" autocomplete="false" readonly onfocus="this.removeAttribute('readonly');" />
To change the remote upstream:
git remote set-url origin <url>
To add more upstreams:
git remote add newplace <url>
So you can choose where to work
git push origin <branch>
or git push newplace <branch>
To further compliment Andrés Torres Marroquín and Leo Dabus, I have a version that preserves fractional seconds. I can't find it documented anywhere, but Apple truncate fractional seconds to the microsecond (3 digits of precision) on both input and output (even though specified using SSSSSSS, contrary to Unicode tr35-31).
I should stress that this is probably not necessary for most use cases. Dates online do not typically need millisecond precision, and when they do, it is often better to use a different data format. But sometimes one must interoperate with a pre-existing system in a particular way.
Xcode 8/9 and Swift 3.0-3.2
extension Date {
struct Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXXXX"
return formatter
}()
}
var iso8601: String {
// create base Date format
var formatted = DateFormatter.iso8601.string(from: self)
// Apple returns millisecond precision. find the range of the decimal portion
if let fractionStart = formatted.range(of: "."),
let fractionEnd = formatted.index(fractionStart.lowerBound, offsetBy: 7, limitedBy: formatted.endIndex) {
let fractionRange = fractionStart.lowerBound..<fractionEnd
// replace the decimal range with our own 6 digit fraction output
let microseconds = self.timeIntervalSince1970 - floor(self.timeIntervalSince1970)
var microsecondsStr = String(format: "%.06f", microseconds)
microsecondsStr.remove(at: microsecondsStr.startIndex)
formatted.replaceSubrange(fractionRange, with: microsecondsStr)
}
return formatted
}
}
extension String {
var dateFromISO8601: Date? {
guard let parsedDate = Date.Formatter.iso8601.date(from: self) else {
return nil
}
var preliminaryDate = Date(timeIntervalSinceReferenceDate: floor(parsedDate.timeIntervalSinceReferenceDate))
if let fractionStart = self.range(of: "."),
let fractionEnd = self.index(fractionStart.lowerBound, offsetBy: 7, limitedBy: self.endIndex) {
let fractionRange = fractionStart.lowerBound..<fractionEnd
let fractionStr = self.substring(with: fractionRange)
if var fraction = Double(fractionStr) {
fraction = Double(floor(1000000*fraction)/1000000)
preliminaryDate.addTimeInterval(fraction)
}
}
return preliminaryDate
}
}
-- If no parameters need to be passed to a procedure, simply:
BEGIN
MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;
Most (if not all) of these answers assume you are happy to install packages globally. This answer is for you if you:
(Note: this answer adds a python2 kernel to a python3-jupyter install, but it's conceptually easy to swap things around.)
Prerequisites
Create a python3 venv and install jupyter
python3 -m venv .venv
. .venv/bin/activate
pip install jupyterlab
. This will create locally all the essential infrastructure for running notebooks. $PWD/.venv/share/jupyter/kernels/python3/
. If you want to install and run jupyter elsewhere, and only use this venv for organizing all your kernels, then you only need: pip install ipykernel
jupyter lab
(and go to your browser to the url displayed in the console). So far, you'll only see one kernel option called 'Python 3'. (This name is determined by the display_name
entry in your kernel.json
file.)Add a python2 kernel
ctrl-c
deactivate
virtualenv -p python2 .venv2
. .venv2/bin/activate
pip install ipykernel
. This will also generate default kernel specs for this python2 venv in .venv2/share/jupyter/kernels/python2
python -m ipykernel install --prefix=$PWD/.venv
. This basically just copies the dir $PWD/.venv2/share/jupyter/kernels/python2
to $PWD/.venv/share/jupyter/kernels/
deactivate; . .venv/bin/activate; jupyter lab
. If all went well, you'll see a Python 2
option in your list of kernels. You can test that they're running real python2/python3 interpreters by their handling of a simple print 'Hellow world'
vs print('Hellow world')
command.TL;DR
R -e "install.packages('IRkernel',repos='https://cran.mtu.edu/')"
. (This will install to your standard R-packages location; for home-brewed-installed R on a Mac, this will look like /usr/local/Cellar/r/3.5.2_2/lib/R/library/IRkernel
.)R -e "IRkernel::installspec(prefix=paste(getwd(),'/.venv',sep=''))"
. If you now look in $PWD/.venv/share/jupyter/kernels/
you'll find an ir
directory with kernel.json
file that looks something like this:{
"argv": ["/usr/local/Cellar/r/3.5.2_2/lib/R/bin/R", "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"],
"display_name": "R",
"language": "R"
}
In summary, a kernel just 'is' an invocation of a language-specific executable from a kernel.json
file that jupyter looks for in the .../share/jupyter/kernels
dir and lists in its interface; in this case, R is being called to run the function IRkernel::main()
, which will send messages back and forth to the Jupiter server. Likewise, the python2 kernel just 'is' an invocation of the python2 interpreter with module ipykernel_launcher
as seen in .venv/share/jupyter/kernels/python2/kernel.json
, etc.
Here is a script if you want to run all of these instructions in one fell swoop.
Just use the Json.NET library. It lets you parse Json format strings very easily:
JObject o = JObject.Parse(@"
{
""something"":""value"",
""jagged"":
{
""someother"":""value2""
}
}");
string something = (string)o["something"];
Documentation: Parsing JSON Object using JObject.Parse
First I executed:
sudo chown -R $(whoami):admin /usr/local
Then:
cd $(brew --prefix) && git fetch origin && git reset --hard origin/master
if you are using class component, you are most likely to use GSerjo suggestion. Pass in the params via <Route>
props to your target component:
exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />}
Setting "expires" to a past date is the standard way to delete a cookie.
Your problem is probably because the date format is not conventional. IE probably expects GMT only.
You can compile with either Cygwin's g++
or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll
(and others) PATH to the system Windows PATH, before any cygwin style paths.
Thus add: ;C:\cygwin64\bin
to the end of your Windows system PATH
variable.
Also, to compile for use in CMD or PowerShell, you may need to use:
x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe
(This invokes the cross-compiler, if installed.)
In my case, I put a mistake in my web.config
file. The application key somehow was put under the <appSettings> tag. But I wonder why it doesn't display a configuration error. The error 500 is too generic for investigating the problem.
mklbtz is correct about exponentiation by squaring being the standard algorithm for computing integer powers, but the tail-recursive implementation of the algorithm seems a bit confusing. See http://www.programminglogic.com/fast-exponentiation-algorithms/ for a non-recursive implementation of exponentiation by squaring in C. I've attempted to translate it to Swift here:
func expo(_ base: Int, _ power: Int) -> Int {
var result = 1
while (power != 0){
if (power%2 == 1){
result *= base
}
power /= 2
base *= base
}
return result
}
Of course, this could be fancied up by creating an overloaded operator to call it and it could be re-written to make it more generic so it worked on anything that implemented the IntegerType
protocol. To make it generic, I'd probably start with something like
func expo<T:IntegerType>(_ base: T, _ power: T) -> T {
var result : T = 1
But, that is probably getting carried away.
If you restructured your date format into YYYY/MM/DD then you can use this simple string ordering to achieve the formating you need.
Alternatively, using the SUBSTR(store_name,start,length) command you should be able to restructure the sorting term into the above format
perhaps using the following
SELECT *
FROM vw_view
ORDER BY SUBSTR(EventDate,6,4) + SUBSTR(EventDate, 0, 5) DESC
To add new changes to a new branch and push to remote:
git branch branch/name
git checkout branch/name
git push origin branch/name
Often times I forget to add the origin part to push and get confused why I don't see the new branch/commit in bitbucket
Just some examples on usage of array_split
, split
, hsplit
and vsplit
:
n [9]: a = np.random.randint(0,10,[4,4])
In [10]: a
Out[10]:
array([[2, 2, 7, 1],
[5, 0, 3, 1],
[2, 9, 8, 8],
[5, 7, 7, 6]])
Some examples on using array_split
:
If you give an array or list as second argument you basically give the indices (before) which to 'cut'
# split rows into 0|1 2|3
In [4]: np.array_split(a, [1,3])
Out[4]:
[array([[2, 2, 7, 1]]),
array([[5, 0, 3, 1],
[2, 9, 8, 8]]),
array([[5, 7, 7, 6]])]
# split columns into 0| 1 2 3
In [5]: np.array_split(a, [1], axis=1)
Out[5]:
[array([[2],
[5],
[2],
[5]]),
array([[2, 7, 1],
[0, 3, 1],
[9, 8, 8],
[7, 7, 6]])]
An integer as second arg. specifies the number of equal chunks:
In [6]: np.array_split(a, 2, axis=1)
Out[6]:
[array([[2, 2],
[5, 0],
[2, 9],
[5, 7]]),
array([[7, 1],
[3, 1],
[8, 8],
[7, 6]])]
split
works the same but raises an exception if an equal split is not possible
In addition to array_split
you can use shortcuts vsplit
and hsplit
.
vsplit
and hsplit
are pretty much self-explanatry:
In [11]: np.vsplit(a, 2)
Out[11]:
[array([[2, 2, 7, 1],
[5, 0, 3, 1]]),
array([[2, 9, 8, 8],
[5, 7, 7, 6]])]
In [12]: np.hsplit(a, 2)
Out[12]:
[array([[2, 2],
[5, 0],
[2, 9],
[5, 7]]),
array([[7, 1],
[3, 1],
[8, 8],
[7, 6]])]
Even more simple if you accept using pandas :
import pandas
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
df = pandas.DataFrame(result, index=[0])
print df
gives :
0 1 2 3 4 5 6
0 1.118175 0.556608 0.471827 0.487167 1 0.139508 0.209416
First Install React dev tools if not installed and then use the run below code in the browser console :
__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.get(1).version
it is working in my google chrome browser version 11.0.696.60
I created a simple page with no other items just basic tags and no separate CSS file and got an image
this is what i setup:
<div id="placeholder" style="width: 60px; height: 60px; border: 1px solid black; background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div>
I put an id just in case there was a hidden id tag and it works
To conditionally check the length of the string, use CASE
.
SELECT CASE WHEN LEN(comments) <= 60
THEN comments
ELSE LEFT(comments, 60) + '...'
END As Comments
FROM myView
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
then just call monthNames[1] that will be Feb
So you can always make something like
monthNumber = "5";
jQuery('#element').text(monthNames[monthNumber])
Maybe I've late a bit, but you really should try to use json library from play framework. You could look at documentation. In current 2.1.1 release you could not separately use it without whole play 2, so dependency will looks like this:
val typesaferepo = "TypeSafe Repo" at "http://repo.typesafe.com/typesafe/releases"
val play2 = "play" %% "play" % "2.1.1"
It will bring you whole play framework with all stuff on board.
But as I know guys from Typesafe have a plan to separate it in 2.2 release. So, there is standalone play-json from 2.2-snapshot.
npm install sloc -g
git clone --depth 1 https://github.com/vuejs/vue/
sloc ".\vue\src" --format cli-table
rm -rf ".\vue\"
npm install sloc -g
git clone --depth 1 https://github.com/facebook/react/
sloc ".\react\src" --format cli-table
sloc supports formatting the output as a cli-table
, as json
or csv
. Regular expressions can be used to exclude files and folders (Further information on npm).
Powershell: rm -r -force ".\react\"
or on Mac/Unix: rm -rf ".\react\"
Screenshots of the executed steps (cli-table):
sloc output (no arguments):
It is also possible to get details for every file with the --details
option:
sloc ".\react\src" --format cli-table --details
I'm on OSX, I was using Android Studio instead of ADT and I had this issue, my problem was being behind a proxy with authentication, for what ever reason, In Android SDK Manager Window, under Preferences -> Others, I needed to uncheck the
"Force https://... sources to be fetched using http://..."
Also, there was no place to put the proxy credentials, but it will prompt you for them.
Update 2020:
Unfortunately this is still happening:
I still don't know why, it would allow me to install without checking for dependencies. I have become accustomed to this kind of behavior when I am installing any application and to not see it is annoying. I suppose I should leave this personal opinions out of my solution but I have had to install this multiple times and have comes across some kind of dependency issue.
I solved this problem. You can use Support library and ViewPager
. If you don't need swiping by gesture you can disable swiping. So here is some code to improve my solution:
public class TestFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag, container, false);
final ArrayList<Fragment> list = new ArrayList<Fragment>();
list.add(new TrFrag());
list.add(new TrFrag());
list.add(new TrFrag());
ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list.size();
}
});
return v;
}
}
P.S.It is ugly code for test, but it improves that it is possible.
P.P.S Inside fragment ChildFragmentManager
should be passed to ViewPagerAdapter
Shortest form for small text files (in Kotlin):
val reader = FileReader(path)
val txt = reader.readText()
reader.close()
There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):
word = 'hello'
so_far = "-" * len(word) # Create variable so_far to contain the current guess
while word != so_far: # if still not complete
print(so_far)
guess = input('>> ') # get a char guess
if guess in word:
print("\nYes!", guess, "is in the word!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess # fill the position with new value
else:
new += so_far[i] # same value as before
so_far = new
else:
print("try_again")
print('finish')
I tried to write it for py3k with a py2k ide, be careful with errors.
Find list of Nearby Bluetooth Devices:
Find Screenshot for the same.
MainActivity.java:
public class MainActivity extends ActionBarActivity {
private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, mDeviceList));
}
}
};
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bluetoothdemo.MainActivity" >
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"/>
</RelativeLayout>
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Note:
Please make sure that you ask Location permission to your user and turn GPS On.
Reason: From Android 6.0 you need Location permission for Bluetooth Discovery.
More reference:
Done
1.
function setColor(e) {
var target = e.target,
count = +target.dataset.count;
target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
target.dataset.count = count === 1 ? 0 : 1;
/*
() : ? - this is conditional (ternary) operator - equals
if (count === 1) {
target.style.backgroundColor = "#7FFF00";
target.dataset.count = 0;
} else {
target.style.backgroundColor = "#FFFFFF";
target.dataset.count = 1;
}
target.dataset - return all "data attributes" for current element,
in the form of object,
and you don't need use global variable in order to save the state 0 or 1
*/
}
<input
type="button"
id="button"
value="button"
style="color:white"
onclick="setColor(event)";
data-count="1"
/>
2.
function setColor(e) {
var target = e.target,
status = e.target.classList.contains('active');
e.target.classList.add(status ? 'inactive' : 'active');
e.target.classList.remove(status ? 'active' : 'inactive');
}
.active {
background-color: #7FFF00;
}
.inactive {
background-color: #FFFFFF;
}
<input
type="button"
id="button"
value="button"
style="color:white"
onclick="setColor(event)"
/>
Here's a hint, you have a graph of nodes in the linked list, and you always keep a reference to head which is the first node in the linkedList.
next points to the next node in the linkedlist, so when next is null you are at the end of the list.
Just add the directory on the command line:
svn checkout svn://192.168.1.1/projectname/ target-directory/
I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."
INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there
Using jQuery:
$(document).ready(function(){
$('div').click(function(){
$(this).toggleClass('clicked');
});
});?
In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/
The following worked for me:
Put your curl statement in a script named abc.sh
Now run:
sh abc.sh 1>stdout_output 2>stderr_output
You will get your curl's results in stdout_output
and the progress info in stderr_output
.
I don't exactly know what causes that, but I solve it this way.
Reinstall whole project but remember that webpack-dev-server must be globally installed.
I walk through some server errors like webpack cant be found, so I linked Webpack using link command.
In output Resolving some absolute path issues.
In devServer object: inline: false
webpack.config.js
module.exports = {
entry: "./src/js/main.js",
output: {
path:__dirname+ '/dist/',
filename: "bundle.js",
publicPath: '/'
},
devServer: {
inline: false,
contentBase: "./dist",
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude:/(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
package.json
{
"name": "react-flux-architecture-es6",
"version": "1.0.0",
"description": "egghead",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"repository": {
"type": "git",
"url": "git+https://github.com/cichy/react-flux-architecture-es6.git"
},
"keywords": [
"React",
"flux"
],
"author": "Jaroslaw Cichon",
"license": "ISC",
"bugs": {
"url": "https://github.com/cichy/react-flux-architecture-es6/issues"
},
"homepage": "https://github.com/cichy/react-flux-architecture-es6#readme",
"dependencies": {
"flux": "^3.1.2",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "^3.0.2"
},
"devDependencies": {
"babel-core": "^6.22.1",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0"
}
}
I think this is a better way to unambiguously identify a clone of a repository.
git config --get remote.origin.url
and checking to make sure that the origin matches ssh://your/repo
.
use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
The instantclient works only by defining the folder in the windows PATH environment variable. But you can "install" manually to create some keys in the Windows registry. How?
1) Download instantclient (http://www.oracle.com/technetwork/topics/winsoft-085727.html)
2) Unzip the ZIP file (eg c:\oracle\instantclient).
3) Include the above path in the PATH.
4) Create the registry key:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE]
5) In the above registry key, create a sub-key starts with "KEY_" followed by the name of the installation you want:
[HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\KEY_INSTANTCLIENT]
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE\KEY_INSTANTCLIENT]
6) Now create at least three string values ??in the above key:
NLS_LANG = BRAZILIAN PORTUGUESE_BRAZIL.WE8MSWIN1252
(complete list here: http://docs.oracle.com/cd/B19306_01/install.102/b14317/gblsupp.htm)ORACLE_HOME = c:\oracle\instantclient
(the same folder in PATH)ORACLE_HOME_NAME = MY_INSTANTCLIENT
(choose any name)For those who use Quest SQL Navigator or Quest Toad for Oracle will see that it works. Displays the message "Home is valid.":
The registry keys are now displayed for selecting the oracle client:
ok so I used this:
public partial class Form1 : Form
{
private void Button_Click(object sender, EventArgs e)
{
Form2 myForm = new Form2();
this.Hide();
myForm.ShowDialog();
this.Close();
}
}
This seems to be working fine but the first form is just hidden and it can still generate events. the "this.Close()" is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with
this.Show();
Best of luck!
Try to check at Settings > Advanced. At Valid OAuth redirect URIs, make sure you have a correct domain.
Hope it works.
Check the properties of App.xaml. Is the Build Action
still ApplicationDefinition
?
An additional simple solution
HTML:
<div id="d1">
<div id="d2">
Text
</div>
</div>
CSS:
#d1{
position:absolute;
top:100px;left:100px;
}
#d2{
border:1px solid black;
height:50px; width:50px;
display:table-cell;
vertical-align:middle;
text-align:center;
}
Oh My Goodness! Look at the size of my temporary table space! Or... how to shrink temporary tablespaces in Oracle.
Yes I ran a query to see how big my temporary tablespace is:
SQL> SELECT tablespace_name, file_name, bytes
2 FROM dba_temp_files WHERE tablespace_name like 'TEMP%';
TABLESPACE_NAME FILE_NAME BYTES
----------------- -------------------------------- --------------
TEMP /the/full/path/to/temp01.dbf 13,917,200,000
The first question you have to ask is why the temporary tablespace is so large. You may know the answer to this off the top of your head. It may be due to a large query that you just run with a sort that was a mistake (I have done that more than once.) It may be due to some other exceptional circumstance. If that is the case then all you need to do to clean up is to shrink the temporary tablespace and move on in life.
But what if you don't know? Before you decide to shrink you may need to do some investigation into the causes of the large tablespace. If this happens on a regular basis then it is possible that your database just needs that much space.
The dynamic performance view
V$TEMPSEG_USAGE
can be very useful in determining the cause.
Maybe you just don't care about the cause and you just need to shrink it. This is your third day on the job. The data in the database is only 200MiB if data and the temporary tablespace is 13GiB - Just shrink it and move on. If it grows again then we will look into the cause. In the mean time I am out of space on that disk volume and I just need the space back.
Let's take a look at shrinking it. It will depend a little on what version
of Oracle you are running and how the temporary tablespace was set up.
Oracle will do it's best to keep you from making any horrendous mistakes
so we will just try the commands and if they don't work we will shrink
in a new way.
First let's try to shrink the datafile. If we can do that then we get back the space and we can worry about why it grew tomorrow.
SQL>
SQL> alter database tempfile '/the/full/path/to/temp01.dbf' resize 256M;
alter database tempfile '/the/full/path/to/temp01.dbf' resize 256M
*
ERROR at line 1:
ORA-03297: file contains used data beyond requested RESIZE value
Depending on the error message you may want to try this with different sizes that are smaller than the current site of the file. I have had limited success with this. Oracle will only shrink the file if the temporary tablespace is at the head of the file and if it is smaller than the size you specify. Some old Oracle documentation (they corrected this) said that you could issue the command and the error message would tell you what size you could shrink to. By the time I started working as a DBA this was not true. You just had to guess and re-run the command a bunch of times and see if it worked.
Alright. That didn't work. How about this.
SQL> alter tablespace YOUR_TEMP_TABLESPACE_NAME shrink space keep 256M;
If you are in 11g (Maybee in 10g too) this is it! If it works you may want to go back to the previous command and give it some more tries.
But what if that fails. If the temporary tablespace is the default temporary that was set up when the database was installed then you may need to do a lot more work. At this point I usually re-evaluate if I really need that space back. After all disk space only costs $X.XX a GiB. Usually I don't want to make changes like this during production hours. That means working at 2AM AGAIN! (Not that I really object to working at 2AM - it is just that... Well I like to sleep too. And my wife likes to have me at home at 2AM... not roaming the downtown streets at 4AM trying to remember where I parked my car 3 hours earlier. I have heard of that "telecommuting" thing. I just worry that I will get half way through and then my internet connectivity will fail - then I have to rush downtown to fix it all before folks show up in the morning to use the database.)
Ok... Back to the serious stuff... If the temporary tablespace you want to shrink is your default temporary tablespace, you will have to first create a new temporary tablespace, set it as the default temporary tablespace then drop your old default temporary tablespace and recreate it. Afterwords drop the second temporary table created.
SQL> CREATE TEMPORARY TABLESPACE temp2
2 TEMPFILE '/the/full/path/to/temp2_01.dbf' SIZE 5M REUSE
3 AUTOEXTEND ON NEXT 1M MAXSIZE unlimited
4 EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
Tablespace created.
SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE temp2;
Database altered.
SQL> DROP TABLESPACE temp INCLUDING CONTENTS AND DATAFILES;
Tablespace dropped.
SQL> CREATE TEMPORARY TABLESPACE temp
2 TEMPFILE '/the/full/path/to/temp01.dbf' SIZE 256M REUSE
3 AUTOEXTEND ON NEXT 128M MAXSIZE unlimited
4 EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
Tablespace created.
SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE temp;
Database altered.
SQL> DROP TABLESPACE temp2 INCLUDING CONTENTS AND DATAFILES;
Tablespace dropped.
Hopefully one of these things will help!
For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. In addition if you forgot one of the steps I have listed the error that will be thrown.
Enable the xp_cmdshell procedure
Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.*
Create a login for the non-sysadmin user that has public access to the master database
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*
Grant EXEC permission on the xp_cmdshell stored procedure
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*
Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1 The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.*
It would seem from your error that either step 2 or 3 was missed. I am not familiar with clusters to know if there is anything particular to that setup.
To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.
You could try adding an<hr>
and styling that. Its a minimal markup change but seems to need less css so that might do the trick.
fiddle:
Using dataset with default values is one way, but you must use query for Available values and for Default Values, if values are hard coded in Available values tab, then you must define default values as expressions. Pictures should explain everything
Create Parameter (if not automaticly created)
Define values - wrong way example
Define values - correct way example
Set default values - you must define all default values reflecting available values to make "Select All" by default, if you won't define all only those defined will be selected by default.
The Result
One picture for Data type: Int
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
Try this...
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId="
+ pet.getOwner().getId();
}
}
}
Tried all the above, did some research of my own resulting in the following solution for rendering linefeed escape chars:
string = string.replace("\\\n", System.getProperty("line.separator"));
Using the replace method you need to filter escaped linefeeds (e.g. '\\n')
Only then each instance of line feed '\n' escape chars gets rendered into the actual linefeed
For this example I used a Google Apps Scripting noSQL database (ScriptDb) with JSON formatted data.
Cheers :D
Difference between String and the other two classes is that String is immutable and the other two are mutable classes.
But why we have two classes for same purpose?
Reason is that StringBuffer
is Thread safe and StringBuilder
is not.
StringBuilder
is a new class on StringBuffer Api
and it was introduced in JDK5
and is always recommended if you are working in a Single threaded environment as it is much Faster
For complete Details you can read http://www.codingeek.com/java/stringbuilder-and-stringbuffer-a-way-to-create-mutable-strings-in-java/
For fun, instead of using a loop to create the extra zeros:
function zeroPad(n,length){
var s=n+"",needed=length-s.length;
if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
return s;
}