The best and simplest way to read a line from a console is using the getchar() function, whereby you will store one character at a time in an array.
{
char message[N]; /* character array for the message, you can always change the character length */
int i = 0; /* loop counter */
printf( "Enter a message: " );
message[i] = getchar(); /* get the first character */
while( message[i] != '\n' ){
message[++i] = getchar(); /* gets the next character */
}
printf( "Entered message is:" );
for( i = 0; i < N; i++ )
printf( "%c", message[i] );
return ( 0 );
}
console.log('Hello, \n' +
'Text under your Header\n' +
'-------------------------\n' +
'More Text\n' +
'Moree Text\n' +
'Moooooer Text\n' );
This works great for me for text only, and easy on the eye.
To turn it off:
old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
To turn it back on:
ActiveRecord::Base.logger = old_logger
A lot of good answers but why not just use JSON.stringify(your_variable) ? Then take the contents via copy and paste (remove outer quotes). I posted this same answer also at: How to save the output of a console.log(object) to a file?
Insted of using System.Net.WebClient I would recommend to have a look on System.Net.Http.HttpClient which was introduced with net 4.5 and makes your life much easier.
Also microsoft recommends to use the HttpClient on this article
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx
An example could look like this:
var client = new HttpClient();
var content = new MultipartFormDataContent
{
{ new StringContent("myUserId"), "userid"},
{ new StringContent("myFileName"), "filename"},
{ new StringContent("myPassword"), "password"},
{ new StringContent("myType"), "type"}
};
var responseMessage = await client.PostAsync("some url", content);
var stream = await responseMessage.Content.ReadAsStreamAsync();
Try to install this package: pip install progressbar2
:
import time
import progressbar
for i in progressbar.progressbar(range(100)):
time.sleep(0.02)
progresssbar github: https://github.com/WoLpH/python-progressbar
You shouldn't launch as an IIS server. check your launch setting, make sure it switched to your project name( change this name in your launchSettings.json
file ), not the IIS.
Open the Windows > Preferences menu.
Expand the Run/Debug > Console preferences.
Set the Console buffer size (characters)
to something much bigger. 2147383647
/ ~2GB is the upper limit (or 1000000
/ ~1MB in older releases). Or just uncheck the Limit console output
.
Replace
var myNewString = myOldString.replace ("username," visitorName);
with
var myNewString = myOldString.replace("username", visitorName);
Google has documented this https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css
The CSS format specifier allows you to customize the display in the console. Start the string with the specifier and give the style you wish to apply as the second parameter.
One example:
console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");
I am late, here but want to share so may be it help some one and me too when ever needed later :) , So below is the way to open emulator from command line with one command using bash script. I am using MX Linux but process is same on all operating systems
1- First Check the installed emulators
emulator -list-avds
it will result like below
emulator -list-avds
Nexus_4_API_28
Pixel_2_API_28
2- open any plain text or code editor and create a new file and write as below
#!/bin/sh
emulator -avd Nexus_4_API_28
Nexus_4_API_28 is the emulator that i want to open you write yours which you got from first step
save this file with .sh extension
3- Then, change the permissions on the file to make it executable:
chmod u+x emu.sh
4- Now open the emulator just executing this bash script file with following command
./emu.sh
NSLog
- add meta info (like timestamp and identifier) and allows you to output 1023 symbols. Also print message into Console. The slowest method@import Foundation
NSLog("SomeString")
print
- prints all string to Xcode. Has better performance than previous@import Foundation
print("SomeString")
println
(only available Swift v1) and add \n
at the end of stringos_log
(from iOS v10) - prints 32768 symbols also prints to console. Has better performance than previous@import os.log
os_log("SomeIntro: %@", log: .default, type: .info, "someString")
Logger
(from iOS v14) - prints 32768 symbols also prints to console. Has better performance than previous@import os
let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "someCategory")
logger.log("\(s)")
Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)
- Wall -pedantic -Weffc++ -Werror
Added process.StartInfo.**CreateNoWindow** = true;
and timeout
.
private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)
{
using (Process process = new Process())
{
process.StartInfo.FileName = exeName;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
output = process.StandardOutput.ReadToEnd();
bool exited = process.WaitForExit(timeoutMilliseconds);
if (exited)
{
exitCode = process.ExitCode;
}
else
{
exitCode = -1;
}
}
}
Do some padding, i.e.
public static void prn(string fname, string fvalue)
{
string outstring = fname.PadRight(20) +"\t\t " + fvalue;
Console.WriteLine(outstring);
}
This worked well, at least for me.
Keeping your commands short will make them easier to remember:
git log --graph --oneline
Right click on your project
Properties > Configuration Properties > Linker > System
Select Console (/SUBSYSTEM:CONSOLE) in SubSystem
option or you can just type Console in the text field!
Now try it...it should work
You can do pretty much the same as in JavaScript. Try this:
Console.WriteLine(mon + "." + da + "." + yer);
Or you can use WriteLine
as if it were a string.Format
statement by doing:
Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
which is equivalent to:
string.Format("{0}.{1}.{2}", mon, da, yer);
The number of parameters can be infinite, just make sure you correctly index those numbers (starting at 0).
If the method is the POST
method then:
app.post 'controller/action?parameter1=value1¶meter2=value2'
(Here parameters will be as per your applicability.)
Else if it is the GET
method then:
app.get 'controller/action'
If you want history, use rlwrap. This could be your ~/bin/ips
for example:
#!/bin/sh
echo 'This is Interactive Perl shell'
rlwrap -A -pgreen -S"perl> " perl -wnE'say eval()//$@'
And this is how it looks like:
$ ips
This is Interactive Perl shell
perl> 2**128
3.40282366920938e+38
perl>
Instead of typing command just press:
CLTRL + L
to clear chrome console
A bit more elaborate version (to use from another window):
#!/bin/bash
DELAY=3
TERM_PID=$(echo `ps -C gnome-terminal -o pid= | head -1`) # get first gnome-terminal's PID
WID=$(wmctrl -lp | awk -v pid=$TERM_PID '$3==pid{print $1;exit;}') # get window id
xdotool windowfocus $WID
xdotool key alt+t # my key map
xdotool sleep $DELAY # it may take a while to start new shell :(
xdotool type --delay 1 --clearmodifiers "$@"
xdotool key Return
wmctrl -i -a $WID # go to that window (WID is numeric)
# vim:ai
# EOF #
If you're using gulp, then you can use this plugin:
Install this plugin with the command:
npm install gulp-remove-logging
Next, add this line to your gulpfile:
var gulp_remove_logging = require("gulp-remove-logging");
Lastly, add the configuration settings (see below) to your gulpfile.
Task Configuration
gulp.task("remove_logging", function() { return gulp.src("src/javascripts/**/*.js") .pipe( gulp_remove_logging() ) .pipe( gulp.dest( "build/javascripts/" ) ); });
git log --oneline | grep PATTERN
Depending on what listeners you attach, trace output can go to the debug window, the console, a file, database, or all at once. The possibilities are literally endless, as implementing your own TraceListener is extremely simple.
Improving on Andru's idea, you can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
This is the simplest thing you can do and it doesn't require any additional libraries. It will clear the screen and return >>>
to the top left corner.
print("\033[H\033[J")
You can run your program by: Debug -> Start Without Debugging
. It will keep a console opened after the program will be finished.
Right click on the project, "Properties", "Application" tab, change "Output Type" to "Console Application", and then it will also have a console.
After I tried algirdas' solution, my Windows crashed (Win 7 Pro 64bit) so I decided to try a different solution:
Run
(Win+R)cmd /K chcp 65001
You will get mostly what you want. To start it from the taskbar or anywhere else, make a shortcut (you can name it cmd.unicode.exe
or whatever you like) and change its Target
to C:\Windows\System32\cmd.exe /K chcp 65001
.
Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
Is the only one that has worked for me in every case I have tried.
In his book, "Secrets of Javascript Ninja", John Resig (creator of jQuery) has a really simple code which will handle cross-browser console.log issues. He explains that he would like to have a log message which works with all browsers and here is how he coded it:
function log() {
try {
console.log.apply(console, arguments);
} catch(e) {
try {
opera.postError.apply(opera, arguments);
}
catch(e) {
alert(Array.prototype.join.call( arguments, " "));
}
}
It's very simple.
You can call it from anywhere in APP.
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("Hello from Terminal");
Use the Debug.WriteLine
. This will display your message in the Output
window immediately. The only restriction is that you must run your test in Debug
mode.
[TestMethod]
public void TestMethod1()
{
Debug.WriteLine("Time {0}", DateTime.Now);
System.Threading.Thread.Sleep(30000);
Debug.WriteLine("Time {0}", DateTime.Now);
}
Output
It works in IE8. Open IE8's Developer Tools by hitting F12.
>>console.log('test')
LOG: test
Facebook login for smarttv/devices without facebook sdk is possible throught code , check the documentation here :
https://developers.facebook.com/docs/facebook-login/for-devices
Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.
cin.get();
As a follow up to Shubham's great answer I like to suggest using enum values instead of strings. Please take a look at the documentation of the TestLogging class.
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent
tasks.withType(Test) {
testLogging {
events TestLogEvent.FAILED,
TestLogEvent.PASSED,
TestLogEvent.SKIPPED,
TestLogEvent.STANDARD_ERROR,
TestLogEvent.STANDARD_OUT
exceptionFormat TestExceptionFormat.FULL
showCauses true
showExceptions true
showStackTraces true
}
}
I was looking for a way to debug code in a WordPress plugin that I was developing and came across this post.
I took the bits of code that are most applicable to me from other responses and combined these into a function that I can use for debugging WordPress. The function is:
function debug_log($object=null, $label=null, $priority=1) {
$priority = $priority<1? 1: $priority;
$message = json_encode($object, JSON_PRETTY_PRINT);
$label = "Debug" . ($label ? " ($label): " : ': ');
echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}
Usage is as follows:
$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);
If this function is used with WordPress development, the function should be placed in the functions.php
file of the child theme and can then be called anywhere in the code.
Just press Alt+Shift+Q,c for quick access.(In windows)
I assume bash is running on a vt100-compatible terminal in which the user did not explicitly turn off the support for formatting.
First, turn on support for special characters in echo
, using -e
option. Later, use ansi escape sequence ESC[1m
, like:
echo -e "\033[1mSome Text"
More on ansi escape sequences for example here: ascii-table.com/ansi-escape-sequences-vt-100.php
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
These are the methods of system.console
(There are more system.console methods like write() and writeline() as well which are used to write in command line, behaving similarly as read() and readline() methods)
This was clearly described with examples in the MSDN documentation (links are included above).
A different approach, just for kicks:
Console.WriteLine(string.Join("\t", list));
You're missing a semicolon: double b = a * Math.PI;
i was looking for same solution in vb.net and i found this one and it's great.
however as @JohnOdom suggested a better way to handle the blanks space if previous one is larger than current one..
i make a function in vb.net and thought someone could get helped ..
here is my code:
Private Sub sPrintStatus(strTextToPrint As String, Optional boolIsNewLine As Boolean = False)
REM intLastLength is declared as public variable on global scope like below
REM intLastLength As Integer
If boolIsNewLine = True Then
intLastLength = 0
End If
If intLastLength > strTextToPrint.Length Then
Console.Write(Convert.ToChar(13) & strTextToPrint.PadRight(strTextToPrint.Length + (intLastLength - strTextToPrint.Length), Convert.ToChar(" ")))
Else
Console.Write(Convert.ToChar(13) & strTextToPrint)
End If
intLastLength = strTextToPrint.Length
End Sub
You cannot directly print by using system.out.println or using logger api while using JUnit. But if you want to check any values then you simply can use
Assert.assertEquals("value", str);
It will throw below assertion error:
java.lang.AssertionError: expected [21.92] but found [value]
Your value should be 21.92, Now if you will test using this value like below your test case will pass.
Assert.assertEquals(21.92, str);
Use the PowerConsole project on Github at https://github.com/bigabdoul/PowerConsole or the equivalent NuGet package at https://www.nuget.org/packages/PowerConsole. It elegantly handles timers in a reusable fashion. Take a look at this sample code:
using PowerConsole;
namespace PowerConsoleTest
{
class Program
{
static readonly SmartConsole MyConsole = SmartConsole.Default;
static void Main()
{
RunTimers();
}
public static void RunTimers()
{
// CAUTION: SmartConsole is not thread safe!
// Spawn multiple timers carefully when accessing
// simultaneously members of the SmartConsole class.
MyConsole.WriteInfo("\nWelcome to the Timers demo!\n")
// SetTimeout is called only once after the provided delay and
// is automatically removed by the TimerManager class
.SetTimeout(e =>
{
// this action is called back after 5.5 seconds; the name
// of the timer is useful should we want to clear it
// before this action gets executed
e.Console.Write("\n").WriteError("Time out occured after 5.5 seconds! " +
"Timer has been automatically disposed.\n");
// the next statement will make the current instance of
// SmartConsole throw an exception on the next prompt attempt
// e.Console.CancelRequested = true;
// use 5500 or any other value not multiple of 1000 to
// reduce write collision risk with the next timer
}, millisecondsDelay: 5500, name: "SampleTimeout")
.SetInterval(e =>
{
if (e.Ticks == 1)
{
e.Console.WriteLine();
}
e.Console.Write($"\rFirst timer tick: ", System.ConsoleColor.White)
.WriteInfo(e.TicksToSecondsElapsed());
if (e.Ticks > 4)
{
// we could remove the previous timeout:
// e.Console.ClearTimeout("SampleTimeout");
}
}, millisecondsInterval: 1000, "EverySecond")
// we can add as many timers as we want (or the computer's resources permit)
.SetInterval(e =>
{
if (e.Ticks == 1 || e.Ticks == 3) // 1.5 or 4.5 seconds to avoid write collision
{
e.Console.WriteSuccess("\nSecond timer is active...\n");
}
else if (e.Ticks == 5)
{
e.Console.WriteWarning("\nSecond timer is disposing...\n");
// doesn't dispose the timer
// e.Timer.Stop();
// clean up if we no longer need it
e.DisposeTimer();
}
else
{
System.Diagnostics.Trace.WriteLine($"Second timer tick: {e.Ticks}");
}
}, 1500)
.Prompt("\nPress Enter to stop the timers: ")
// makes sure that any remaining timer is disposed off
.ClearTimers()
.WriteSuccess("Timers cleared!\n");
}
}
}
A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:
$ tail -f $RAILS_APP_DIR/logs/test.log
or tail -f $RAILS_APP_DIR\logs\test.log
for Window usersIf you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec
and the test.log
output side by side.
If you're using Python 3.3 or above, I'd recommend the built-in get_terminal_size()
as already recommended. However if you are stuck with an older version and want a simple, cross-platform way of doing this, you could use asciimatics. This package supports versions of Python back to 2.7 and uses similar options to those suggested above to get the current terminal/console size.
Simply construct your Screen
class and use the dimensions
property to get the height and width. This has been proven to work on Linux, OSX and Windows.
Oh - and full disclosure here: I am the author, so please feel free to open a new issue if you have any problems getting this to work.
In plain JavaScript, simply use response = readline()
after printing a prompt.
In Node.js, you'll need to use the readline module: const readline = require('readline')
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
Double d = scan.nextDouble();
String newStr = "";
Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
while( charScanner.hasNext() ) {
String c = charScanner.next();
if (c.equalsIgnoreCase("\r")) {
break;
}
else {
newStr += c;
}
}
System.out.println("String: " + newStr);
System.out.println("Int: " + i);
System.out.println("Double: " + d);
This code works fine
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and _getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
The given code given will work absolutely fine if we run from console. and there is no package name in the class
You have to make sure where you have your ".class" file. because, if package name is given for the class, you have to make sure to keep the ".class" file inside the specified folder. For example, my package name is "src.main.code" , I have to create a code folder,inside main folder, inside src folder and put Test.class in code folder. then it will work perfectly.
If you get this error when you try to pipe/redirect output of your script
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
Just export PYTHONIOENCODING in console and then run your code.
export PYTHONIOENCODING=utf8
In Windows console (Linux, too), you should replace '\r'
with its equivalent code \033[0G
:
process.stdout.write('ok\033[0G');
This uses a VT220 terminal escape sequence to send the cursor to the first column.
In your ~/.gitconfig
file, simply add this:
[color]
ui = auto
It takes care of all your git commands.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
<AppenderRef ref="MyFile"/>
</Root>
</Loggers>
</Configuration>
Notes:
Logger logger = LogManager.getLogger();
to initialize your loggerRun this:
Rails.application.eager_load!
Then
ActiveRecord::Base.descendants
To return a list of models/tables
Use the following code:
System.out.println("\f");
'\f' is an escape sequence which represents FormFeed. This is what I have used in my projects to clear the console. This is simpler than the other codes, I guess.
FYI dataTables requires a well formed table. It must contain <thead>
and <tbody>
tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.
The following will throw error (no <thead>
and <tbody>
tags)
<table id="sample-table">
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
<tr>
<td>data-1</td>
<td>data-2</td>
</tr>
</table>
The following will also throw an error (unequal number of columns)
<table id="sample-table">
<thead>
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>
For more info read more here
You're getting the toString()
value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,
Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);
Please read the tutorial on how to use it as it will explain all.
Edit
Please look here: Scanner tutorial
Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.
To stop Jenkins Please avoid shutting down the Java process or the Windows service. These are not usual commands. Use those only if your Jenkins is causing problems.
Use Jenkins' way to stop that protects from data loss.
http://[jenkins-server]/[command]
where [command] can be any one of the following
Example: if my local PC is running Jenkins at port 8080, it will be
http://localhost:8080/exit
Edit: thanks to @superlogical, you can now find and improve the following code in github!
I wrote this class based on some ideas here. The columns width is optimal, an it can handle object arrays with this simple API:
static void Main(string[] args)
{
IEnumerable<Tuple<int, string, string>> authors =
new[]
{
Tuple.Create(1, "Isaac", "Asimov"),
Tuple.Create(2, "Robert", "Heinlein"),
Tuple.Create(3, "Frank", "Herbert"),
Tuple.Create(4, "Aldous", "Huxley"),
};
Console.WriteLine(authors.ToStringTable(
new[] {"Id", "First Name", "Surname"},
a => a.Item1, a => a.Item2, a => a.Item3));
/* Result:
| Id | First Name | Surname |
|----------------------------|
| 1 | Isaac | Asimov |
| 2 | Robert | Heinlein |
| 3 | Frank | Herbert |
| 4 | Aldous | Huxley |
*/
}
Here is the class:
public static class TableParser
{
public static string ToStringTable<T>(
this IEnumerable<T> values,
string[] columnHeaders,
params Func<T, object>[] valueSelectors)
{
return ToStringTable(values.ToArray(), columnHeaders, valueSelectors);
}
public static string ToStringTable<T>(
this T[] values,
string[] columnHeaders,
params Func<T, object>[] valueSelectors)
{
Debug.Assert(columnHeaders.Length == valueSelectors.Length);
var arrValues = new string[values.Length + 1, valueSelectors.Length];
// Fill headers
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
arrValues[0, colIndex] = columnHeaders[colIndex];
}
// Fill table rows
for (int rowIndex = 1; rowIndex < arrValues.GetLength(0); rowIndex++)
{
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
arrValues[rowIndex, colIndex] = valueSelectors[colIndex]
.Invoke(values[rowIndex - 1]).ToString();
}
}
return ToStringTable(arrValues);
}
public static string ToStringTable(this string[,] arrValues)
{
int[] maxColumnsWidth = GetMaxColumnsWidth(arrValues);
var headerSpliter = new string('-', maxColumnsWidth.Sum(i => i + 3) - 1);
var sb = new StringBuilder();
for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
{
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
// Print cell
string cell = arrValues[rowIndex, colIndex];
cell = cell.PadRight(maxColumnsWidth[colIndex]);
sb.Append(" | ");
sb.Append(cell);
}
// Print end of line
sb.Append(" | ");
sb.AppendLine();
// Print splitter
if (rowIndex == 0)
{
sb.AppendFormat(" |{0}| ", headerSpliter);
sb.AppendLine();
}
}
return sb.ToString();
}
private static int[] GetMaxColumnsWidth(string[,] arrValues)
{
var maxColumnsWidth = new int[arrValues.GetLength(1)];
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
{
int newLength = arrValues[rowIndex, colIndex].Length;
int oldLength = maxColumnsWidth[colIndex];
if (newLength > oldLength)
{
maxColumnsWidth[colIndex] = newLength;
}
}
}
return maxColumnsWidth;
}
}
Edit: I added a minor improvement - if you want the column headers to be the property name, add the following method to TableParser
(note that it will be a bit slower due to reflection):
public static string ToStringTable<T>(
this IEnumerable<T> values,
params Expression<Func<T, object>>[] valueSelectors)
{
var headers = valueSelectors.Select(func => GetProperty(func).Name).ToArray();
var selectors = valueSelectors.Select(exp => exp.Compile()).ToArray();
return ToStringTable(values, headers, selectors);
}
private static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expresstion)
{
if (expresstion.Body is UnaryExpression)
{
if ((expresstion.Body as UnaryExpression).Operand is MemberExpression)
{
return ((expresstion.Body as UnaryExpression).Operand as MemberExpression).Member as PropertyInfo;
}
}
if ((expresstion.Body is MemberExpression))
{
return (expresstion.Body as MemberExpression).Member as PropertyInfo;
}
return null;
}
This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).
public final static void clearConsole()
{
try
{
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
{
Runtime.getRuntime().exec("cls");
}
else
{
Runtime.getRuntime().exec("clear");
}
}
catch (final Exception e)
{
// Handle any exceptions.
}
}
Note that this method generally will not clear the console if you are running inside an IDE.
Of course, to see the result in logcat, you should set the Log level at least to "Info" (Log level in logcat); otherwise, as it happened to me, you won't see your output.
Any other solution/library is in the end going to use reflection to introspect the type...
In ubuntu you can simply use color codes:
var sys = require('sys');
process.stdout.write("x1B[31m" + your_message_in_red + "\x1B[0m\r\n");
If the project is a GUI project, no console will appear. In order to change the project into a console one you need to go to the project properties panel and set:
This solution works only if you had the classic "int main()" entry point.
But if you are like in my case (an openGL project), you don't need to edit the properties, as this works better:
AllocConsole();
freopen("CONIN$", "r",stdin);
freopen("CONOUT$", "w",stdout);
freopen("CONOUT$", "w",stderr);
printf and cout will work as usual.
If you call AllocConsole before the creation of a window, the console will appear behind the window, if you call it after, it will appear ahead.
Update
freopen
is deprecated and may be unsafe. Use freopen_s
instead:
FILE* fp;
AllocConsole();
freopen_s(&fp, "CONIN$", "r", stdin);
freopen_s(&fp, "CONOUT$", "w", stdout);
freopen_s(&fp, "CONOUT$", "w", stderr);
Some worthwhile subtleties...
\33[2K
erases the entire line your cursor is currently on
\033[A
moves your cursor up one line, but in the same column i.e. not to the start of the line
\r
brings your cursor to the beginning of the line (r is for carriage return N.B. carriage returns do not include a newline so cursor remains on the same line) but does not erase anything
In xterm specifically, I tried the replies mentioned above and the only way I found to erase the line and start again at the beginning is the sequence (from the comment above posted by @Stephan202 as well as @vlp and @mantal) \33[2K\r
On an implementation note, to get it to work properly for example in a countdown scenario since I wasn't using a new line character '\n'
at the end of each fprintf()
, so I had to fflush()
the stream each time (to give you some context, I started xterm using a fork on a linux machine without redirecting stdout, I was just writing to the buffered FILE pointer fdfile
with a non-blocking file descriptor I had sitting on the pseudo terminal address which in my case was /dev/pts/21
):
fprintf(fdfile, "\33[2K\rT minus %d seconds...", i);
fflush(fdfile);
Note that I used both the \33[2K sequence to erase the line followed by the \r
carriage return sequence to reposition the cursor at the beginning of the line. I had to fflush()
after each fprintf()
because I don't have a new line character at the end '\n'
. The same result without needing fflush() would require the additional sequence to go up a line:
fprintf(fdfile, "\033[A\33[2K\rT minus %d seconds...\n", i);
Note that if you have something on the line immediately above the line you want to write on, it will get over-written with the first fprintf(). You would have to leave an extra line above to allow for the first movement up one line:
i = 3;
fprintf(fdfile, "\nText to keep\n");
fprintf(fdfile, "Text to erase****************************\n");
while(i > 0) { // 3 second countdown
fprintf(fdfile, "\033[A\33[2KT\rT minus %d seconds...\n", i);
i--;
sleep(1);
}
In linux, just run it, no problem. In Windows, you want to use the pythonw executable.
Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?
$ nohup mypythonprog &
C:/> start pythonw mypythonprog
I think that's right. In any case, now you can close the terminal.
You can use Scanner class
Import first :
import java.util.Scanner;
Then you use like this.
Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();
Side note : If you are using nextInt()
with nextLine()
you probably could have some trouble cause nextInt()
does not read the last newline character of input and so nextLine()
then is not gonna to be executed with desired behaviour. Read more in how to solve it in this previous question Skipping nextLine using nextInt.
I assume you're using some version of Visual Studio? In windows, std::cout << "something";
should write something to a console window IF your program is setup in the project settings as a console program.
Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.
I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.
I got this too work by adding a reset button to the form, which had an id of myform
:
$("#myform > input[type=reset]").trigger('click');
This for me had the correct outcome on resetting the form, oh and dont forget the
event.preventDefault();
to stop the form submitting in browser, like I did :).
Regards
Jacko
To save text from the console: run the analysis and then choose (Windows) "File>Save to File".
Put a breakpoint on the return
line.
You are running it in the debugger, right?
You can run ruby commands in one line with the -e
flag:
ruby -e "puts 'hi'"
Check the man page for more information.
if you create a console application, console will stay opened until you close the application.
if you already creat an application and you dont know how to open a console, you can change the subsystem as Console(/Subsystem:Console) in project configurations -> linker -> system.
Are you talking about gets
?
puts "Enter A"
a = gets.chomp
puts "Enter B"
b = gets.chomp
c = a.to_i + b.to_i
puts c
Something like that?
Kernel.gets
tries to read the params found in ARGV
and only asks to console if not ARGV
found. To force to read from console even if ARGV
is not empty use STDIN.gets
If anyone, fails to load because hes script violates the script-src "Content Security Policy" or "because unsafe-eval' is not an allowed", I will advice using my pretty-small module-injector as a dev-tools snippet, then you'll be able to load like this:
imports('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js')_x000D_
.then(()=>alert(`today is ${moment().format('dddd')}`));
_x000D_
<script src="https://raw.githack.com/shmuelf/PowerJS/master/src/power-moduleInjector.js"></script>
_x000D_
this solution works because:
I just copied from http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/1555ce45-8313-4669-a31e-b95b5d28c787/?prof=required:
The following works for me :-)
/////////////////////////////////////////////////////////////////////////////////////
Here is another reason the console may disappear. And the solution:
With the new Visual Studio 2010 you might see this behavior even when you use Ctrl + F5 aka "start without debugging". This is most likely because you created an "empty project" instead of a "Win32 console application". If you create the project as a "Win32 console application" you can disregard this as it does not apply.
In the older versions it would default to the console subsystem even if you selected "empty project", but not in Visual Studio 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this).
Then select "project" from the menu bar drop down menus, then select "project_name properties" ? "configuration properties" ? "linker" ? "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
/////////////////////////////////////////////////////////////////////////////////////
For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin
to the PATH
. Use whatever directory you have this installed in.
Then you can run from any directory in command line:
httpd -k restart
The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?
yes it's possible to print a string to the console.
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string strMytestString("hello world");
cout << strMytestString;
return 0;
}
stdafx.h isn't pertinent to the solution, everything else is.
No need to divert stdout. Here is better way to do it:
import logging
class MyLogHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger().addHandler(MyLogHandler())
An even simpler way is:
logging.getLogger().setLevel(100)
I've used another API for this purpose..
var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('guess> ');
rl.prompt();
rl.on('line', function(line) {
if (line === "right") rl.close();
rl.prompt();
}).on('close',function(){
process.exit(0);
});
This allows to prompt in loop until the answer is right
. Also it gives nice little console.You can find the details @ http://nodejs.org/api/readline.html#readline_example_tiny_cli
From the comments:
import msvcrt # built-in module
def kbfunc():
return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:
#include <conio.h>
int kb_inkey () {
int rc;
int key;
key = _kbhit();
if (key == 0) {
rc = 0;
} else {
rc = _getch();
}
return rc;
}
And I access it in python using the ctypes module (built into python 2.5):
import ctypes
import time
#
# first, load the DLL
#
try:
kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
raise ("Error Loading PyKeyboardAccess.dll")
#
# now, find our function
#
try:
kbfunc = kblib.kb_inkey
except:
raise ("Could not find the kb_inkey function in the dll!")
#
# Ok, now let's demo the capability
#
while 1:
x = kbfunc()
if x != 0:
print "Got key: %d" % x
else:
time.sleep(.01)
d
and i
conversion specifiers behave the same with fprintf
but behave differently for fscanf
.
As some other wrote in their answer, the idiomatic way to print an int
is using d
conversion specifier.
Regarding i
specifier and fprintf
, C99 Rationale says that:
The %i conversion specifier was added in C89 for programmer convenience to provide symmetry with fscanf’s %i conversion specifier, even though it has exactly the same meaning as the %d conversion specifier when used with fprintf.
The easiest way to write console output to text file is
//create a file first
PrintWriter outputfile = new PrintWriter(filename);
//replace your System.out.print("your output");
outputfile.print("your output");
outputfile.close();
You don't need the QCoreApplication
at all, just include your Qt objects as you would other objects, for example:
#include <QtCore>
int main()
{
QVector<int> a; // Qt object
for (int i=0; i<10; i++)
{
a.append(i);
}
/* manipulate a here */
return 0;
}
order
is an Object
, not an Array()
.
push()
is for arrays.
Refer to this post
Try this though(but your subobjects have to be Arrays()
):
var order = new Array();
// initialize order; n = index
order[n] = new Array();
// and then you can perform push()
order[n].push(some_value);
Or you can just use order as an array of non-array objects:
var order = new Array();
order.push(a[n]);
In Windows I have made the mistake of using
system("clear")
but that is actually for Linux
The Windows type is
system("cls")
without #include conio.h
As per Jeffrey Knight quote above, as soon as I run into situations where I need API calls to get something done, I tend to stop and ask myself "am I overcomplicating things?".
If what is wanted is to have some code and run it in Windows GUI mode or Console mode, consider moving the code used in both modes off to a code library DLL, and then having a Windows Forms application that uses that DLL, and a Console application that uses that DLL (i.e. if in Visual Studio you now have a three-project solution: library with the bulk of the code, GUI with just the Win Forms code, and Console with just your console code.)
From Linux you can use 'swaks' which is available as an official packages on many distros including Debian/Ubuntu and Redhat/CentOS on EPEL:
swaks -f [email protected] -t [email protected] \
--server mail.example.com
From the firebug site http://getfirebug.com/logging/
Calling console.dir(object) will log an interactive listing of an object's properties, like > a miniature version of the DOM tab.
Just go to the application's Properties and change the Output type from Console Application to Windows Application.
Option combinations for mysql Ver 14.14 Distrib 5.7.18, for Linux (x86_64)
.
Doesn't throw:
STRICT_TRANS_TABLES
+ NO_ZERO_DATE
Throws:
STRICT_TRANS_TABLES
+ NO_ZERO_IN_DATE
My settings in /etc/mysql/my.cnf
on Ubuntu:
[mysqld]
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Based on this article, you should:
create new branch which is based upon new version of master
git branch -b newmaster
merge your old feature branch into new one
git checkout newmaster
resolve conflict on new feature branch
The first two commands can be combined to git checkout -b newmaster
.
This way your history stays clear because you don't need back merges. And you don't need to be so super cautious since you don't need to do a Git rebase.
this is the only case in which ==
and !=
should be used:
if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')
For any other comparisons, the strict comparators (===
and !==
) should be used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
I have a lighter and better solution..
It could be easily solve through some additional CSS styles..
hide the class .modal-backdrop
(auto generated from Bootstrap.js)
.modal-backdrop
{
display:none;
visibility:hidden;
position:relative
}
set the background of .modal
to a translucent black backdrop image.
.modal
{
background:url("http://bin.smwcentral.net/u/11361/BlackTransparentBackground.png")
// translucent image from google images
z-index:1100;
}
This will works best if you have a requirement that needs the modal to be inside an element and not near the </body>
tag..
Creation time isn't stored.
What are stored are three timestamps (generally, they can be turned off on certain filesystems or by certain filesystem options):
a "Change" to the file is counted as permission changes, rename etc. While the modification is contents only.
use array_map()
:
$yourArray = array_map('strtolower', $yourArray);
In case you need to lowercase nested array (by Yahya Uddin):
$yourArray = array_map('nestedLowercase', $yourArray);
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
For whatever reason I have had issues with some of these answers, I've went and written a couple helper functions for myself, so if you have problems like I did, give these a try.
def bin_string_to_bin_value(input):
highest_order = len(input) - 1
result = 0
for bit in input:
result = result + int(bit) * pow(2,highest_order)
highest_order = highest_order - 1
return bin(result)
def hex_string_to_bin_string(input):
lookup = {"0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011", "4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111", "8" : "1000", "9" : "1001", "A" : "1010", "B" : "1011", "C" : "1100", "D" : "1101", "E" : "1110", "F" : "1111"}
result = ""
for byte in input:
result = result + lookup[byte]
return result
def hex_string_to_hex_value(input):
bin_string = hex_string_to_bin_string(input)
bin_value = bin_string_to_bin_value(bin_string)
return hex(int(bin_value, 2))
They seem to work well.
print hex_string_to_hex_value("FF")
print hex_string_to_hex_value("01234567")
print bin_string_to_bin_value("11010001101011")
results in:
0xff
0x1234567
0b11010001101011
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));
Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
alert(matches[i]);
}
This code alerts with all the matches.
References:
search for "?=n" http://www.w3schools.com/jsref/jsref_obj_regexp.asp
search for "x(?=y)" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
By Timestamp
, I presume you mean java.sql.Timestamp
. You will notice that this class has a constructor that accepts a long
argument. You can parse this using the DateFormat
class:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);
If you already know for sure that the user is logged in (in your example if /index.html
is protected):
UserDetails userDetails =
(UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
To first check if the user is logged in, check that the current Authentication
is not a AnonymousAuthenticationToken
.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
// userDetails = auth.getPrincipal()
}
New answer to an old question:
Method 1:
Step 1: You have to put /show
after the URL
you are working on:
http://jsfiddle.net/<fiddle_id>/show/
It shows the output with a result header.
Step 2: Right click the bottom frame and select View Frame Source. That's it. You got the html code with online JS links, CSS.
Just Save it.
For Example: http://jsfiddle.net/YRafQ/20/show/ for the site http://jsfiddle.net/YRafQ/20/
Note: View Frame Source and not View Page Source
Method 2:
You can use this code: view-source:http://fiddle.jshell.net/<fiddle_id>/show/light/
For Example: For my fiddle_id: YRafQ/20
view-source:http://fiddle.jshell.net/YRafQ/20/show/light/
Another alternative:
Use the code from the unicodecsv package ...
https://pypi.python.org/pypi/unicodecsv/
>>> import unicodecsv as csv
>>> from io import BytesIO
>>> f = BytesIO()
>>> w = csv.writer(f, encoding='utf-8')
>>> _ = w.writerow((u'é', u'ñ'))
>>> _ = f.seek(0)
>>> r = csv.reader(f, encoding='utf-8')
>>> next(r) == [u'é', u'ñ']
True
This module is API compatible with the STDLIB csv module.
Just a NOTE, something that I wasted hours tracking down tonight...
If you decide to hold onto a marker for some reason, after you have REMOVED it from a map... getTag will return NULL, even though the remaining get values will return with the values you set them to when the marker was created...
TAG value is set to NULL if you ever remove a marker, and then attempt to reference it.
Seems like a bug to me...
lapply
can be used instead of a for
loop.
d1[] <- lapply(d1, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
This doesn't really have any advantages over the for loop, though maybe it's easier if you have non-numeric columns as well, in which case
d1[sapply(d1, is.numeric)] <- lapply(d1[sapply(d1, is.numeric)], function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))
is almost as easy.
Just spent 4 hours tracking down a similar problem in a WSDL. Turns out the WSDL used an XSD which imports another namespace XSD. This imported XSD contained the following:
<?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://www.xyz.com/Services/CommonTypes" elementFormDefault="qualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:CommonTypes="http://www.xyz.com/Services/CommonTypes">
<include schemaLocation=""></include>
<complexType name="RequestType">
<....
Note the empty include
element! This was the root of my woes. I guess this is a variation on Egor's file not found problem above.
+1 to disappointing error reporting.
i experienced this problem in Microsoft Visual Studio Express 2012 for windows phone while trying to open file.
Then i browsed to
C:\Users\MyUserName\AppData\Local\Microsoft\VPDExpress\11.0\ComponentModelCache
And Inside ComponentModelCache i deleted Microsoft.VisualStudio.Default.cache CACHE file. Finaly i restarted visual studio and reopened my project.
Then my problem was solved, i was able to open file.
Note: My OS is windows 8. And i installed SDK 8 for developing windows phone app
Thanks
It works!!! Use the following code:
<style>
div.select-container{
border: 1px black;width:200px;
}
</style>
<div id="status" class="select-container">
<select name="status">
<option value="" >Please Select...</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
</div>
You'll have to do this in two steps:
If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:
mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile
You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ...
.
Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:
<dependencies>
...
<dependency>
<groupId>com.stackoverflow...</groupId>
<artifactId>artifactId...</artifactId>
<version>1.0</version>
</dependency>
...
</dependencies>
If You want get date defer from using table and column.
SELECT TO_DATE( TO_CHAR(COLUMN_NAME_1, 'YYYY-MM-DD'), 'YYYY-MM-DD') -
TO_DATE(TO_CHAR(COLUMN_NAME_2, 'YYYY-MM-DD') , 'YYYY-MM-DD') AS DATEDIFF
FROM TABLE_NAME;
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
CSS 3 introduces the background-size property, but support is not universal.
Having the browser resize the image is inefficient though, the large image still has to be downloaded. You should resize it server side (caching the result) and use that instead. It will use less bandwidth and work in more browsers.
Or you can use one SQL-command instead of create and call stored procedure
INSERT INTO [order_cart](orId,caId)
OUTPUT inserted.*
SELECT
(SELECT MAX(orId) FROM [order]) as orId,
(SELECT MAX(caId) FROM [cart]) as caId;
I believe SET
is ANSI standard whereas the SELECT
is not. Also note the different behavior of SET
vs. SELECT
in the example below when a value is not found.
declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */
set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */
Minimal example
from setuptools import setup, find_packages
setup(
name="foo",
version="1.0",
packages=find_packages(),
)
More info in docs
I had the same error yesterday: I had two classes, cProgress and cProgressEx, in my project, one of which was no longer used, and when I removed cProgress class I was given this same compilation error.
I managed to fix the error as follows:
First Navigate the Path of php.ini
sudo vi /etc/php/7.2/fpm/php.ini
then, next change
upload_max_filesize = 999M
post_max_size = 999M
then ESC-->:wq
Now Lastly Paste this command,
sudo systemctl restart php7.2-fpm.service
you are done.
Check you have the line:
import org.json.JSONArray;
at the top of your source code
In a single database - yes:
USE your_database
SELECT name FROM sys.tables
Getting all tables across all databases - only with a hack.... see this SO question for several approaches how to do that: How do I list all tables in all databases in SQL Server in a single result set?
I'm not entirely sure what you're after but this sounds like it can be achieved by storing the state of the input elements (or the div?) as a variable:
$('div').each(function(){
var childInputHasFocus = false;
$(this).hover(function(){
if (childInputHasFocus) {
// do something
} else { }
}, function() {
if (childInputHasFocus) {
// do something
} else { }
});
$('input', this)
.focus(function(){
childInputHasFocus = true;
})
.blur(function(){
childInputHasFocus = false;
});
});
Yes.
new ArrayList<String>(){{
add("A");
add("B");
}}
What this is actually doing is creating a class derived from ArrayList<String>
(the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this
pointer. Not a problem unless you want to serialise it, or you're expecting the outer class to be garbage collected.
I understand that Java 7 will provide additional language constructs to do precisely what you want.
EDIT: recent Java versions provide more usable functions for creating such collections, and are worth investigating over the above (provided at a time prior to these versions)
call() :-- Here we pass the function arguments individually, not in an array format
var obj = {name: "Raushan"};
var greeting = function(a,b,c) {
return "Welcome "+ this.name + " to "+ a + " " + b + " in " + c;
};
console.log(greeting.call(obj, "USA", "INDIA", "ASIA"));
apply() :-- Here we pass the function arguments in an array format
var obj = {name: "Raushan"};
var cal = function(a,b,c) {
return this.name +" you got " + a+b+c;
};
var arr =[1,2,3]; // array format for function arguments
console.log(cal.apply(obj, arr));
bind() :--
var obj = {name: "Raushan"};
var cal = function(a,b,c) {
return this.name +" you got " + a+b+c;
};
var calc = cal.bind(obj);
console.log(calc(2,3,4));
Dot grammar maybe more swift!
@(intValueDemo).stringValue
for example
int intValueDemo = 1;
//or
NSInteger intValueDemo = 1;
//So you can use dot grammar
NSLog(@"%@",@(intValueDemo).stringValue);
hope this can help someone out there:
List list = ..;
String [] stringArray = list.toArray(new String[list.size()]);
great answer from here: https://stackoverflow.com/a/4042464/1547266
There is also one ugly but working way. Decompile FirebaseMessagingService.class and modify it's behavior. Then just put the class to the right package in yout app and dex use it instead of the class in the messaging lib itself. It is quite easy and working.
There is method:
private void zzo(Intent intent) {
Bundle bundle = intent.getExtras();
bundle.remove("android.support.content.wakelockid");
if (zza.zzac(bundle)) { // true if msg is notification sent from FirebaseConsole
if (!zza.zzdc((Context)this)) { // true if app is on foreground
zza.zzer((Context)this).zzas(bundle); // create notification
return;
}
// parse notification data to allow use it in onMessageReceived whe app is on foreground
if (FirebaseMessagingService.zzav(bundle)) {
zzb.zzo((Context)this, intent);
}
}
this.onMessageReceived(new RemoteMessage(bundle));
}
This code is from version 9.4.0, method will have different names in different version because of obfuscation.
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
If the primary key happens to be an auto_increment value, you have to remove the auto increment, then drop the primary key then re-add the auto-increment
ALTER TABLE `xx`
MODIFY `auto_increment_field` INT,
DROP PRIMARY KEY,
ADD PRIMARY KEY (new_primary_key);
then add back the auto increment
ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;
then set auto increment back to previous value
ALTER TABLE `xx` AUTO_INCREMENT = 5;
FYI, sender
and e
are not specific to ASP.NET or to C#. See Events (C# Programming Guide) and Events in Visual Basic.
Also note that the SPOOL
output is driven by a few SQLPlus settings:
SET LINESIZE nn
- maximum line width; if the output is longer it will wrap to display the contents of each result row.
SET TRIMSPOOL OFF|ON
- if set OFF
(the default), every output line will be padded to LINESIZE
. If set ON
, every output line will be trimmed.
SET PAGESIZE nn
- number of lines to output for each repetition of the header. If set to zero, no header is output; just the detail.
Those are the biggies, but there are some others to consider if you just want the output without all the SQLPlus chatter.
What browser are you testing in?
What DOCType have you set?
How exactly are you declaring your CSS?
Are you sure you haven't missed a ;
before/after the overflow-y: scroll
?
I've just tested the following in IE7 and Firefox and it works fine
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents --> _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
</div>
_x000D_
Change this code:
setTimeout(function(){this.setState({timePassed: true})}, 1000);
to the following:
setTimeout(()=>{this.setState({timePassed: true})}, 1000);
This is a mismatch between assemblies: a DLL referenced from an assembly doesn't have a method signature that's expected.
Clean the solution, rebuild everything, and try again.
Also, be careful if this is a reference to something that's in the GAC; it could be that something somewhere is pointing to an incorrect version. Make sure (through the Properties of each reference) that the correct version is chosen or that Specific Version is set false.
Please use following php function to convert php stdClass to array
get_object_vars($data)
You can use the Page.ClientScript.RegisterStartupScript method.
@PathVariable
is to obtain some placeholder from the URI (Spring call it an URI Template)
— see Spring Reference Chapter 16.3.2.2 URI Template Patterns@RequestParam
is to obtain a parameter from the URI as well — see Spring Reference Chapter 16.3.3.3 Binding request parameters to method parameters with @RequestParamIf the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013
gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:
@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
@PathVariable("userId") int user,
@RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
Also, request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices
provide the invoices for user null
or details about a user with ID "invoices"?
What you are thinking of sounds a lot like triggers. MongoDB does not have any support for triggers, however some people have "rolled their own" using some tricks. The key here is the oplog.
When you run MongoDB in a Replica Set, all of the MongoDB actions are logged to an operations log (known as the oplog). The oplog is basically just a running list of the modifications made to the data. Replicas Sets function by listening to changes on this oplog and then applying the changes locally.
Does this sound familiar?
I cannot detail the whole process here, it is several pages of documentation, but the tools you need are available.
First some write-ups on the oplog
- Brief description
- Layout of the local
collection (which contains the oplog)
You will also want to leverage tailable cursors. These will provide you with a way to listen for changes instead of polling for them. Note that replication uses tailable cursors, so this is a supported feature.
You can force IE10 to render in IE9 mode by adding:
<meta http-equiv="X-UA-Compatible" content="IE=9">
in your <head>
tag.
See MSDN for more information...
Since JPA 2.0 a TypedQuery
can be used:
TypedQuery<SimpleEntity> q =
em.createQuery("select t from SimpleEntity t", SimpleEntity.class);
List<SimpleEntity> listOfSimpleEntities = q.getResultList();
for (SimpleEntity entity : listOfSimpleEntities) {
// do something useful with entity;
}
You can use this function if it's multiple string
df[!grepl("REVERSE|GENJJS", df$Name),]
It would appear this is not possible, or at least not supported.
From the HTML5 specification:
When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.
If the IE example doesn't work use this one. Anyway this should be faster than starting up an instance of IE.
Here is a complete solution based on
http://www.dailydoseofexcel.com/archives/2005/02/23/html-in-cells-ii/
Note, if your innerHTML is all numbers eg '12345', HTML formatting dosen't fully work in excel as it treats number differently? but add a character eg a trailing space at the end eg. 12345 + "& nbsp;" formats ok.
Sub test()
Cells(1, 1).Value = "<HTML>1<font color=blue>a</font>" & _
"23<font color=red>4</font></HTML>"
Dim rng As Range
Set rng = ActiveSheet.Cells(1, 1)
Worksheet_Change rng, ActiveSheet
End Sub
Private Sub Worksheet_Change(ByVal Target As Range, ByVal sht As Worksheet)
Dim objData As DataObject ' Set a reference to MS Forms 2.0
Dim sHTML As String
Dim sSelAdd As String
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
Set objData = New DataObject
sHTML = Target.Text
objData.SetText sHTML
objData.PutInClipboard
Target.Select
sht.PasteSpecial Format:="Unicode Text"
End If
Application.EnableEvents = True
End Sub
Try this:
$('button:eq(0)',$('#dialog_id').dialog.buttons).button('disable');
You can say Dispatcher Servlet acts as an entry and exit point for any request. Whenever a request comes it first goes to the Dispatcher Servlet(DS) where the DS then tries to identify its handler method ( the methods you define in the controller to handle the requests ), once the handler mapper (The DS asks the handler mapper) returns the controller the dispatcher servlet knows the controller which can handle this request and can now go to this controller to further complete the processing of the request. Now the controller can respond with an appropriate response and then the DS goes to the view resolver to identify where the view is located and once the view resolver tells the DS it then grabs that view and returns it back to you as the final response. I am adding an image which I took from YouTube from the channel Java Guides.
There are libraries that do charset conversion in Javascript. But if you want something simple, this function does approximately what you want:
function stringToBytes(text) {
const length = text.length;
const result = new Uint8Array(length);
for (let i = 0; i < length; i++) {
const code = text.charCodeAt(i);
const byte = code > 255 ? 32 : code;
result[i] = byte;
}
return result;
}
If you want to convert the resulting byte array into a Blob, you would do something like this:
const originalString = 'ååå';
const bytes = stringToBytes(originalString);
const blob = new Blob([bytes.buffer], { type: 'text/plain; charset=ISO-8859-1' });
Now, keep in mind that some apps do accept UTF-8 encoding, but they can't guess the encoding unless you prepend a BOM character, as explained here.
It seems that the version "20140702" of the example link in the question was the final version, because I downloaded this file on the 12th November 2014, i.e. the version from the 2nd of July 2014 was still the latest version on 12th of November. When I try manually all the possible versions/dates between today in this date, then I always get a page with error code "404" (file not found), which indicates that no new version was released since the 12th of November.
background:url("img/content-bg.jpg") no-repeat;
background-position:center;
background-size:cover;
or
background-size:100%;
There is no way to dynamically increase the heap programatically since the heap is allocated when the Java Virtual Machine is started.
However, you can use this command
java -Xmx1024M YourClass
to set the memory to 1024
or, you can set a min max
java -Xms256m -Xmx1024m YourClassNameHere
Try this way,hope this will help you to solve your problem.
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MyActivity.java
public class MyActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webView);
webView.loadData("<a href=\"tel:+1800229933\">Call us free!</a>", "text/html", "utf-8");
}
}
Please add this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.CALL_PHONE"/>
This solved my problem. I added this line before the request is made:
System.Net.ServicePointManager.Expect100Continue = false;
It seemed there were a proxy in the way of the server that not supported 100-continue behavior.
In java config,make sure you have import your config in RootConfig like this @Import(PersistenceJPAConfig.class)
Just to extend the accepted answer:
From version 2.7
and 3.1
python has got set
literal {}
in form of usage {1,2,3}
, but {}
itself still used for empty dict.
Python 2.7 (first line is invalid in Python <2.7)
>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>
Python 3.x
>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>
More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes
I think you can still rely on CSS
ctx.measureText().height doesn’t exist.
Luckily, through CSS hack-ardry ( seeTypographic Metrics for more ways to fix older implementations of using CSS measurements), we can find the height of the text through measuring the offsetHeight of a with the same font-properties:
var d = document.createElement(”span”);
d.font = “20px arial”
d.textContent = “Hello world!”
var emHeight = d.offsetHeight;
from: http://www.html5rocks.com/en/tutorials/canvas/texteffects/
Sadly, Mark Rushakoff's answer (now deleted - it referenced the code from here) does not seem to work correctly when adapted to:
source=/home/part2/part3/part4
target=/work/proj1/proj2
The thinking outlined in the commentary can be refined to make it work correctly for most cases. I'm about to assume that the script takes a source argument (where you are) and a target argument (where you want to get to), and that either both are absolute pathnames or both are relative. If one is absolute and the other relative, the easiest thing is to prefix the relative name with the current working directory - but the code below does not do that.
The code below is close to working correctly, but is not quite right.
xyz/./pqr
'.xyz/../pqr
'../
' from paths.Dennis's code is better because it fixes 1 and 5 - but has the same issues 2, 3, 4. Use Dennis's code (and up-vote it ahead of this) because of that.
(NB: POSIX provides a system call realpath()
that resolves pathnames so that there are no symlinks left in them. Applying that to the input names, and then using Dennis's code would give the correct answer each time. It is trivial to write the C code that wraps realpath()
- I've done it - but I don't know of a standard utility that does so.)
For this, I find Perl easier to use than shell, though bash has decent support for arrays and could probably do this too - exercise for the reader. So, given two compatible names, split them each into components:
Thus:
#!/bin/perl -w
use strict;
# Should fettle the arguments if one is absolute and one relative:
# Oops - missing functionality!
# Split!
my(@source) = split '/', $ARGV[0];
my(@target) = split '/', $ARGV[1];
my $count = scalar(@source);
$count = scalar(@target) if (scalar(@target) < $count);
my $relpath = "";
my $i;
for ($i = 0; $i < $count; $i++)
{
last if $source[$i] ne $target[$i];
}
$relpath = "." if ($i >= scalar(@source) && $relpath eq "");
for (my $s = $i; $s < scalar(@source); $s++)
{
$relpath = "../$relpath";
}
$relpath = "." if ($i >= scalar(@target) && $relpath eq "");
for (my $t = $i; $t < scalar(@target); $t++)
{
$relpath .= "/$target[$t]";
}
# Clean up result (remove double slash, trailing slash, trailing slash-dot).
$relpath =~ s%//%/%;
$relpath =~ s%/$%%;
$relpath =~ s%/\.$%%;
print "source = $ARGV[0]\n";
print "target = $ARGV[1]\n";
print "relpath = $relpath\n";
Test script (the square brackets contain a blank and a tab):
sed 's/#.*//;/^[ ]*$/d' <<! |
/home/part1/part2 /home/part1/part3
/home/part1/part2 /home/part4/part5
/home/part1/part2 /work/part6/part7
/home/part1 /work/part1/part2/part3/part4
/home /work/part2/part3
/ /work/part2/part3/part4
/home/part1/part2 /home/part1/part2/part3/part4
/home/part1/part2 /home/part1/part2/part3
/home/part1/part2 /home/part1/part2
/home/part1/part2 /home/part1
/home/part1/part2 /home
/home/part1/part2 /
/home/part1/part2 /work
/home/part1/part2 /work/part1
/home/part1/part2 /work/part1/part2
/home/part1/part2 /work/part1/part2/part3
/home/part1/part2 /work/part1/part2/part3/part4
home/part1/part2 home/part1/part3
home/part1/part2 home/part4/part5
home/part1/part2 work/part6/part7
home/part1 work/part1/part2/part3/part4
home work/part2/part3
. work/part2/part3
home/part1/part2 home/part1/part2/part3/part4
home/part1/part2 home/part1/part2/part3
home/part1/part2 home/part1/part2
home/part1/part2 home/part1
home/part1/part2 home
home/part1/part2 .
home/part1/part2 work
home/part1/part2 work/part1
home/part1/part2 work/part1/part2
home/part1/part2 work/part1/part2/part3
home/part1/part2 work/part1/part2/part3/part4
!
while read source target
do
perl relpath.pl $source $target
echo
done
Output from the test script:
source = /home/part1/part2
target = /home/part1/part3
relpath = ../part3
source = /home/part1/part2
target = /home/part4/part5
relpath = ../../part4/part5
source = /home/part1/part2
target = /work/part6/part7
relpath = ../../../work/part6/part7
source = /home/part1
target = /work/part1/part2/part3/part4
relpath = ../../work/part1/part2/part3/part4
source = /home
target = /work/part2/part3
relpath = ../work/part2/part3
source = /
target = /work/part2/part3/part4
relpath = ./work/part2/part3/part4
source = /home/part1/part2
target = /home/part1/part2/part3/part4
relpath = ./part3/part4
source = /home/part1/part2
target = /home/part1/part2/part3
relpath = ./part3
source = /home/part1/part2
target = /home/part1/part2
relpath = .
source = /home/part1/part2
target = /home/part1
relpath = ..
source = /home/part1/part2
target = /home
relpath = ../..
source = /home/part1/part2
target = /
relpath = ../../../..
source = /home/part1/part2
target = /work
relpath = ../../../work
source = /home/part1/part2
target = /work/part1
relpath = ../../../work/part1
source = /home/part1/part2
target = /work/part1/part2
relpath = ../../../work/part1/part2
source = /home/part1/part2
target = /work/part1/part2/part3
relpath = ../../../work/part1/part2/part3
source = /home/part1/part2
target = /work/part1/part2/part3/part4
relpath = ../../../work/part1/part2/part3/part4
source = home/part1/part2
target = home/part1/part3
relpath = ../part3
source = home/part1/part2
target = home/part4/part5
relpath = ../../part4/part5
source = home/part1/part2
target = work/part6/part7
relpath = ../../../work/part6/part7
source = home/part1
target = work/part1/part2/part3/part4
relpath = ../../work/part1/part2/part3/part4
source = home
target = work/part2/part3
relpath = ../work/part2/part3
source = .
target = work/part2/part3
relpath = ../work/part2/part3
source = home/part1/part2
target = home/part1/part2/part3/part4
relpath = ./part3/part4
source = home/part1/part2
target = home/part1/part2/part3
relpath = ./part3
source = home/part1/part2
target = home/part1/part2
relpath = .
source = home/part1/part2
target = home/part1
relpath = ..
source = home/part1/part2
target = home
relpath = ../..
source = home/part1/part2
target = .
relpath = ../../..
source = home/part1/part2
target = work
relpath = ../../../work
source = home/part1/part2
target = work/part1
relpath = ../../../work/part1
source = home/part1/part2
target = work/part1/part2
relpath = ../../../work/part1/part2
source = home/part1/part2
target = work/part1/part2/part3
relpath = ../../../work/part1/part2/part3
source = home/part1/part2
target = work/part1/part2/part3/part4
relpath = ../../../work/part1/part2/part3/part4
This Perl script works fairly thoroughly on Unix (it does not take into account all the complexities of Windows path names) in the face of weird inputs. It uses the module Cwd
and its function realpath
to resolve the real path of names that exist, and does a textual analysis for paths that don't exist. In all cases except one, it produces the same output as Dennis's script. The deviant case is:
source = home/part1/part2
target = .
relpath1 = ../../..
relpath2 = ../../../.
The two results are equivalent - just not identical. (The output is from a mildly modified version of the test script - the Perl script below simply prints the answer, rather than the inputs and the answer as in the script above.) Now: should I eliminate the non-working answer? Maybe...
#!/bin/perl -w
# Based loosely on code from: http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2005-10/1256.html
# Via: http://stackoverflow.com/questions/2564634
use strict;
die "Usage: $0 from to\n" if scalar @ARGV != 2;
use Cwd qw(realpath getcwd);
my $pwd;
my $verbose = 0;
# Fettle filename so it is absolute.
# Deals with '//', '/./' and '/../' notations, plus symlinks.
# The realpath() function does the hard work if the path exists.
# For non-existent paths, the code does a purely textual hack.
sub resolve
{
my($name) = @_;
my($path) = realpath($name);
if (!defined $path)
{
# Path does not exist - do the best we can with lexical analysis
# Assume Unix - not dealing with Windows.
$path = $name;
if ($name !~ m%^/%)
{
$pwd = getcwd if !defined $pwd;
$path = "$pwd/$path";
}
$path =~ s%//+%/%g; # Not UNC paths.
$path =~ s%/$%%; # No trailing /
$path =~ s%/\./%/%g; # No embedded /./
# Try to eliminate /../abc/
$path =~ s%/\.\./(?:[^/]+)(/|$)%$1%g;
$path =~ s%/\.$%%; # No trailing /.
$path =~ s%^\./%%; # No leading ./
# What happens with . and / as inputs?
}
return($path);
}
sub print_result
{
my($source, $target, $relpath) = @_;
if ($verbose)
{
print "source = $ARGV[0]\n";
print "target = $ARGV[1]\n";
print "relpath = $relpath\n";
}
else
{
print "$relpath\n";
}
exit 0;
}
my($source) = resolve($ARGV[0]);
my($target) = resolve($ARGV[1]);
print_result($source, $target, ".") if ($source eq $target);
# Split!
my(@source) = split '/', $source;
my(@target) = split '/', $target;
my $count = scalar(@source);
$count = scalar(@target) if (scalar(@target) < $count);
my $relpath = "";
my $i;
# Both paths are absolute; Perl splits an empty field 0.
for ($i = 1; $i < $count; $i++)
{
last if $source[$i] ne $target[$i];
}
for (my $s = $i; $s < scalar(@source); $s++)
{
$relpath = "$relpath/" if ($s > $i);
$relpath = "$relpath..";
}
for (my $t = $i; $t < scalar(@target); $t++)
{
$relpath = "$relpath/" if ($relpath ne "");
$relpath = "$relpath$target[$t]";
}
print_result($source, $target, $relpath);
If you've installed 32-bit Office on a 64-bit machine, you may need to check for the presence of "SOFTWARE\Wow6432Node\Microsoft\Office\12.0\", substituting the 12.0 with the appropriate version. This is certainly the case for Office 2007 installed on 64-bit Windows 7.
Note that Office 2010 (== 14.0) is the first Office for which a 64-bit version exists.
If it's WPF, there is a collection of colors in the static class Brushes
.
TextBox.Background = Brushes.Red;
Of course, you can create your own brush if you want.
LinearGradientBrush myBrush = new LinearGradientBrush();
myBrush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
myBrush.GradientStops.Add(new GradientStop(Colors.Orange, 0.5));
myBrush.GradientStops.Add(new GradientStop(Colors.Red, 1.0));
TextBox.Background = myBrush;
Suppose you bound your combobox to a List<Person>
List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource
pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;
Of course this means that you need to add a checking code when you try to use the info from the combobox
if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
MessageBox.Show("Please select a person name");
else
......
The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection
In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to
DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
I fixed this problem with sql command line:
connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;
Restart database.
You can use the jquery.soap plugin to do the work for you.
This script uses $.ajax to send a SOAPEnvelope. It can take XML DOM, XML string or JSON as input and the response can be returned as either XML DOM, XML string or JSON too.
Example usage from the site:
$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',
data: {
name: 'Remy Blom',
msg: 'Hi!'
},
success: function (soapResponse) {
// do stuff with soapResponse
// if you want to have the response as JSON use soapResponse.toJSON();
// or soapResponse.toString() to get XML string
// or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
// show error
}
});
see nditer
import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
y += 3
Y == np.array([6, 7, 8, 9])
y = 3
would not work, usey *= 0
andy += 3
instead.
if in case you are not using name in input but other element, then you can target other element with there attribute.
[title~=flower] {_x000D_
border: 5px solid yellow;_x000D_
}
_x000D_
<img src="klematis.jpg" title="klematis flower" width="150" height="113">_x000D_
<img src="img_flwr.gif" title="flower" width="224" height="162">_x000D_
<img src="img_flwr.gif" title="flowers" width="224" height="162">
_x000D_
hope its help. Thank you
Have you tried?
var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
// "2013-10-10T22:10:00"
dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern);
// "2013-10-10 22:10:00Z"
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)
Also try using parameters when you store the c# datetime value in the mySql database, this might help.
They are almost the same - all of them mean that the class is a Spring bean. @Service
, @Repository
and @Controller
are specialized @Component
s. You can choose to perform specific actions with them. For example:
@Controller
beans are used by spring-mvc@Repository
beans are eligible for persistence exception translationAnother thing is that you designate the components semantically to different layers.
One thing that @Component
offers is that you can annotate other annotations with it, and then use them the same way as @Service
.
For example recently I made:
@Component
@Scope("prototype")
public @interface ScheduledJob {..}
So all classes annotated with @ScheduledJob
are spring beans and in addition to that are registered as quartz jobs. You just have to provide code that handles the specific annotation.
Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.
After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):
index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.
from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.
EDIT 10/20/2014 - More information
I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:
If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...
Ordinarily, you can achieve this behavior using the index_col option.
There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...
If you are using Python2.6 or newer, it's convenient to use socket.create_connection
sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)
I would think that for a large part your or your client's requirements should dictate what precision and scale to use. For example, for the e-commerce website I am working on that deals with money in GBP only, I have been required to keep it to Decimal( 6, 2 ).
Extension of VolkerK's answer, to make code a little more readable, you can use AS to reference the count, example below:
SELECT COUNT(*) AS c from profile
This makes for much easier reading in some frameworks, for example, i'm using Exponent's (React Native) Sqlite integration, and without the AS statement, the code is pretty ugly.
For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str
to int
) so you must do this yourself. You'll like that in the long-run, trust me!
You could specify the title (and also the title of the axes via xlab
and ylab
) with the main
option. E.g.:
plot(data[,i], main=names(data)[i])
And if you want to plot (and save) each variable of a dataframe, you should use png
, pdf
or any other graphics driver you need, and after that issue a dev.off()
command. E.g.:
data <- read.csv("sample.csv",header=T,sep=",")
for (i in 1:length(data)) {
pdf(paste('fileprefix_', names(data)[i], '.pdf', sep='')
plot(data[,i], ylab=names(data[i]), type="l")
dev.off()
}
Or draw all plots to the same image with the mfrow
paramater of par()
. E.g.: use par(mfrow=c(2,2)
to include the next 4 plots in the same "image".
You have to create custom pipe.
import { Injectable, Pipe } from '@angular/core';
@Pipe({
name: 'keyobject'
})
@Injectable()
export class Keyobject {
transform(value, args:string[]):any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}}
And then use it in your *ngFor
*ngFor="let item of data | keyobject"
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
If you are using OkHttp for Java/Android you can use the following constant:
import com.squareup.okhttp.internal.Util;
Util.UTF_8; // Charset
Util.UTF_8.name(); // String
You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!
The better approach would be to extract this logic into reusable function on your $rootScope
:
.run(function ($rootScope) {
$rootScope.inArray = function (item, array) {
return (-1 !== array.indexOf(item));
};
})
Then, use it in your template:
<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>
I think everyone will agree that this example is much more readable and maintainable.
First convert your Chart.js canvas to base64 string.
var url_base64 = document.getElementById('myChart').toDataURL('image/png');
Set it as a href attribute for anchor tag.
link.href = url_base64;
<a id='link' download='filename.png'>Save as Image</a>
The Ruby-way (TM) since Ruby 2.3: Use the squiggly HEREDOC <<~
to define a multi-line string with newlines and proper indentation:
conn.exec <<~EOS
select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc
where etc etc etc etc etc etc etc etc etc etc etc etc etc
EOS
# -> "select...\nfrom...\nwhere..."
If proper indentation is not a concern, then single and double quotes can span multiple lines in Ruby:
conn.exec "select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc"
# -> "select...\n from...\n where..."
If single or double quotes are cumbersome because that would need lots of escaping, then the percent string literal notation %
is the most flexible solution:
conn.exec %(select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc
where (ProductLine = 'R' OR ProductLine = "S") AND Country = "...")
# -> "select...\n from...\n where..."
If the aim is to avoid the newlines (which both the squiggly HEREDOC, quotes and the percent string literal will cause), then a line continuation can be used by putting a backslash \
as the last non-whitespace character in a line. This will continue the line and will cause Ruby to concatenate the Strings back to back (watch out for those spaces inside the quoted string):
conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 ' \
'from table1, table2, table3, etc, etc, etc, etc, etc, ' \
'where etc etc etc etc etc etc etc etc etc etc etc etc etc'
# -> "select...from...where..."
If you use Rails, then String.squish
will strip the string of leading and trailing space and collapse all consecutive whitespaces (newlines, tabs, and all) into a single space:
conn.exec "select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc".squish
# -> "select...attr7 from...etc, where..."
More details:
The Here Document Notation for Strings is a way to designate long blocks of text inline in code. It is started by <<
followed by a user-defined String (the End of String terminator). All following lines are concatenated until the End of String terminator is found at the very beginning of a line:
puts <<HEREDOC
Text Text Text Text
Bla Bla
HEREDOC
# -> "Text Text Text Text\nBlaBla"
The End of String terminator can be chosen freely, but it is common to use something like "EOS" (End of String) or something that matches the domain of the String such as "SQL".
HEREDOC supports interpolation by default or when the EOS terminator is double quoted:
price = 10
print <<"EOS" # comments can be put here
1.) The price is #{price}.
EOS
# -> "1.) The price is 10."
Interpolation can be disabled if the EOS terminator is single quoted:
print <<'EOS' # Disabled interpolation
3.) The price is #{price}.
EOS
# -> "3.) The price is #{price}."
One important restriction of the <<HEREDOC
is that the End of String terminator needs to be at the beginning of the line:
puts <<EOS
def foo
print "foo"
end
EOS
EOS
#-> "....def foo\n......print "foo"\n....end\n..EOS"
To get around this, the <<-
syntax was created. It allows the EOS terminator to be indented to make the code look nicer. The lines between the <<-
and EOS terminator are still used in their full extend including all indentation:
def printExample
puts <<-EOS # Use <<- to indent End of String terminator
def foo
print "foo"
end
EOS
end
# -> "....def foo\n......print "foo"\n....end"
Since Ruby 2.3, we now have the squiggly HEREDOC <<~
removes leading whitespace:
puts <<~EOS # Use the squiggly HEREDOC <<~ to remove leading whitespace (since Ruby 2.3!)
def foo
print "foo"
end
EOS
# -> "def foo\n..print "foo"\nend"
Empty lines and lines which only contains tabs and space are ignored by <<~
puts <<~EOS.inspect
Hello
World!
EOS
#-> "Hello\n..World!"
If both tabs and spaces are used, tabs are considered as equal to 8 spaces. If the least-indented line is in the middle of a tab, this tab is not removed.
puts <<~EOS.inspect
<tab>One Tab
<space><space>Two Spaces
EOS
# -> "\tOne Tab\nTwoSpaces"
HEREDOC can do some crazy stuff such as executing commands using backticks:
puts <<`EOC`
echo #{price}
echo #{price * 2}
EOC
HEREDOC String definitions can be "stacked", which means that the first EOS terminator (EOSFOO below) will end the first string and start the second (EOSBAR below):
print <<EOSFOO, <<EOSBAR # you can stack them
I said foo.
EOSFOO
I said bar.
EOSBAR
I don't think anybody would ever use it as such, but the <<EOS
is really just a string literal and can be put whereever a string can normally be put:
def func(a,b,c)
puts a
puts b
puts c
end
func(<<THIS, 23, <<THAT)
Here's a line
or two.
THIS
and here's another.
THAT
If you don't have Ruby 2.3, but Rails >=
3.0 then you can use String.strip_heredoc
which does the same as <<~
# File activesupport/lib/active_support/core_ext/string/strip.rb, line 22
class String
def strip_heredoc
gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "".freeze)
end
end
puts <<-USAGE.strip_heredoc # If no Ruby 2.3, but Rails >= 3.0
This command does such and such.
Supported options are:
-h This message
...
USAGE
If you see errors when Ruby parses your file, then it is most likely that you either have extra leading or trailing spaces with a HEREDOC or extra trailing spaces with a squiggly HEREDOC. For example:
What you see:
database_yml = <<~EOS
production:
database: #{fetch(:user)}
adapter: postgresql
pool: 5
timeout: 5000
EOS
What Ruby tells you:
SyntaxError: .../sample.rb:xx: can't find string "EOS" anywhere before EOF
...sample.rb:xx: syntax error, unexpected end-of-input, expecting `end'
What is at fault:
Spot the extra spaces after the terminating EOS.
See RubyDoc for how to use the percentage sign followed by a string in a parentheses pair such as a %(...)
, %[...]
, %{...}
, etc. or a pair of any non-alphanumeric character such as %+...+
Last, to get the answer to the original question "Is there a way to imply concatenation?" answered: Ruby always implies concatenation if two strings (single and double quoted) are found back to back:
puts "select..." 'from table...' "where..."
# -> "select...from table...where..."
The caveat is that this does not work across line-breaks, because Ruby is interpreting an end of statement and the consequitive line of just strings alone on a line doesn't do anything.
This is all because you are not in the desired directory. You need to first get into the desired directory. Mine was angular-phonecat directory. So I typed in cd angular-phonecat
and then npm install
.
Also worth noting window.scrollBy(dx,dy)
(ref)
VBA subs are no macros. A VBA sub can be a macro, but it is not a must.
The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.
The more elegant way is, to design and write your own VBA code without using the macro features!
VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.
If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".
In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.
It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.
In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.
You can do it with two find/replace sequences
:6,10s/<search_string>/<replace_string>/g
:14,18s/<search_string>/<replace_string>/g
The second time all you need to adjust is the range so instead of typing it all out, I would recall the last command and edit just the range
You can set location.href
to a data URI containing the data you want to let the user download. Besides this, I don't think there's any way to do it with just JavaScript.
What I have just experiment with VS diagnostic tools is I called this.Close() then formclosing event triggered. Then When I call this.Dispose() at the end in Formclosing event where I dispose many other objects in it, it cleans everything much much smoother.
I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/
The interesting bit is that I apply the data-bind attribute to an element I didn't define:
var handle = slider.slider().find(".ui-slider-handle").first();
$(handle).attr("data-bind", "tooltip: viewModel.value");
ko.applyBindings(viewModel.value, $(handle)[0]);
C# does not support multiple inheritance built in.
For adding multiple inheritance to languages that does not support it, You can use twin design pattern
You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.
Above all answers are right but there is another method also which is very handy.
Pre-condition: Your project is Maven project Or converts it to Maven project.
RightclickOnProject > Configuration > Convert in to Maven Project
1. Select any jar for which you want to download sources or javadocs.
2. RightClick > Maven > Download javadoc or Download javasources
public class NameValue
{
public string Name { get; set; }
public object Value { get; set; }
}
public class NameValue
{
public string Name { get; set; }
public object Value { get; set; }
}
public static List<NameValue> EnumToList<T>()
{
var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>());
var array2 = Enum.GetNames(typeof(T)).ToArray<string>();
List<NameValue> lst = null;
for (int i = 0; i < array.Length; i++)
{
if (lst == null)
lst = new List<NameValue>();
string name = array2[i];
T value = array[i];
lst.Add(new NameValue { Name = name, Value = value });
}
return lst;
}
Convert Enum To a list more information available here.
The Date.getTime()
method can be used with a little tweak:
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
Divide the result by 1000 to get the Unix timestamp, floor
if necessary:
(new Date).getTime() / 1000
The Date.valueOf()
method is functionally equivalent to Date.getTime()
, which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.
Use DataFrame.to_excel from pandas. Pandas allows you to represent your data in functionally rich datastructures and will let you read in excel files as well.
You will first have to convert your data into a DataFrame and then save it into an excel file like so:
In [1]: from pandas import DataFrame
In [2]: l1 = [1,2,3,4]
In [3]: l2 = [1,2,3,4]
In [3]: df = DataFrame({'Stimulus Time': l1, 'Reaction Time': l2})
In [4]: df
Out[4]:
Reaction Time Stimulus Time
0 1 1
1 2 2
2 3 3
3 4 4
In [5]: df.to_excel('test.xlsx', sheet_name='sheet1', index=False)
and the excel file that comes out looks like this:
Note that both lists need to be of equal length else pandas will complain. To solve this, replace all missing values with None
.
The PHP.net recommended way of setting the charset is now this:
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
Chrome did change their menus since this question was asked. This solution was tested with Chrome 47.0.2526.73 to 72.0.3626.109.
If you are using Chrome right now, you can check your version with : chrome://version
OLDER VERSIONS:
Scroll down to the bottom of the page and click on "Show advanced settings..." to show more settings.
OLDER VERSIONS:
In the "Network" section, click on "Change proxy settings...".
That's it.
Try this: http://jsfiddle.net/8fv6e/8/
It is another version of the answers.
HTML:
<label for="aboutDescription" id="aboutHeading">About</label>
<textarea rows="15" cols="50" id="aboutDescription"
style="max-height:100px;min-height:100px; resize: none"></textarea>
<a id="imageURLId" target="_blank">Go to
HomePage</a>
CSS:
#imageURLId{
font-size: 14px;
font-weight: normal;
resize: none;
overflow-y: scroll;
}
artejera, do you mean Selenium as plugin to your browser (Selenium IDE)? Here is something for automation in Google Chrome.
But if you want to work with Selenium RC, just set up browser in your test script. There is setBrowser() method in Selenium.
MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool
To create a package, run the following command (replace Default Web Site with your web site name):
msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log
To restore the package, run the following command:
msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log
try this code: :)
get value:
$("#Ostans option:selected").val() + '.' + $("#shahrha option:selected").val()
get text:
$("#Ostans option:selected").text() + '.' + $("#shahrha option:selected").text()
Use smaller h
// 24 hrs
H:i
// output 14:20
// 12 hrs
h:i
// output 2:20
From the javadoc:
The serialization runtime associates with each serializable class a version number, called a
serialVersionUID
, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a differentserialVersionUID
than that of the corresponding sender's class, then deserialization will result in anInvalidClassException
. A serializable class can declare its ownserialVersionUID
explicitly by declaring a field named"serialVersionUID"
that must be static, final, and of type long:
You can configure your IDE to:
As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":
No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException
.
apply this code for get the ipaddress:
if (getenv('HTTP_X_FORWARDED_FOR')) { $pipaddress = getenv('HTTP_X_FORWARDED_FOR');
$ipaddress = getenv('REMOTE_ADDR');
echo "Your Proxy IP address is : ".$pipaddress. "(via $ipaddress)" ; }
else { $ipaddress = getenv('REMOTE_ADDR'); echo "Your IP address is : $ipaddress"; }
------------------------------------------------------------------------
OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:
UPDATE table1
SET col1 = subquery.col2,
col2 = subquery.col3
FROM (
SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3
FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;
The math.log
function is to the base e
, i.e. natural logarithm. If you want to the base 10 use math.log10
.
You have writer.close();
in your code. So bash receives EOF on its stdin
and exits. Then you get Broken pipe
when trying to read from the stdout
of the defunct bash.
Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want
x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)
WORD.C <- function(WORDS){
require(wordcloud)
L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))
# Takes a dataframe and the text you want to display
FUN <- function(X, text){
windows()
wordcloud(X[, 1], X[, 2], min.freq=1)
mtext(text, 3, padj=-4.5, col="red") #what I'm trying that isn't working
}
# Now creates the sequence 1,...,length(L2)
# Loops over that and then create an anonymous function
# to send in the information you want to use.
lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})
# Since you asked about loops
# you could use i in seq_along(L2)
# instead of 1:length(L2) if you wanted to
#for(i in 1:length(L2)){
# FUN(L2[[i]], names(L2)[i])
#}
}
WORD.C(list.xy)
If you want to mark the type of a dataframe column as a string, you can do:
df['A'].dtype.kind
An example:
In [8]: df = pd.DataFrame([[1,'a',1.2],[2,'b',2.3]])
In [9]: df[0].dtype.kind, df[1].dtype.kind, df[2].dtype.kind
Out[9]: ('i', 'O', 'f')
The answer for your code:
for y in agg.columns:
if(agg[y].dtype.kind == 'f' or agg[y].dtype.kind == 'i'):
treat_numeric(agg[y])
else:
treat_str(agg[y])
Note:
uint
and UInt
are of kind u
, not kind i
.pd.api.types.is_integer_dtype
.Basically, don't use DateTime.MinValue
to represent a missing value. You can't use DateTime.MinValue
in a SQL Server DateTime field, as SQL Server has a minimum value of the start of 1753.
Instead, make your BirthDate
property a Nullable<DateTime>
(aka DateTime?
), and set it to null
when you don't have a value. Also make sure your database field is nullable. Then you just need to make sure that that null
ends up as a NULL
value in the database. Exactly how you do that will depend on your data access, which you haven't told us anything about.
Here is what the standard C99 (ISO-IEC 9899 6.2.5 §10) or C++2003 (ISO-IEC 14882-2003 3.1.9 §8) standards say:
There are three floating point types:
float
,double
, andlong double
. The typedouble
provides at least as much precision asfloat
, and the typelong double
provides at least as much precision asdouble
. The set of values of the typefloat
is a subset of the set of values of the typedouble
; the set of values of the typedouble
is a subset of the set of values of the typelong double
.
The C++ standard adds:
The value representation of floating-point types is implementation-defined.
I would suggest having a look at the excellent What Every Computer Scientist Should Know About Floating-Point Arithmetic that covers the IEEE floating-point standard in depth. You'll learn about the representation details and you'll realize there is a tradeoff between magnitude and precision. The precision of the floating point representation increases as the magnitude decreases, hence floating point numbers between -1 and 1 are those with the most precision.
Just skip the excel part - the excel user forms are just a poor man's version of the way more robust Access forms. Also Access VBA is identical to Excel VBA - you just have to learn Access' object model. With a simple application you won't need to write much VBA anyways because in Access you can wire things together quite easily.
Here is a React Hooks specific solution for
Warning: Can't perform a React state update on an unmounted component.
You can declare let isMounted = true
inside useEffect
, which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally:
useEffect(() => {
let isMounted = true; // note this flag denote mount status
someAsyncOperation().then(data => {
if (isMounted) setState(data);
})
return () => { isMounted = false }; // use effect cleanup to set flag false, if unmounted
});
const Parent = () => {_x000D_
const [mounted, setMounted] = useState(true);_x000D_
return (_x000D_
<div>_x000D_
Parent:_x000D_
<button onClick={() => setMounted(!mounted)}>_x000D_
{mounted ? "Unmount" : "Mount"} Child_x000D_
</button>_x000D_
{mounted && <Child />}_x000D_
<p>_x000D_
Unmount Child, while it is still loading. It won't set state later on,_x000D_
so no error is triggered._x000D_
</p>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
const Child = () => {_x000D_
const [state, setState] = useState("loading (4 sec)...");_x000D_
useEffect(() => {_x000D_
let isMounted = true; // note this mounted flag_x000D_
fetchData();_x000D_
return () => {_x000D_
isMounted = false;_x000D_
}; // use effect cleanup to set flag false, if unmounted_x000D_
_x000D_
// simulate some Web API fetching_x000D_
function fetchData() {_x000D_
setTimeout(() => {_x000D_
// drop "if (isMounted)" to trigger error again_x000D_
if (isMounted) setState("data fetched");_x000D_
}, 4000);_x000D_
}_x000D_
}, []);_x000D_
_x000D_
return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
useAsync
HookWe can encapsulate all the boilerplate into a custom Hook, that just knows, how to deal with and automatically abort async functions in case the component unmounts before:
function useAsync(asyncFn, onSuccess) {
useEffect(() => {
let isMounted = true;
asyncFn().then(data => {
if (isMounted) onSuccess(data);
});
return () => { isMounted = false };
}, [asyncFn, onSuccess]);
}
// use async operation with automatic abortion on unmount_x000D_
function useAsync(asyncFn, onSuccess) {_x000D_
useEffect(() => {_x000D_
let isMounted = true;_x000D_
asyncFn().then(data => {_x000D_
if (isMounted) onSuccess(data);_x000D_
});_x000D_
return () => {_x000D_
isMounted = false;_x000D_
};_x000D_
}, [asyncFn, onSuccess]);_x000D_
}_x000D_
_x000D_
const Child = () => {_x000D_
const [state, setState] = useState("loading (4 sec)...");_x000D_
useAsync(delay, setState);_x000D_
return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
const Parent = () => {_x000D_
const [mounted, setMounted] = useState(true);_x000D_
return (_x000D_
<div>_x000D_
Parent:_x000D_
<button onClick={() => setMounted(!mounted)}>_x000D_
{mounted ? "Unmount" : "Mount"} Child_x000D_
</button>_x000D_
{mounted && <Child />}_x000D_
<p>_x000D_
Unmount Child, while it is still loading. It won't set state later on,_x000D_
so no error is triggered._x000D_
</p>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
const delay = () => new Promise(resolve => setTimeout(() => resolve("data fetched"), 4000));_x000D_
_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'
Now rows that were like
http://www.example.com/articles/updates/43
will be
http://www.example.com/articles/news/43
#include
works just like the C #include
.
#import
keeps track of which headers have already been included and is ignored if a header is imported more than once in a compilation unit. This makes it unnecessary to use header guards.
The bottom line is just use #import
in Objective-C and don't worry if your headers wind up importing something more than once.
Let's just say you have 3 buttons:
<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">
To style the disabled button you can use the following css:
input[type="button"]:disabled{
color:#000;
}
This will only affect the button which is disabled.
To stop the color changing when hovering you can use this too:
input[type="button"]:disabled:hover{
color:#000;
}
You can also avoid this by using a css-reset.
You can use the .hide()
function bound to a click
handler:
$('#Comanda').click(function() {
$(this).hide();
});
Use a version of pip
installed against the Python instance you want to install new packages to.
In many distributions, there may be separate python2.6-pip
and python2.7-pip
packages, invoked with binary names such as pip-2.6
and pip-2.7
. If pip is not packaged in your distribution for the desired target, you might look for a setuptools or easyinstall package, or use virtualenv (which will always include pip in a generated environment).
pip's website includes installation instructions, if you can't find anything within your distribution.
DELETE FROM on_search
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))
Simple way? Use strip_tags()
:
$str = strip_tags($input);
You can also use filter_var()
for that:
$str = filter_var($input, FILTER_SANITIZE_STRING);
The advantage of filter_var()
is that you can control the behaviour by, for example, stripping or encoding low and high characters.
Here is a list of sanitizing filters.
I just ran into this question and, while it is old, I figured I'd add an answer for the archives. The OP asked about for loops, but their goal was to gather a random sample of rows from the table. For that task, Postgres 9.5+ offers the TABLESAMPLE clause on WHERE. Here's a good rundown:
https://www.2ndquadrant.com/en/blog/tablesample-in-postgresql-9-5-2/
I tend to use Bernoulli as it's row-based rather than page-based, but the original question is about a specific row count. For that, there's a built-in extension:
https://www.postgresql.org/docs/current/tsm-system-rows.html
CREATE EXTENSION tsm_system_rows;
Then you can grab whatever number of rows you want:
select * from playtime tablesample system_rows (15);
I was facing the same issue in bitbucket, and this worked for me:
line1
##<2 white spaces><enter>
line2
If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID
instead of HardwareID
in the driver's INF Models section
final static String EXTRA_MESSAGE = "edit.list.message";
Context context;
public void onClick (View view)
{
Intent intent = new Intent(this,display.class);
RelativeLayout relativeLayout = (RelativeLayout) view.getParent();
TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
String message = textView.getText().toString();
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
The identity (===)
operator behaves identically to the equality (==)
operator except no type conversion is done, and the types must be the same to be considered equal.
Edit
Solution mentioned by @leftclickben is also effective. We can also use a stored procedure for the same.
CREATE PROCEDURE get_tree(IN id int)
BEGIN
DECLARE child_id int;
DECLARE prev_id int;
SET prev_id = id;
SET child_id=0;
SELECT col3 into child_id
FROM table1 WHERE col1=id ;
create TEMPORARY table IF NOT EXISTS temp_table as (select * from table1 where 1=0);
truncate table temp_table;
WHILE child_id <> 0 DO
insert into temp_table select * from table1 WHERE col1=prev_id;
SET prev_id = child_id;
SET child_id=0;
SELECT col3 into child_id
FROM TABLE1 WHERE col1=prev_id;
END WHILE;
select * from temp_table;
END //
We are using temp table to store results of the output and as the temp tables are session based we wont there will be not be any issue regarding output data being incorrect.
SQL FIDDLE Demo
Try this query:
SELECT
col1, col2, @pv := col3 as 'col3'
FROM
table1
JOIN
(SELECT @pv := 1) tmp
WHERE
col1 = @pv
SQL FIDDLE Demo
:| COL1 | COL2 | COL3 |
+------+------+------+
| 1 | a | 5 |
| 5 | d | 3 |
| 3 | k | 7 |
Note
parent_id
value should be less than thechild_id
for this solution to work.
string_arr.map(&:inspect).join(',') # or other separator
One of the biggest problems with delivering live events on Internet is 'scale', and TCP doesn’t scale well. For example when you are beaming a live football match -as opposed to an on demand movie playback- the number of people watching can easily be 1000 times more. In such a scenario using TCP is a death sentence for the CDNs (content delivery networks).
There are a couple of main reasons why TCP doesn't scale well:
One of the largest tradeoffs of TCP is the variability of throughput achievable between the sender and the receiver. When streaming video over the Internet the video packets must traverse multiple routers over the Internet, each of these routers is connected with different speed connections. The TCP algorithm starts with TCP window off small, then grows until packet loss is detected, the packet loss is considered a sign of congestion and TCP responds to it by drastically reducing the window size to avoid congestion. Thus in turn reducing the effective throughput immediately. Now imagine a network with TCP transmission using 6-7 router hops to the client (a very normal scenario), if any of the intermediate router looses any packet, the TCP for that link will reduce the transmission rate. In-fact The traffic flow between routers follow an hourglass kind of a shape; always gong up and down in-between one of the intermediate routers. Rendering the effective through put much lower compared to best-effort UDP.
As you may already know TCP is an acknowledgement-based protocol. Lets for example say a sender is 50ms away (i.e. latency btw two points). This would mean time it takes for a packet to be sent to a receiver and receiver to send an acknowledgement would be 100ms; thus maximum throughput possible as compared to UDP based transmission is already halved.
The TCP doesn’t support multicasting or the new emerging standard of multicasting AMT. Which means the CDNs don’t have the opportunity to reduce network traffic by replicating the packets -when many clients are watching the same content. That itself is a big enough reason for CDNs (like Akamai or Level3) to not go with TCP for live streams.
Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:
function compute() {
if ( $('input[name=type]:checked').val() != undefined ) {
var a = parseInt($('input[name=service_price]').val());
var b = parseInt($('input[name=modem_price]').val());
var total = a+b;
$('#total_price').val(a+b);
}
}
and this should work.
Here is some working example that updates the sum when the value when checkbox is checked (and if this is checked, the value is also updated when one of the fields is changed): jsfiddle.
1/3/2017 --> January the 3rd 2017
Hi there, today I found this article to achieve this, the article is called "Creating an HTML UI for Desktop .NET Applications" and is intended to embed a chromium based control in a WPF application. It saved me the day.
https://www.infoq.com/articles/html-desktop-net
I hope it helps somebody else.
NOTE: it is based on DotNetBrowser, see license agreement here: https://www.teamdev.com/dotnetbrowser-licence-agreement
Actually it's best to use:
IF DB_ID('dms') IS NOT NULL
--code mine :)
print 'db exists'
See https://docs.microsoft.com/en-us/sql/t-sql/functions/db-id-transact-sql and note that this does not make sense with the Azure SQL Database.
DataGrid.DataSource = null;
DataGrid.DataBind();
If you are using Framework 4.6
<httpRuntime targetFramework="4.6.1" requestValidationMode="2.0" maxRequestLength="10485760" />
Since Bootstrap 4 you can easily change the primary color of your Bootstrap by downloading a simple CSS file on BootstrapColor.net. You don't need to know SASS and the CSS file is ready to use for your website. You can choose the color you want like blue, indigo, purple, pink, red, orange, yellow, green, teal or cyan color.
You just need:
if (!empty($_POST['search_term']) && !empty($_POST['postcode']))
isset && !empty
is redundant.
To those that are incline to use GUI:
Click Right mouse button on procecdure name then select Test
Then in new window you will see script generated just add the parameters and click on Start Debugger
or F9
Hope this saves you some time.
In my case the problem was rendering the output.. So I used the default text if the ajax data is not present yet.
templateSelection: function(data) {
return data.name || data.element.innerText;
}
I've recently created library which helps to cope with pagination cases like:
DEMO page implements all above features.
Source code you can find on Github
If the string is already within quotes then use another quote to nullify its action.
echo "Insert tablename(col1) Values('""val1""')"
If you don't mind a Perl one-liner:
$ perl -CS -E 'say "\x{2620}"'
?
-CS
enables UTF-8 decoding on input and UTF-8 encoding on output. -E
evaluates the next argument as Perl, with modern features like say
enabled. If you don't want a newline at the end, use print
instead of say
.
In honeycomb, API level 11, it is possible, We can use setScalaX and setScaleY with pivot point
I have explained it here
Zooming a view completely
Pinch Zoom to view completely
Older SQLite command-line shells (sqlite3.exe
) do not appear to offer the .open
command or any readily identifiable alternative.
Although I found no definitive reference it seems that the .open
command was introduced around version 3.15. The SQLite Release History first mentions the .open
command with 2016-10-14 (3.15.0).
Try with this :
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
android:angle="90"
android:centerColor="#555994"
android:endColor="#b5b6d2"
android:startColor="#555994"
android:type="linear" />
<corners
android:radius="0dp"/>
</shape>
overflow: scroll;
-webkit-overflow-scrolling: touch;
On container you can set bounce effect inside element
Source: http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/
I think this is the easy way to open a URL using this function
webbrowser.open_new_tab(url)
Sometimes it can be tricky to use raw html. Mostly because of XSS vulnerability. If that is a concern, but you still want to use raw html, you can encode the scary parts.
@Html.Raw("(<b>" + Html.Encode("<script>console.log('insert')</script>" + "Hello") + "</b>)")
Results in
(<b><script>console.log('insert')</script>Hello</b>)
A Bcrypt hash can be stored in a BINARY(40)
column.
BINARY(60)
, as the other answers suggest, is the easiest and most natural choice, but if you want to maximize storage efficiency, you can save 20 bytes by losslessly deconstructing the hash. I've documented this more thoroughly on GitHub: https://github.com/ademarre/binary-mcf
Bcrypt hashes follow a structure referred to as modular crypt format (MCF). Binary MCF (BMCF) decodes these textual hash representations to a more compact binary structure. In the case of Bcrypt, the resulting binary hash is 40 bytes.
Gumbo did a nice job of explaining the four components of a Bcrypt MCF hash:
$<id>$<cost>$<salt><digest>
Decoding to BMCF goes like this:
$<id>$
can be represented in 3 bits.<cost>$
, 04-31, can be represented in 5 bits. Put these together for 1 byte.1 + 16 + 23
You can read more at the link above, or examine my PHP implementation, also on GitHub.
From Oracle (but works in most SQL DBs):
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
HAVING COUNT(*) >= 3
P.S. it's faster one, because you have no Select withing Select methods here
Three important steps - How to Task Schedule an excel.xls(m) file
simply:
IN MORE DETAIL...
`
' a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt to .vbs
'Write Excel.xls Sheet's full path here
strPath = "C:\RodsData.xlsm"
'Write the macro name - could try including module name
strMacro = "Update" ' "Sheet1.Macro2"
'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application")
objApp.Visible = True ' or False
'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath)
objApp.Run strMacro ' wbToRun.Name & "!" & strMacro
wbToRun.Save
wbToRun.Close
objApp.Quit
'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!", vbInformation
'
`
set Program/script: = C:\Windows\System32\cscript.exe
set Add arguments (optional): = C:\MyVbsFile.vbs
That should work.
Let me know!
Rod Bowen
I've been bitten loads of times by people writing their own path fiddling functions and getting it wrong. Spaces, slashes, backslashes, colons -- the possibilities for confusion are not endless, but mistakes are easily made anyway. So I'm a stickler for the use of os.path
, and recommend it on that basis.
(However, the path to virtue is not the one most easily taken, and many people when finding this are tempted to take a slippery path straight to damnation. They won't realise until one day everything falls to pieces, and they -- or, more likely, somebody else -- has to work out why everything has gone wrong, and it turns out somebody made a filename that mixes slashes and backslashes -- and some person suggests that the answer is "not to do that". Don't be any of these people. Except for the one who mixed up slashes and backslashes -- you could be them if you like.)
You can get the drive and path+file like this:
drive, path_and_file = os.path.splitdrive(path)
Get the path and the file:
path, file = os.path.split(path_and_file)
Getting the individual folder names is not especially convenient, but it is the sort of honest middling discomfort that heightens the pleasure of later finding something that actually works well:
folders = []
while 1:
path, folder = os.path.split(path)
if folder != "":
folders.append(folder)
elif path != "":
folders.append(path)
break
folders.reverse()
(This pops a "\"
at the start of folders
if the path was originally absolute. You could lose a bit of code if you didn't want that.)
here I'm providing solution to setup terraform enviroment variable in windows to beginners.
Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\
and Save it.
Try adding $(document).ready(function(){
to the beginning of your script, and then });
. Also, does the div
have the id in it properly, i.e., as an id, not a class, etc.?
There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.
You can try using Putty (freeware). It is mainly known as a SSH client, but you can use for Telnet login as well
You should catch a HttpStatusCodeException
exception:
try {
restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
int statusCode = exception.getStatusCode().value();
...
}
By default server runs on development environment: $ rails s
If you're running on production environment: $ rails s -e production
or $ RAILS_ENV=production rails s
Perl solution:
perl -ane '$maxc = $#F if $#F > $maxc; END{$maxc++; print "max columns: $maxc\nrows: $.\n"}' file
If your input file is comma-separated:
perl -F, -ane '$maxc = $#F if $#F > $maxc; END{$maxc++; print "max columns: $maxc\nrows: $.\n"}' file
output:
max columns: 5
rows: 2
-a
autosplits input line to @F
array
$#F
is the number of columns -1
-F,
field separator of , instead of whitespace
$.
is the line number (number of rows)
An easy way to pull of the p-values is to use statsmodels regression:
import statsmodels.api as sm
mod = sm.OLS(Y,X)
fii = mod.fit()
p_values = fii.summary2().tables[1]['P>|t|']
You get a series of p-values that you can manipulate (for example choose the order you want to keep by evaluating each p-value):
Another method is to use the io/ioutil
and strings
libraries to read the entire file's bytes, convert them into a string and split them using a "\n
" (newline) character as the delimiter, for example:
import (
"io/ioutil"
"strings"
)
func main() {
bytesRead, _ := ioutil.ReadFile("something.txt")
file_content := string(bytesRead)
lines := strings.Split(file_content, "\n")
}
Technically you're not reading the file line-by-line, however you are able to parse each line using this technique. This method is applicable to smaller files. If you're attempting to parse a massive file use one of the techniques that reads line-by-line.
Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders })
, where orders
was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.
.where(`order.id IN (${orders})`);
If the answers that involve tables or setting line-height don't work for you, you can experiment with wrapping the p element in a div and style its positioning relative to the height of the parent div.
.parent-div{_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
.text-div{_x000D_
position: relative;_x000D_
top: 50%;_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
_x000D_
p.event_desc{_x000D_
font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;_x000D_
color: white;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="parent-div">_x000D_
<div class="text-div">_x000D_
<p class="event_desc">_x000D_
MY TEXT_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
new SecondForm().setVisible(true);
You can either use setVisible(false)
or dispose()
method to disappear current form.
You can just set the onClick of an ImageView and also set it to be clickable, Or set the drawableBottom property of a regular button.
ImageView iv = (ImageView)findViewById(R.id.ImageView01);
iv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
I was calling parentView.removeView(childView) and childView was still showing. I eventually realized that a method was somehow being triggered twice and added the childView to the parentView twice.
So, use parentView.getChildCount() to determine how many children the parent has before you add a view and afterwards. If the child is added too many times then the top most child is being removed and the copy childView remains-which looks like removeView is working even when it is.
Also, you shouldn't use View.GONE to remove a view. If it's truly removed then you won't need to hide it, otherwise it's still there and you're just hiding it from yourself :(
This will give you the working directory of the current file.
File.dirname(__FILE__)
Example:
current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"
result: "/Users/nemrow/SITM/folder1/folder2"
It appears that with newer versions of bundler (>= 1.14) it's:
bundle update --conservative gem-name
you can resize it by displaying svg in image tag and size image tag i.e.
<img width="200px" src="lion.svg"></img>
My mongoose version is 4.10.2
Seems only the hook findOneAndUpdate
is work
ModelSchema.pre('findOneAndUpdate', function(next) {
// console.log('pre findOneAndUpdate ....')
this.update({},{ $set: { updatedAt: new Date() } });
next()
})
Restarting the computer, or using the 'kill' commands listed above solve the problem. AS for preventing it from happening, I've found this occurring anytime my computer goes to sleep. The port is obviously kept reserved, and then on wake, mysql tries to reconnect to that port, but can't. This could be your problem also.
Something like:
library(dplyr)
df <- data.frame(id=c(1,1,1,2,2,2,3,3,3),
stopId=c("a","b","c","a","b","c","a","b","c"),
stopSequence=c(1,2,3,3,1,4,3,1,2))
first_last <- function(x) {
bind_rows(slice(x, 1), slice(x, n()))
}
df %>%
group_by(id) %>%
arrange(stopSequence) %>%
do(first_last(.)) %>%
ungroup
## Source: local data frame [6 x 3]
##
## id stopId stopSequence
## 1 1 a 1
## 2 1 c 3
## 3 2 b 1
## 4 2 c 4
## 5 3 b 1
## 6 3 a 3
With do
you can pretty much perform any number of operations on the group but @jeremycg's answer is way more appropriate for just this task.
Here's a way:
<html>
<head>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var value = $('input[type="hidden"]')[0].value;
alert(value.split(/\?/)[1]);
});
</script>
</head>
<body>
<input type="hidden" value="/TEST/Name?3" />
</body>
</html>
$('input:checkbox.class').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
An example to demonstrate.
:checkbox
is a selector for checkboxes (in fact, you could omit the input
part of the selector, although I found niche cases where you would get strange results doing this in earlier versions of the library. I'm sure they are fixed in later versions).
.class
is the selector for element class attribute containing class
.
sorry for answering in old thread but may my code helps other in future.i was in same scenario that when check box will be checked then few selected inputs fields will be enable other wise disabled.
$("[id*='chkAddressChange']").click(function () {
var checked = $(this).is(':checked');
if (checked) {
$('.DisabledInputs').removeAttr('disabled');
} else {
$('.DisabledInputs').attr('disabled', 'disabled');
}
});
Update: Rather use flex.
If you want precision this is the way to go.
Fiddle. Go Play -> http://jsfiddle.net/atilkan/zxjcrhga/
Here is the HTML
<div class="sosial-links">
<a href="#"><i class="fa fa-facebook fa-lg"></i></a>
<a href="#"><i class="fa fa-twitter fa-lg"></i></a>
<a href="#"><i class="fa fa-google-plus fa-lg"></i></a>
<a href="#"><i class="fa fa-pinterest fa-lg"></i></a>
</div>
Here is the CSS
.sosial-links a{
display: block;
float: left;
width: 36px;
height: 36px;
border: 2px solid #909090;
border-radius: 20px;
margin-right: 7px; /*space between*/
}
.sosial-links a i{
padding: 12px 11px;
font-size: 20px;
color: #909090;
}
Have Fun
This was nice solution from here
InputFilter filter= new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
String checkMe = String.valueOf(source.charAt(i));
Pattern pattern = Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*");
Matcher matcher = pattern.matcher(checkMe);
boolean valid = matcher.matches();
if(!valid){
Log.d("", "invalid");
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
You're misinformed about fcntl()
not always being reliable. It's untrue.
To mark a socket as non-blocking the code is as simple as:
// where socketfd is the socket you want to make non-blocking
int status = fcntl(socketfd, F_SETFL, fcntl(socketfd, F_GETFL, 0) | O_NONBLOCK);
if (status == -1){
perror("calling fcntl");
// handle the error. By the way, I've never seen fcntl fail in this way
}
Under Linux, on kernels > 2.6.27 you can also create sockets non-blocking from the outset using socket()
and accept4()
.
e.g.
// client side
int socketfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
// server side - see man page for accept4 under linux
int socketfd = accept4( ... , SOCK_NONBLOCK);
It saves a little bit of work, but is less portable so I tend to set it with fcntl()
.
Add this at your TODO point:
aRange.Columns.AutoFit();
Is $target.remove();
what you're looking for?
$('#form').append('<input type="text" value="'+yourValue+'" />');
The show()
method only affects the display
CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button
element is a button and does not raise a submit
event. You would need to change your selector to the form
for that to work:
$('#login_form').submit(function() {
$('#gif').css('visibility', 'visible');
});
Also note that return true;
is redundant in your logic, so it can be removed.
In case you would like to read/check your Target Build Settings
in runtime using code, here is the way:
1) Add a Run Script
:
cp ${PROJECT_FILE_PATH}/project.pbxproj ${CONFIGURATION_BUILD_DIR}/${EXECUTABLE_NAME}.app/BuildSetting.pbxproj
It will copy the Target Build Settings
file into your Main Bundle
(will be called BuildSetting.pbxproj
).
2) You can now check the contents of that file at any time in code:
NSString *thePathString = [[NSBundle mainBundle] pathForResource:@"BuildSetting" ofType:@"pbxproj"];
NSDictionary *theDictionary = [NSDictionary dictionaryWithContentsOfFile:thePathString];
You have two choices here. The first is to have two result sets which will set 'Test1' or 'Test2' based on the condition in the WHERE
clause, and then UNION
them together:
select
'Test1', *
from
TABLE
Where
CCC='D' AND DDD='X' AND exists(select ...)
UNION
select
'Test2', *
from
TABLE
Where
CCC<>'D' AND DDD='X' AND exists(select ...)
This might be an issue, because you are going to effectively scan/seek on TABLE twice.
The other solution would be to select from the table once, and set 'Test1' or 'Test2' based on the conditions in TABLE:
select
case
when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1'
when CCC<>'D' AND DDD='X' AND exists(select ...) then 'Test2'
end,
*
from
TABLE
Where
(CCC='D' AND DDD='X' AND exists(select ...)) or
(CCC<>'D' AND DDD='X' AND exists(select ...))
The catch here being that you will have to duplicate the filter conditions in the CASE
statement and the WHERE
statement.
Queue is an interface; you can't explicitly construct a Queue. You'll have to instantiate one of its implementing classes. Something like:
Queue linkedList = new LinkedList();
An expansion for those who did a bit of fiddling around like I did.
The following work (from W3):
<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />
It is important to note that this does not work in CSS though. I.e. you can't use:
.first-input {
autofocus:"autofocus"
}
At least it didn't work for me...
The FolderBrowserDialog class is the best option.
On Itellij 15 CE, it's enough to just install Lombok Plugin (no additional configuration required).
In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.
Try moving that mysql.bak
directory out of /var/lib/mysql
to say /root/
or something. It seems like mysql is finding that and it may be causing that ERROR 1102 (42000): Incorrect database name 'mysql.bak'
error.
you can try on package manager console
PM> EntityFrameWork\enable-migrations
In my case, I had to comment out com.google.firebase.firebase-crash
plugin:
apply plugin: 'com.android.application'
// apply plugin: 'com.google.firebase.firebase-crash' <== this plugin causes the error
It is a bug since Android Studio 3.3.0
If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.
If you want just one result:
$key = array_search(40489, array_column($userdb, 'uid'));
For multiple results
$keys = array_keys(array_column($userdb, 'uid'), 40489);
In case you have an associative array as pointed in the comments you could make it with:
$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!
Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!
The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.
So you have either closed the socket before calling write()
or you have corrupted the value of 'sockfd' somewhere in your code.
It would be useful to trace all calls to close()
, and the value of 'sockfd' prior to the write()
calls.
Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror()
is invalid, as it may disturb the value of errno
. Indeed it may have done so in this case, and the real underlying error may be different.
append
is appending an element to a list. if you want to extend the list with the new list you need to use extend
.
>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]
@[User::path] ="MDS/Material/"+(DT_STR, 4, 1252) DATEPART("yy" , GETDATE())+ "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)