1.Check the Environment variables (must be set for System and not for user):
ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server
ORACLE_SID = XE
2.Check if you have the right definition in listener.ora
XE =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
)
DEFAULT_SERVICE_LISTENER = (XE)
3.Restart the service (Services > OracleServiceXE)
After that you may see a new service called OracleXETNSListenerXE.
There is already an old OracleXETNSListener.
I started both and then I was able to make a successful connection.
Edit:
If everything is running but you still can't connect, check if there is no error: ORA-12557: TNS:protocol adapter not loadable.
To correct the error go back to the Environment variables and this time edit the one called: Path. Be sure that C:\oraclexe\app\oracle\product\11.2.0\server\bin is somewhere at the beginning, definitely before any other path pointing to a different version of the Oracle DB.
For me, the HOST was set differently in tnsnames.ora and listener.ora. One was set to the full name of the computer and the other was set to IP address. I synchronized them to the full name of the computer and it worked. Don't forget to restart the oracle services.
I still don't understand exactly why this caused problem because I think IP address and computer name are ultimately same in my understanding.
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
Dim f as Range
Set f=ActiveSheet.Cells.Find(...)
If Not f Is Nothing then
msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
msgbox "value not found!"
End If
You can use this Function if you have some variable in the SSIS.
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(" Location of your SSIS package", null);
vars = pkg.Variables;
// your variables
vars["somevariable1"].Value = "yourvariable1";
vars["somevariable2"].Value = "yourvariable2";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
{
Console.WriteLine("Package ran successfully");
}
else
{
Console.WriteLine("Package failed");
}
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://stackoverflow.com")
try:
response = urlopen(req)
except HTTPError as e:
print('The server couldn\'t fulfill the request.')
print('Error code: ', e.code)
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
else:
print ('Website is working fine')
Works on Python 3
Solution for those working with Huawei phones - You will get this error when ADB interface is not installed. Check if you have installed Huawei HiSuite. USB driver gets installed when you install HiSuite (I suppose this is true for most of the new phones that come with a Sync Software). If the ADB interface is installed on your computer you should see 'Android Composite ADB Interface' under Android Phone in your Device Manager as shown in this picture.
SELECT word FROM table WHERE word NOT LIKE '%a%'
AND word NOT LIKE '%b%'
AND word NOT LIKE '%c%';
Use Thread.Sleep
when you want to block the current thread.
Use Task.Delay
when you want a logical delay without blocking the current thread.
Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.
In foreach
loop instead of carBootSaleList
use carBootSaleList.data
.
You probably do not need answer anymore, but it could help someone.
It's possible by accessing the key as index
for example:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2
I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:
My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.
private void startCreation(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
intent.setDataAndType(startDir,
"vnd.android.cursor.dir/lysesoft.andexplorer.file");
intent.putExtra("browser_filter_extension_whitelist", "*.csv");
intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
intent.putExtra("browser_title_background_color",
getText(R.string.browser_title_background_color));
intent.putExtra("browser_title_foreground_color",
getText(R.string.browser_title_foreground_color));
intent.putExtra("browser_list_background_color",
getText(R.string.browser_list_background_color));
intent.putExtra("browser_list_fontscale", "120%");
intent.putExtra("browser_list_layout", "2");
try{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("lysesoft.andexplorer", 0 );
startActivityForResult(intent, PICK_REQUEST_CODE);
} catch( PackageManager.NameNotFoundException e ){
showInstallResultMessage(R.string.error_install_andexplorer);
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
This methos is just pick up a dialog and if user wants install the external application from market
private void showInstallResultMessage(int msg_id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(getText(msg_id));
dialog.setButton(getText(R.string.button_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setButton2(getText(R.string.button_install),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
startActivity(intent);
finish();
}
});
dialog.show();
}
I prefer the following so I can still use top interactively without having to look up the pids each time I run it:
top -p `pgrep process-name | tr "\\n" "," | sed 's/,$//'`
Of course if the processes change you'll have to re-run the command.
Explanation:
pgrep process-name
returns a list of process ids which are separated by newlinestr "\\n" ","
translates these newlines into commas, because top wants a comma-separated list of process idssed
is a stream editor, and sed 's/,$//'
is used here to remove the trailing commaI think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.
As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:
$(window).resize(function() {
//update stuff
});
I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.
It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.
Generally speaking I always look for a set based approach (sometimes at the expense of changing the schema).
However, this snippet does have its place..
-- Declare & init (2008 syntax)
DECLARE @CustomerID INT = 0
-- Iterate over all customers
WHILE (1 = 1)
BEGIN
-- Get next customerId
SELECT TOP 1 @CustomerID = CustomerID
FROM Sales.Customer
WHERE CustomerID > @CustomerId
ORDER BY CustomerID
-- Exit loop if no more customers
IF @@ROWCOUNT = 0 BREAK;
-- call your sproc
EXEC dbo.YOURSPROC @CustomerId
END
Create an output file and custom function:
outputFile = open('outputfile.log', 'w')
def printing(text):
print(text)
if outputFile:
outputFile.write(str(text))
Then instead of print(text) in your code, call printing function.
printing("START")
printing(datetime.datetime.now())
printing("COMPLETE")
printing(datetime.datetime.now())
I had the same problem but I replaced the following line in my header:
@interface MyController : UIViewTableViewController <UITableViewDelegate, UITableViewDataSource>
with this line and it works as expected:
@interface RequestViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
Notice the UIViewController. Good luck :)
The differences are
String class is overriding toString(), equals(), hashCode() of Object class, but StringBuffer only overrides toString().
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // output true
StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer("abc");
System.out.println(sb1.equals(sb2)); // output false
String class is both Serializable as well as Comparable, but StringBuffer is only Serializable.
Set<StringBuffer> set = new TreeSet<StringBuffer>();
set.add(sb1);
set.add(sb2);
System.out.println(set); // gives ClassCastException because there is no Comparison mechanism
We can create a String object with and without new operator, but StringBuffer object can only be created using new operator.
As per my research I found that WebClient.DownloadFileAsync
is the best way to download file. It is available in System.Net
namespace and it supports .net core as well.
Here is the sample code to download the file.
using System;
using System.IO;
using System.Net;
using System.ComponentModel;
public class Program
{
public static void Main()
{
new Program().Download("ftp://localhost/test.zip");
}
public void Download(string remoteUri)
{
string FilePath = Directory.GetCurrentDirectory() + "/tepdownload/" + Path.GetFileName(remoteUri); // path where download file to be saved, with filename, here I have taken file name from supplied remote url
using (WebClient client = new WebClient())
{
try
{
if (!Directory.Exists("tepdownload"))
{
Directory.CreateDirectory("tepdownload");
}
Uri uri = new Uri(remoteUri);
//password username of your file server eg. ftp username and password
client.Credentials = new NetworkCredential("username", "password");
//delegate method, which will be called after file download has been complete.
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Extract);
//delegate method for progress notification handler.
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgessChanged);
// uri is the remote url where filed needs to be downloaded, and FilePath is the location where file to be saved
client.DownloadFileAsync(uri, FilePath);
}
catch (Exception)
{
throw;
}
}
}
public void Extract(object sender, AsyncCompletedEventArgs e)
{
Console.WriteLine("File has been downloaded.");
}
public void ProgessChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
}
}
With above code file will be downloaded inside tepdownload
folder of the project's directory. Please read comment in code to understand what above code do.
I know this is an old question but I use synonyms. Supposedly the query is executed within database server A, and looks for a table in a database server B that does not exist on server A. Add then a synonym on A database that calls your table from server B. Your query doesn't have to include any schemas, or different database names, just call the table name per usual and it will work.
There's no need to link servers as synonyms per say are sort of linking.
If removing the flag shows service temporary unavailable. Go to "http://localhost.com/downloader" and unisntall slider banner,BusinessDecision_Interaktingslider,lightbox2 and anotherone that I dont remember.
TextBox2.Text = "Line 1" & Environment.NewLine & "Line 2"
or
TextBox2.Text = "Line 1"
TextBox2.Text += Environment.NewLine
TextBox2.Text += "Line 2"
This, is how it is done.
For to use looping to get all arguments and in pure batch:
Obs: For using without: ?*&<>
@echo off && setlocal EnableDelayedExpansion
for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!")
:: write/test these arguments/parameters ::
for /l %%l in (1 1 !_cnt!)do echo/ The argument n:%%l is: !_arg_[%%l]!
goto :eof
Your code is ready to do something with the argument number where it needs, like...
@echo off && setlocal EnableDelayedExpansion
for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!"
echo= !_arg_[1]! !_arg_[2]! !_arg_[2]!> log.txt
You can use built-in map
function:
result = map(lambda x: x * P, S)
or list comprehensions that is a bit more pythonic:
result = [x * P for x in S]
In iOS 9.1 and lower, go to Settings - General - Profiles - tap on your Profile - tap on Trust button.
In iOS 9.2+ & iOS 11+ go to: Settings - General - Profiles & Device Management - tap on your Profile - tap on Trust button.
In iOS 10+, go to: Settings - General - Device Management - tap on your Profile - tap on Trust button.
You can use logger.exception("msg")
for logging exception with traceback:
try:
#your code
except Exception as e:
logger.exception('Failed: ' + str(e))
This answer might not be 100% relevant to the question. But it does address the problem. I found this simple way of achieving this requirement. Code goes below:
<a href="@Url.Action("Display", "Customer")?custId={{cust.Id}}"></a>
In the above example {{cust.Id}} is an AngularJS variable. However one can replace it with a JavaScript variable.
I haven't tried passing multiple variables using this method but I'm hopeful that also can be appended to the Url if required.
Here is another thing to try (I'm using Windows 10):
This is what worked for me. I have no idea why the service wasn't started in the first place and it used to work fine with my IPhone 7. Good luck.
Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21
webViewClient = object : WebViewClient() {
.
.
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
parseUri(request?.url)
return true
}
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
parseUri(Uri.parse(url))
return true
}
}
Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.
" To solve this problem You need set ServerName.
1: $ vim /etc/apache2/conf.d/name
For example set add ServerName localhost or any other name:
2: ServerName localhost Restart Apache 2
3: $ service apache restart
For this example I use Ubuntu 11.10.1.125"
Use sysdate-1 to subtract one day from system date.
select sysdate, sysdate -1 from dual;
Output:
SYSDATE SYSDATE-1
-------- ---------
22-10-13 21-10-13
To make the scripts compatible with Python2 and 3 i use :
from sys import version_info
if version_info[0] < 3:
from __future__ import print_function
Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :
var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...
...
d3.select("#the_SVG_ID").remove();
To comapre dates of string format (mm-dd-yyyy).
var job_start_date = "10-1-2014"; // Oct 1, 2014
var job_end_date = "11-1-2014"; // Nov 1, 2014
job_start_date = job_start_date.split('-');
job_end_date = job_end_date.split('-');
var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);
if(new_end_date <= new_start_date) {
// your code
}
This will also work:
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1);
}
UPDATE Slightly more concise version (http://ideone.com/B8i4o):
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}
There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.
The generally used solution is to always provide an alternate form of vararg functions, so printf
has vprintf
which takes a va_list
in place of the ...
. The ...
versions are just wrappers around the va_list
versions.
Just a note that as of Ruby 2.0 there is no need to add # encoding: utf-8
. UTF-8 is automatically detected.
Make the URL of the iframe point to a page on your site which acts as a proxy to retrieve and return the actual contents of the iframe. Now you are no longer bound by the same-origin policy (EDIT: does not prevent the iframe caching issue).
Here is my list (updated for 1.0):
// sending to sender-client only
socket.emit('message', "this is a test");
// sending to all clients, include sender
io.emit('message', "this is a test");
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');
// sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'cool game');
// sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'enjoy the game');
// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');
// sending to individual socketid
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
// list socketid
for (var socketid in io.sockets.sockets) {}
OR
Object.keys(io.sockets.sockets).forEach((socketid) => {});
data.sort(function(a,b)
{
return a.val - b.val;
});
You need to create a service to be able to share data between controllers.
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
In your controller A:
myService.set(yourSharedData);
In your controller B:
$scope.desiredLocation = myService.get();
Remember to inject myService in the controllers by passing it as a parameter.
I don't know if it is help. Create an AVD for a tablet-type device: Set the target to "Android 3.0" and the skin to "WXGA" (the default skin). You can check this site. http://developer.android.com/guide/practices/optimizing-for-3.0.html
If you don't want to use library (which you should) then use something like this (PHP 7):
function sign($message, $key) {
return hash_hmac('sha256', $message, $key) . $message;
}
function verify($bundle, $key) {
return hash_equals(
hash_hmac('sha256', mb_substr($bundle, 64, null, '8bit'), $key),
mb_substr($bundle, 0, 64, '8bit')
);
}
function getKey($password, $keysize = 16) {
return hash_pbkdf2('sha256',$password,'some_token',100000,$keysize,true);
}
function encrypt($message, $password) {
$iv = random_bytes(16);
$key = getKey($password);
$result = sign(openssl_encrypt($message,'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv), $key);
return bin2hex($iv).bin2hex($result);
}
function decrypt($hash, $password) {
$iv = hex2bin(substr($hash, 0, 32));
$data = hex2bin(substr($hash, 32));
$key = getKey($password);
if (!verify($data, $key)) {
return null;
}
return openssl_decrypt(mb_substr($data, 64, null, '8bit'),'aes-256-ctr',$key,OPENSSL_RAW_DATA,$iv);
}
$string_to_encrypt='John Smith';
$password='password';
$encrypted_string=encrypt($string_to_encrypt, $password);
$decrypted_string=decrypt($encrypted_string, $password);
For the text color add:
android:textColor="<hex color>"
For the background color add:
android:background="<hex color>"
From API 21 you can use:
android:backgroundTint="<hex color>"
android:backgroundTintMode="<mode>"
Note: If you're going to work with android/java you really should learn how to google ;)
How to customize different buttons in Android
The way to close resources are context managers, aka the with
statement:
class Foo(object):
def __init__(self):
self.bar = None
def __enter__(self):
if self.bar != 'open':
print 'opening the bar'
self.bar = 'open'
return self # this is bound to the `as` part
def close(self):
if self.bar != 'closed':
print 'closing the bar'
self.bar = 'close'
def __exit__(self, *err):
self.close()
if __name__ == '__main__':
with Foo() as foo:
print foo, foo.bar
output:
opening the bar
<__main__.Foo object at 0x17079d0> open
closing the bar
2) Python's objects get deleted when their reference count is 0. In your example the del foo
removes the last reference so __del__
is called instantly. The GC has no part in this.
class Foo(object):
def __del__(self):
print "deling", self
if __name__ == '__main__':
import gc
gc.disable() # no gc
f = Foo()
print "before"
del f # f gets deleted right away
print "after"
output:
before
deling <__main__.Foo object at 0xc49690>
after
The gc
has nothing to do with deleting your and most other objects. It's there to clean up when simple reference counting does not work, because of self-references or circular references:
class Foo(object):
def __init__(self, other=None):
# make a circular reference
self.link = other
if other is not None:
other.link = self
def __del__(self):
print "deling", self
if __name__ == '__main__':
import gc
gc.disable()
f = Foo(Foo())
print "before"
del f # nothing gets deleted here
print "after"
gc.collect()
print gc.garbage # The GC knows the two Foos are garbage, but won't delete
# them because they have a __del__ method
print "after gc"
# break up the cycle and delete the reference from gc.garbage
del gc.garbage[0].link, gc.garbage[:]
print "done"
output:
before
after
[<__main__.Foo object at 0x22ed8d0>, <__main__.Foo object at 0x22ed950>]
after gc
deling <__main__.Foo object at 0x22ed950>
deling <__main__.Foo object at 0x22ed8d0>
done
3) Lets see:
class Foo(object):
def __init__(self):
raise Exception
def __del__(self):
print "deling", self
if __name__ == '__main__':
f = Foo()
gives:
Traceback (most recent call last):
File "asd.py", line 10, in <module>
f = Foo()
File "asd.py", line 4, in __init__
raise Exception
Exception
deling <__main__.Foo object at 0xa3a910>
Objects are created with __new__
then passed to __init__
as self
. After a exception in __init__
, the object will typically not have a name (ie the f =
part isn't run) so their ref count is 0. This means that the object is deleted normally and __del__
is called.
Register a hook to unsubscribe your listeners when the component is removed:
$scope.$on('$destroy', function () {
delete $rootScope.$$listeners["youreventname"];
});
Use this code:
private void pdfOpen(String fileUrl){
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
//---you need this to prevent the webview from
// launching another browser when a url
// redirection occurs---
webView.setWebViewClient(new Callback());
webView.loadUrl(
"http://docs.google.com/gview?embedded=true&url=" + fileUrl);
}
private class Callback extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(
WebView view, String url) {
return (false);
}
}
After some years have passed, you can do that now with ES6 Array.from
(or spread syntax):
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
<ul>_x000D_
<li id="navbar-One">One</li>_x000D_
<li id="navbar-Two">Two</li>_x000D_
<li id="navbar-Three">Three</li>_x000D_
</ul>_x000D_
</div>
_x000D_
The [:-1]
removes the last element. Instead of
a[3:-1]
write
a[3:]
You can read up on Python slicing notation here: Explain Python's slice notation
NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.
If none of given solutions fixed the error, the issue probably about Google Cloud Billing settings. You must enable Billing on the Google Cloud Project at billing/enable.
{
"error_message" : "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started",
"results" : [],
"status" : "REQUEST_DENIED"
}
I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...
It looks like you're trying to replace the extension with the following code:
if (myFile[-4:] == ".asm"):
newFile = myFile[:4]+".hack"
However, you appear to have the array indexes mixed up. Try the following:
if (myFile[-4:] == ".asm"):
newFile = myFile[:-4]+".hack"
Note the use of -4
instead of just 4
in the second line of code. This explains why your program is trying to create /Use.hack
, which is the first four characters of your file name (/Use
), with .hack
appended to it.
From CSS
video {
position: fixed; right: 0; bottom: 0;
min-width: 100%; min-height: 100%;
width: auto; height: auto; z-index: -100;
background: url(polina.jpg) no-repeat;
background-size: cover;
}
Python has nothing built-in to support this. Do you really need to optimize it so much as I don't think that appending will add that much overhead.
However, you can do something like l = [None] * 1000
.
Alternatively, you could use a generator.
You can print some text by using SELECT
command like that:
SELECT 'some text'
Result:
+-----------+
| some text |
+-----------+
| some text |
+-----------+
1 row in set (0.02 sec)
A better idea,
if you want to put the error message just beneath the text field, you can do like this
.row.spacer20top
.col-sm-6.form-group
= f.label :first_name, "*Your First Name:"
= f.text_field :first_name, :required => true, class: "form-control"
= f.error_message_for(:first_name)
What is error_message_for
?
--> Well, this is a beautiful hack to do some cool stuff
# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
def error_message_for(field_name)
if self.object.errors[field_name].present?
model_name = self.object.class.name.downcase
id_of_element = "error_#{model_name}_#{field_name}"
target_elem_id = "#{model_name}_#{field_name}"
class_name = 'signup-error alert alert-danger'
error_declaration_class = 'has-signup-error'
"<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
"#{self.object.errors[field_name].join(', ')}"\
"</div>"\
"<!-- Later JavaScript to add class to the parent element -->"\
"<script>"\
"document.onreadystatechange = function(){"\
"$('##{id_of_element}').parent()"\
".addClass('#{error_declaration_class}');"\
"}"\
"</script>".html_safe
end
rescue
nil
end
end
Markup Generated after error
<div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
<script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>
Corresponding SCSS
.has-signup-error{
.signup-error{
background: transparent;
color: $brand-danger;
border: none;
}
input, select{
background-color: $bg-danger;
border-color: $brand-danger;
color: $gray-base;
font-weight: 500;
}
&.checkbox{
label{
&:before{
background-color: $bg-danger;
border-color: $brand-danger;
}
}
}
Note: Bootstrap variables used here
When we capture the image from Camera in Android then Uri
or data.getdata()
becomes null. We have two solutions to resolve this issue.
This is how to retrieve the Uri from the Bitmap Image. First capture image through Intent that will be the same for both methods:
// Capture Image
captureImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, reqcode);
}
}
});
Now implement OnActivityResult
, which will be the same for both methods:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==reqcode && resultCode==RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// Show Uri path based on Image
Toast.makeText(LiveImage.this,"Here "+ tempUri, Toast.LENGTH_LONG).show();
// Show Uri path based on Cursor Content Resolver
Toast.makeText(this, "Real path for URI : "+getRealPathFromURI(tempUri), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Failed To Capture Image", Toast.LENGTH_SHORT).show();
}
}
Now create all above methods to create the Uri from Image and Cursor methods:
Uri path from Bitmap Image:
private Uri getImageUri(Context applicationContext, Bitmap photo) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(LiveImage.this.getContentResolver(), photo, "Title", null);
return Uri.parse(path);
}
Uri from Real path of saved image:
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Adding this answer for people like me for whom a TRUE/FALSE answer is perfectly acceptable
OR(IF(ISNUMBER(SEARCH($G$1:$G$7,A1)),TRUE,FALSE))
or case-sensitive
OR(IF(ISNUMBER(FIND($G$1:$G$7,A1)),TRUE,FALSE))
Where the range for the search terms is G1:G7
Remember to press CTRL+SHIFT+ENTER
The ConverterParameter
property can not be bound because it is not a dependency property.
Since Binding
is not derived from DependencyObject
none of its properties can be dependency properties. As a consequence, a Binding can never be the target object of another Binding.
There is however an alternative solution. You could use a MultiBinding
with a multi-value converter instead of a normal Binding:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=FindAncestor,
AncestorType=UserControl}"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
The multi-value converter gets an array of source values as input:
public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
public object Convert(
object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.All(v => (v is bool && (bool)v))
? Visibility.Visible
: Visibility.Hidden;
}
public object[] ConvertBack(
object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
I found this answer here: https://dba.stackexchange.com/questions/1558. In short using the following (or within my.cnf) will remove the timeout issue.
SET GLOBAL interactive_timeout = 180;
SET GLOBAL wait_timeout = 180;
This allows the connections to end if they remain in a sleep State for 3 minutes (or whatever you define).
I feel like this is the simplest way. (Feel free to change the width and height values).
<a href="http://www.google.com"
target="popup"
onclick="window.open('http://www.google.com','popup','width=600,height=600'); return false;">
Link Text goes here...
</a>
See if this helps: Back to CSV - Convert CSV text to Objects; via JSON
This is a blog post published in November 2008 that includes C# code to provide a solution.
From the intro on the blog post:
As Json is easier to read and write then Xml. It follows that CSV (comma seperated values) is easier to read and write then Json. CSV also has tools such as Excel and others that make it easy to work with and create. So if you ever want to create a config or data file for your next app, here is some code to convert CSV to JSON to POCO objects
$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s).
E.g., attr1="Name: {{name}}"
, then in a directive: attrs.$observe('attr1', ...)
.
(If you try scope.$watch(attrs.attr1, ...)
it won't work because of the {{}}s -- you'll get undefined
.) Use $watch for everything else.
$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in
Because strings are evaluated as Angular expressions, $watch is often used when you want to observe/watch a model/scope property. E.g., attr1="myModel.some_prop"
, then in a controller or link function: scope.$watch('myModel.some_prop', ...)
or scope.$watch(attrs.attr1, ...)
(or scope.$watch(attrs['attr1'], ...)
).
(If you try attrs.$observe('attr1')
you'll get the string myModel.some_prop
, which is probably not what you want.)
As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.
Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.
To help test all of this, I wrote a Plunker that defines two directives. One (d1
) does not create a new scope, the other (d2
) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.
<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
attr5="a_string" attr6="{{1+aNumber}}"></div>
Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.
Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined
). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)
Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22"
, then in, say, your linking function: var count = scope.$eval(attrs.attr1)
. If it is just a constant string – attr1="my string"
– then just use attrs.attr1
in your directive (no need for $eval()).
See also Vojta's google group post about $watch expressions.
You can use Buffer.from()
to convert a string to buffer. More information on this can be found here
var buf = Buffer.from('some string', 'encoding');
for example
var buf = Buffer.from(bStr, 'utf-8');
Just a a bit modifications on reading string from a file method for more performance
private String readFromFile(Context context, String fileName) {
if (context == null) {
return null;
}
String ret = "";
try {
InputStream inputStream = context.openFileInput(fileName);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int size = inputStream.available();
char[] buffer = new char[size];
inputStreamReader.read(buffer);
inputStream.close();
ret = new String(buffer);
}
}catch (Exception e) {
e.printStackTrace();
}
return ret;
}
Maybe it is really late answer but if you want to navigate another page with param you can,
[routerLink]="['/user', user.id, 'details']"
also you shouldn't forget about routing config like ,
[path: 'user/:id/details', component:userComponent, pathMatch: 'full']
Difference between IaaS PaaS & SaaS
In the following tabular format we will be explaining the difference in context of
pizza as a service
import math #imports math module
import math as m
print(m.sqrt(25))
from math import sqrt #imports a method from math module
print(sqrt(25))
from math import sqrt as s
print(s(25))
from math import *
print(sqrt(25))
String result = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
I was able to screen using the device's name anyway so that wasn't the issue. I was actually just trying to find the port number, i.e. 5331, 5332 etc. I managed to find this by a trial and error process using an app called TCP2Serial from the app store on Mac OS X. It isn't free but that's fine as long as I know it works!
Worth the 99c :) http://itunes.apple.com/us/app/tcp2serial/id506186902?mt=12
I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.
For those still facing this problem, I was able to resolve it as follows:
$ git commit --allow-empty -n -m "Initial commit".
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Here is the right anwser:
ADD_EXECUTABLE(your_executable ${source_files})
TARGET_LINK_LIBRARIES( your_executable
pthread
)
equivalent to
-lpthread
Before executing this command keep in mind that it will leave you in detached head status
Use git checkout <sha1>
to check out a particular commit.
Where <sha1>
is the commit unique number that you can obtain with git log
Here are some options after you are in detached head status:
git checkout <existingBranch>
and replace filesgit checkout -b <new_branch_name> <sha1>
double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;
Install tampermonkey and add the following UserScript with one (or more) @match
with specific page url (or a match of all pages: https://*
) e.g.:
// ==UserScript==
// @name inject-rx
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Inject rx library on the page
// @author Me
// @match https://www.some-website.com/*
// @require https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js
// @grant none
// ==/UserScript==
(function() {
'use strict';
window.injectedRx = rxjs;
//Or even: window.rxjs = rxjs;
})();
Whenever you need the library on the console, or on a snippet enable the specific UserScript and refresh.
This solution prevents namespace pollution. You can use custom namespaces to avoid accidental overwrite of existing global variables on the page.
In case it's useful, here's a C++ version of the Java snippet posted by Ribo:
struct decompressXML
{
// decompressXML -- Parse the 'compressed' binary form of Android XML docs
// such as for AndroidManifest.xml in .apk files
enum
{
endDocTag = 0x00100101,
startTag = 0x00100102,
endTag = 0x00100103
};
decompressXML(const BYTE* xml, int cb) {
// Compressed XML file/bytes starts with 24x bytes of data,
// 9 32 bit words in little endian order (LSB first):
// 0th word is 03 00 08 00
// 3rd word SEEMS TO BE: Offset at then of StringTable
// 4th word is: Number of strings in string table
// WARNING: Sometime I indiscriminently display or refer to word in
// little endian storage format, or in integer format (ie MSB first).
int numbStrings = LEW(xml, cb, 4*4);
// StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
// of the length/string data in the StringTable.
int sitOff = 0x24; // Offset of start of StringIndexTable
// StringTable, each string is represented with a 16 bit little endian
// character count, followed by that number of 16 bit (LE) (Unicode) chars.
int stOff = sitOff + numbStrings*4; // StringTable follows StrIndexTable
// XMLTags, The XML tag tree starts after some unknown content after the
// StringTable. There is some unknown data after the StringTable, scan
// forward from this point to the flag for the start of an XML start tag.
int xmlTagOff = LEW(xml, cb, 3*4); // Start from the offset in the 3rd word.
// Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
for (int ii=xmlTagOff; ii<cb-4; ii+=4) {
if (LEW(xml, cb, ii) == startTag) {
xmlTagOff = ii; break;
}
} // end of hack, scanning for start of first start tag
// XML tags and attributes:
// Every XML start and end tag consists of 6 32 bit words:
// 0th word: 02011000 for startTag and 03011000 for endTag
// 1st word: a flag?, like 38000000
// 2nd word: Line of where this tag appeared in the original source file
// 3rd word: FFFFFFFF ??
// 4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
// 5th word: StringIndex of Element Name
// (Note: 01011000 in 0th word means end of XML document, endDocTag)
// Start tags (not end tags) contain 3 more words:
// 6th word: 14001400 meaning??
// 7th word: Number of Attributes that follow this tag(follow word 8th)
// 8th word: 00000000 meaning??
// Attributes consist of 5 words:
// 0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
// 1st word: StringIndex of Attribute Name
// 2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
// 3rd word: Flags?
// 4th word: str ind of attr value again, or ResourceId of value
// TMP, dump string table to tr for debugging
//tr.addSelect("strings", null);
//for (int ii=0; ii<numbStrings; ii++) {
// // Length of string starts at StringTable plus offset in StrIndTable
// String str = compXmlString(xml, sitOff, stOff, ii);
// tr.add(String.valueOf(ii), str);
//}
//tr.parent();
// Step through the XML tree element tags and attributes
int off = xmlTagOff;
int indent = 0;
int startTagLineNo = -2;
while (off < cb) {
int tag0 = LEW(xml, cb, off);
//int tag1 = LEW(xml, off+1*4);
int lineNo = LEW(xml, cb, off+2*4);
//int tag3 = LEW(xml, off+3*4);
int nameNsSi = LEW(xml, cb, off+4*4);
int nameSi = LEW(xml, cb, off+5*4);
if (tag0 == startTag) { // XML START TAG
int tag6 = LEW(xml, cb, off+6*4); // Expected to be 14001400
int numbAttrs = LEW(xml, cb, off+7*4); // Number of Attributes to follow
//int tag8 = LEW(xml, off+8*4); // Expected to be 00000000
off += 9*4; // Skip over 6+3 words of startTag data
std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
//tr.addSelect(name, null);
startTagLineNo = lineNo;
// Look for the Attributes
std::string sb;
for (int ii=0; ii<numbAttrs; ii++) {
int attrNameNsSi = LEW(xml, cb, off); // AttrName Namespace Str Ind, or FFFFFFFF
int attrNameSi = LEW(xml, cb, off+1*4); // AttrName String Index
int attrValueSi = LEW(xml, cb, off+2*4); // AttrValue Str Ind, or FFFFFFFF
int attrFlags = LEW(xml, cb, off+3*4);
int attrResId = LEW(xml, cb, off+4*4); // AttrValue ResourceId or dup AttrValue StrInd
off += 5*4; // Skip over the 5 words of an attribute
std::string attrName = compXmlString(xml, cb, sitOff, stOff, attrNameSi);
std::string attrValue = attrValueSi!=-1
? compXmlString(xml, cb, sitOff, stOff, attrValueSi)
: "resourceID 0x"+toHexString(attrResId);
sb.append(" "+attrName+"=\""+attrValue+"\"");
//tr.add(attrName, attrValue);
}
prtIndent(indent, "<"+name+sb+">");
indent++;
} else if (tag0 == endTag) { // XML END TAG
indent--;
off += 6*4; // Skip over 6 words of endTag data
std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
prtIndent(indent, "</"+name+"> (line "+toIntString(startTagLineNo)+"-"+toIntString(lineNo)+")");
//tr.parent(); // Step back up the NobTree
} else if (tag0 == endDocTag) { // END OF XML DOC TAG
break;
} else {
prt(" Unrecognized tag code '"+toHexString(tag0)
+"' at offset "+toIntString(off));
break;
}
} // end of while loop scanning tags and attributes of XML tree
prt(" end at offset "+off);
} // end of decompressXML
std::string compXmlString(const BYTE* xml, int cb, int sitOff, int stOff, int strInd) {
if (strInd < 0) return std::string("");
int strOff = stOff + LEW(xml, cb, sitOff+strInd*4);
return compXmlStringAt(xml, cb, strOff);
}
void prt(std::string str)
{
printf("%s", str.c_str());
}
void prtIndent(int indent, std::string str) {
char spaces[46];
memset(spaces, ' ', sizeof(spaces));
spaces[min(indent*2, sizeof(spaces) - 1)] = 0;
prt(spaces);
prt(str);
prt("\n");
}
// compXmlStringAt -- Return the string stored in StringTable format at
// offset strOff. This offset points to the 16 bit string length, which
// is followed by that number of 16 bit (Unicode) chars.
std::string compXmlStringAt(const BYTE* arr, int cb, int strOff) {
if (cb < strOff + 2) return std::string("");
int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
char* chars = new char[strLen + 1];
chars[strLen] = 0;
for (int ii=0; ii<strLen; ii++) {
if (cb < strOff + 2 + ii * 2)
{
chars[ii] = 0;
break;
}
chars[ii] = arr[strOff+2+ii*2];
}
std::string str(chars);
free(chars);
return str;
} // end of compXmlStringAt
// LEW -- Return value of a Little Endian 32 bit word from the byte array
// at offset off.
int LEW(const BYTE* arr, int cb, int off) {
return (cb > off + 3) ? ( arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000
| arr[off+1]<<8&0xff00 | arr[off]&0xFF ) : 0;
} // end of LEW
std::string toHexString(DWORD attrResId)
{
char ch[20];
sprintf_s(ch, 20, "%lx", attrResId);
return std::string(ch);
}
std::string toIntString(int i)
{
char ch[20];
sprintf_s(ch, 20, "%ld", i);
return std::string(ch);
}
};
HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);
That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like
400 (bad request) - indicates a bad request
or
412 (Precondition Failed) e.g. conflict by performing conditional update
More info in free InfoQ Explores: REST book.
Assuming dateTime1
and dateTime2
are DateTime
values:
var diffInSeconds = (dateTime1 - dateTime2).TotalSeconds;
In your case, you 'd use DateTime.Now
as one of the values and the time in the list as the other. Be careful of the order, as the result can be negative if dateTime1
is earlier than dateTime2
.
You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.
The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.
The latest version of .Net (v4.6) just added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.
DateTimeOffset
:DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
DateTimeOffset
to Unix time in seconds:long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
DateTimeOffset
:DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
DateTimeOffset
to Unix time in milliseconds:long unixTimeStampInMilliseconds= dateTimeOffset.ToUnixTimeMilliseconds();
Note: These methods convert to and from DateTimeOffset
. To get a DateTime
representation simply use the DateTimeOffset.DateTime
property:
DateTime dateTime = dateTimeOffset.UtcDateTime;
Use the optional font
argument to turtle.write()
, from the docs:
turtle.write(
arg, move=False, align="left", font=("Arial", 8, "normal"))
Parameters:
- arg – object to be written to the TurtleScreen
- move – True/False
- align – one of the strings “left”, “center” or right”
- font – a triple (fontname, fontsize, fonttype)
So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal"))
to change the font size to 16 (default is 8).
#include <iostream>
using namespace std;
int main() {
enum level {EASY = 1, NORMAL, HARD};
// Present menu
int choice;
cout << "Choose your level:\n\n";
cout << "1 - Easy.\n";
cout << "2 - Normal.\n";
cout << "3 - Hard.\n\n";
cout << "Choice --> ";
cin >> choice;
cout << endl;
switch (choice) {
case EASY:
cout << "You chose Easy.\n";
break;
case NORMAL:
cout << "You chose Normal.\n";
break;
case HARD:
cout << "You chose Hard.\n";
break;
default:
cout << "Invalid choice.\n";
}
return 0;
}
You can use setText(java.lang.String text,
boolean html) from MimeMessageHelper
:
MimeMessage mimeMsg = javaMailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, false, "utf-8");
boolean isHTML = true;
msgHelper.setText("<h1>some html</h1>", isHTML);
But you need to:
mimeMsg.saveChanges();
Before:
javaMailSender.send(mimeMsg);
Without rooting: If you can't root your phone, use the run-as <package>
command to be able to access data of your application.
Example:
$ adb exec-out run-as com.yourcompany.app ls -R /data/data/com.yourcompany.app/
exec-out
executes the command without starting a shell and mangling the output.
Change your Main.c
like so
#include <stdlib.h>
#include <stdio.h>
#include "ClasseAusiliaria.h"
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
Create ClasseAusiliaria.h
like so
extern int addizione(int a, int b);
I then compiled and ran your code, I got an output of
11
from pathlib import Path
import os
sorted(Path('./').iterdir(), key=lambda t: t.stat().st_mtime)
or
sorted(Path('./').iterdir(), key=os.path.getmtime)
or
sorted(os.scandir('./'), key=lambda t: t.stat().st_mtime)
where m time is modified time.
Use This chunk of code..
.card::-webkit-scrollbar {
display: none;
}
you can use PATTERN:
<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
<div *ngIf="name.errors?.pattern">Is not a number</div>
</div>
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too. .....
Unfortunately, there is no :click pseudo selector. If you want to change styling on click, you should use Jquery/Javascript. It certainly is better than the "hack" for pure HTML / CSS. But if you insist...
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
background: #444;_x000D_
color: #fff;_x000D_
}
_x000D_
<label for="input">_x000D_
<input id="input" type="radio" />_x000D_
<span>NO JS styling</span>_x000D_
</label>
_x000D_
Or, if you prefer, you can toggle the styling:
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
background: #444;_x000D_
color: #fff;_x000D_
}
_x000D_
<label for="input">_x000D_
<input id="input" type="checkbox" />_x000D_
<span>NO JS styling</span>_x000D_
</label>
_x000D_
Use a long datatype.
I solved this issue by creating a bean for my service in SpringConfig.java file. Please check the below code,
@Configuration
public class SpringConfig {
@Bean
public TransactionService transactionService() {
return new TransactionServiceImpl();
}
}
The path of this file is shown in the below image, Spring boot application folder structure
You can't enable it or disable it in your XML (since your layout is set at runtime), but you can set if it's clickable at the launch of the activity with android:clickable
.
The control searches for a view in the following order:
As you do not have xxx.cshtml
in those locations, it returns a "view not found" error.
Solution: You can use the complete path of your view:
Like
PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
There's another detail here, not mentioned, related to writing to a module. Granted this may not be very common, but I've needed it from time to time.
Due to the way references and name binding works in Python, if you want to update some symbol in a module, say foo.bar, from outside that module, and have other importing code "see" that change, you have to import foo a certain way. For example:
module foo:
bar = "apples"
module a:
import foo
foo.bar = "oranges" # update bar inside foo module object
module b:
import foo
print foo.bar # if executed after a's "foo.bar" assignment, will print "oranges"
However, if you import symbol names instead of module names, this will not work.
For example, if I do this in module a:
from foo import bar
bar = "oranges"
No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its "bar".
Use ajax, a simple example,
HTML
<button id="button">Get Data</button>
Javascript
var button = document.getElementById("button");
button.addEventListener("click" ajaxFunction, false);
var ajaxFunction = function () {
// ajax code here
}
Alternatively look into jquery ajax
http://api.jquery.com/jQuery.ajax/
I know this is an old question, but I wanted to add something to the answers already here in hopes of helping someone else.
You can script the ftp
command with the -s:filename
option. The syntax is just a list of commands to pass to the ftp
shell, each terminated by a newline. This page has a nice reference to the commands that can be performed with ftp
.
Using the normal ftp
doesn't work very well when you need to have an entire directory tree copied to or from a ftp site. So you could use something like these to handle those situations.
These scripts works with the Windows ftp
command and allows for uploading and downloading of entire directories from a single command. This makes it pretty self reliant when using on different systems.
Basically what they do is map out the directory structure to be up/downloaded, dump corresponding ftp
commands to a file, then execute those commands when the mapping has finished.
ftpupload.bat
@echo off
SET FTPADDRESS=%1
SET FTPUSERNAME=%2
SET FTPPASSWORD=%3
SET LOCALDIR=%~f4
SET REMOTEDIR=%5
if "%FTPADDRESS%" == "" goto FTP_UPLOAD_USAGE
if "%FTPUSERNAME%" == "" goto FTP_UPLOAD_USAGE
if "%FTPPASSWORD%" == "" goto FTP_UPLOAD_USAGE
if "%LOCALDIR%" == "" goto FTP_UPLOAD_USAGE
if "%REMOTEDIR%" == "" goto FTP_UPLOAD_USAGE
:TEMP_NAME
set TMPFILE=%TMP%\%RANDOM%_ftpupload.tmp
if exist "%TMPFILE%" goto TEMP_NAME
SET INITIALDIR=%CD%
echo user %FTPUSERNAME% %FTPPASSWORD% > %TMPFILE%
echo bin >> %TMPFILE%
echo lcd %LOCALDIR% >> %TMPFILE%
cd %LOCALDIR%
setlocal EnableDelayedExpansion
echo mkdir !REMOTEDIR! >> !TMPFILE!
echo cd %REMOTEDIR% >> !TMPFILE!
echo mput * >> !TMPFILE!
for /d /r %%d in (*) do (
set CURRENT_DIRECTORY=%%d
set RELATIVE_DIRECTORY=!CURRENT_DIRECTORY:%LOCALDIR%=!
echo mkdir "!REMOTEDIR!/!RELATIVE_DIRECTORY:~1!" >> !TMPFILE!
echo cd "!REMOTEDIR!/!RELATIVE_DIRECTORY:~1!" >> !TMPFILE!
echo mput "!RELATIVE_DIRECTORY:~1!\*" >> !TMPFILE!
)
echo quit >> !TMPFILE!
endlocal EnableDelayedExpansion
ftp -n -i "-s:%TMPFILE%" %FTPADDRESS%
del %TMPFILE%
cd %INITIALDIR%
goto FTP_UPLOAD_EXIT
:FTP_UPLOAD_USAGE
echo Usage: ftpupload [address] [username] [password] [local directory] [remote directory]
echo.
:FTP_UPLOAD_EXIT
set INITIALDIR=
set FTPADDRESS=
set FTPUSERNAME=
set FTPPASSWORD=
set LOCALDIR=
set REMOTEDIR=
set TMPFILE=
set CURRENT_DIRECTORY=
set RELATIVE_DIRECTORY=
@echo on
ftpget.bat
@echo off
SET FTPADDRESS=%1
SET FTPUSERNAME=%2
SET FTPPASSWORD=%3
SET LOCALDIR=%~f4
SET REMOTEDIR=%5
SET REMOTEFILE=%6
if "%FTPADDRESS%" == "" goto FTP_UPLOAD_USAGE
if "%FTPUSERNAME%" == "" goto FTP_UPLOAD_USAGE
if "%FTPPASSWORD%" == "" goto FTP_UPLOAD_USAGE
if "%LOCALDIR%" == "" goto FTP_UPLOAD_USAGE
if not defined REMOTEDIR goto FTP_UPLOAD_USAGE
if not defined REMOTEFILE goto FTP_UPLOAD_USAGE
:TEMP_NAME
set TMPFILE=%TMP%\%RANDOM%_ftpupload.tmp
if exist "%TMPFILE%" goto TEMP_NAME
echo user %FTPUSERNAME% %FTPPASSWORD% > %TMPFILE%
echo bin >> %TMPFILE%
echo lcd %LOCALDIR% >> %TMPFILE%
echo cd "%REMOTEDIR%" >> %TMPFILE%
echo mget "%REMOTEFILE%" >> %TMPFILE%
echo quit >> %TMPFILE%
ftp -n -i "-s:%TMPFILE%" %FTPADDRESS%
del %TMPFILE%
goto FTP_UPLOAD_EXIT
:FTP_UPLOAD_USAGE
echo Usage: ftpget [address] [username] [password] [local directory] [remote directory] [remote file pattern]
echo.
:FTP_UPLOAD_EXIT
set FTPADDRESS=
set FTPUSERNAME=
set FTPPASSWORD=
set LOCALDIR=
set REMOTEFILE=
set REMOTEDIR=
set TMPFILE=
set CURRENT_DIRECTORY=
set RELATIVE_DIRECTORY=
@echo on
The "table-column" display type means it acts like the <col>
tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.
See the W3C standard for more information about the CSS table model.
* And a few other properties like borders, backgrounds.
I had this problem and fixed it with manuel-84's suggestion. Using a 400x400px image worked great, while my smaller image never showed up in the sharer.
Note that Facebook recommends a minimum 200px square image as the og:image tag: https://developers.facebook.com/docs/opengraph/howtos/maximizing-distribution-media-content/#tags
You can use the cd
builtin, or the pushd
and popd
builtins for this purpose. For example:
# do something with /etc as the working directory
cd /etc
:
# do something with /tmp as the working directory
cd /tmp
:
You use the builtins just like any other command, and can change directory context as many times as you like in a script.
This may be one of following problems.
mysqladmin -p variables | grep socket
and then put it in your db connection code:
pymysql.connect(db='db', user='user', passwd='pwd', unix_socket="/tmp/mysql.sock")
/tmp/mysql.sock is the returned from grep
2.Incorrect mysql port solution: You have to find out the correct mysql port:
mysqladmin -p variables | grep port
and then in your code:
pymysql.connect(db='db', user='user', passwd='pwd', host='localhost', port=3306)
3306 is the port returned from the grep
I think first option will resolve your problem.
IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression
technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.
Use a CSS rule like so:
body {
behavior:url(script.htc);
}
and within that script.htc file have something like:
<PUBLIC:COMPONENT TAGNAME="xss">
<PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
function main()
{
alert("HTC script executed.");
}
</SCRIPT>
The HTC file executes the main()
function on the event ondocumentready
(referring to the HTC document's readiness.)
Firefox supports a similar XML-script-executing hack, using XBL.
Use a CSS rule like so:
body {
-moz-binding: url(script.xml#mycode);
}
and within your script.xml:
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="mycode">
<implementation>
<constructor>
alert("XBL script executed.");
</constructor>
</implementation>
</binding>
</bindings>
All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)
In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body
, it will execute immediately on page load.
I had to remove the first option from a select, with no ID, only a class, so I used this code successfully:
$('select.validation').find('option:first').remove();
AJAX does the magic:
$(document).ready(function(
$.ajax({ url: 'script.php?argument=value&foo=bar' });
));
With a list comprehension:
a = [x - 13 for x in a]
Its a bit late, however... Full implementation:
[HttpGet]
public async Task<HttpResponseMessage> GetPageFromUriOrBody(RequestQuery requestQuery)
{
log(nameof(GetPageFromUriOrBody), nameof(requestQuery));
var responseResult = await _requestQueryCache.GetOrCreate(
nameof(GetPageFromUriOrBody)
, requestQuery
, (x) => getPageContent(x).Result);
return Request.CreateResponse(System.Net.HttpStatusCode.Accepted, responseResult);
}
static MemoryCacheWithPolicy<RequestQuery, string> _requestQueryCache = new MemoryCacheWithPolicy<RequestQuery, string>();
Here is getPageContent
signature:
async Task<string> getPageContent(RequestQuery requestQuery);
And here is the MemoryCacheWithPolicy
implementation:
public class MemoryCacheWithPolicy<TParameter, TResult>
{
static ILogger _nlogger = new AppLogger().Logger;
private MemoryCache _cache = new MemoryCache(new MemoryCacheOptions()
{
//Size limit amount: this is actually a memory size limit value!
SizeLimit = 1024
});
/// <summary>
/// Gets or creates a new memory cache record for a main data
/// along with parameter data that is assocciated with main main.
/// </summary>
/// <param name="key">Main data cache memory key.</param>
/// <param name="param">Parameter model that assocciated to main model (request result).</param>
/// <param name="createCacheData">A delegate to create a new main data to cache.</param>
/// <returns></returns>
public async Task<TResult> GetOrCreate(object key, TParameter param, Func<TParameter, TResult> createCacheData)
{
// this key is used for param cache memory.
var paramKey = key + nameof(param);
if (!_cache.TryGetValue(key, out TResult cacheEntry))
{
// key is not in the cache, create data through the delegate.
cacheEntry = createCacheData(param);
createMemoryCache(key, cacheEntry, paramKey, param);
_nlogger.Warn(" cache is created.");
}
else
{
// data is chached so far..., check if param model is same (or changed)?
if(!_cache.TryGetValue(paramKey, out TParameter cacheParam))
{
//exception: this case should not happened!
}
if (!cacheParam.Equals(param))
{
// request param is changed, create data through the delegate.
cacheEntry = createCacheData(param);
createMemoryCache(key, cacheEntry, paramKey, param);
_nlogger.Warn(" cache is re-created (param model has been changed).");
}
else
{
_nlogger.Trace(" cache is used.");
}
}
return await Task.FromResult<TResult>(cacheEntry);
}
MemoryCacheEntryOptions createMemoryCacheEntryOptions(TimeSpan slidingOffset, TimeSpan relativeOffset)
{
// Cache data within [slidingOffset] seconds,
// request new result after [relativeOffset] seconds.
return new MemoryCacheEntryOptions()
// Size amount: this is actually an entry count per
// key limit value! not an actual memory size value!
.SetSize(1)
// Priority on removing when reaching size limit (memory pressure)
.SetPriority(CacheItemPriority.High)
// Keep in cache for this amount of time, reset it if accessed.
.SetSlidingExpiration(slidingOffset)
// Remove from cache after this time, regardless of sliding expiration
.SetAbsoluteExpiration(relativeOffset);
//
}
void createMemoryCache(object key, TResult cacheEntry, object paramKey, TParameter param)
{
// Cache data within 2 seconds,
// request new result after 5 seconds.
var cacheEntryOptions = createMemoryCacheEntryOptions(
TimeSpan.FromSeconds(2)
, TimeSpan.FromSeconds(5));
// Save data in cache.
_cache.Set(key, cacheEntry, cacheEntryOptions);
// Save param in cache.
_cache.Set(paramKey, param, cacheEntryOptions);
}
void checkCacheEntry<T>(object key, string name)
{
_cache.TryGetValue(key, out T value);
_nlogger.Fatal("Key: {0}, Name: {1}, Value: {2}", key, name, value);
}
}
nlogger
is just nLog
object to trace MemoryCacheWithPolicy
behavior.
I re-create the memory cache if request object (RequestQuery requestQuery
) is changed through the delegate (Func<TParameter, TResult> createCacheData
) or re-create when sliding or absolute time reached their limit. Note that everything is async too ;)
Fast
fun unicodeDecode(unicode: String): String {
val stringBuffer = StringBuilder()
var i = 0
while (i < unicode.length) {
if (i + 1 < unicode.length)
if (unicode[i].toString() + unicode[i + 1].toString() == "\\u") {
val symbol = unicode.substring(i + 2, i + 6)
val c = Integer.parseInt(symbol, 16)
stringBuffer.append(c.toChar())
i += 5
} else stringBuffer.append(unicode[i])
i++
}
return stringBuffer.toString()
}
I think, the easiest way is to read readme file inside your Eclipse directory at path eclipse/readme/eclipse_readme
.
At the very top of this file it clearly tells the version number:
For My Eclipse Juno; it says version as Release 4.2.0
I just set this property and now Android OS is taking care of every thing.
android:adjustViewBounds="true"
Use this in your layout.xml where you have planted your ImageView :D
I have found a simple solution to banding by content at Pearson Software Consulting: Let's say the header is from A1 to B1, table data is from A2 to B5, the controling cell is in the A column
You have quite a few options for this:
1 - If you can find an SVG file for the map you want, you can use something like RaphaelJS or SnapSVG to add click listeners for your states/regions, this solution is the most customizable...
2 - You can use dedicated tools such as clickablemapbuilder (free) or makeaclickablemap (i think free also).
[disclaimer] Im the author of clickablemapbuilder.com :)
Each directive's controller
function is called whenever a new related element is instantiated.
Officially, the controller
function is where one:
Again, it is important to remember that if the directive involves an isolated scope, any properties within it that inherit from the parent scope are not yet available.
Simple and clean:
$('#select_all').click(function() {_x000D_
var c = this.checked;_x000D_
$(':checkbox').prop('checked', c);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<table>_x000D_
<tr>_x000D_
<td><input type="checkbox" id="select_all" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="checkbox" name="select[]" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="checkbox" name="select[]" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="checkbox" name="select[]" /></td>_x000D_
</tr>_x000D_
</table>_x000D_
</form>
_x000D_
def insenStringCompare(s1, s2):
""" Method that takes two strings and returns True or False, based
on if they are equal, regardless of case."""
try:
return s1.lower() == s2.lower()
except AttributeError:
print "Please only pass strings into this method."
print "You passed a %s and %s" % (s1.__class__, s2.__class__)
If you're working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:
Get-PfxCertificate -FilePath InputBundle.pfx |
Export-Certificate -FilePath OutputCert.der -Type CERT
Newline added for clarity, but you can of course have this all on a single line.
If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem
If you need to export to a different format than DER encoded, you can change the -Type
parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed
:
-Type <CertType>
Specifies the type of output file for the certificate export as follows.
-- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates.
-- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate.
-- P7B: A PKCS#7 file format which can contain one or more certificates.
For me, this is the best autofit and autoresize for table and its columns (use css !important ... only if you can't without)
.myclass table {
table-layout: auto !important;
}
.myclass th, .myclass td, .myclass thead th, .myclass tbody td, .myclass tfoot td, .myclass tfoot th {
width: auto !important;
}
Don't specify css width for table or for table columns. If table content is larger it will go over screen size to.
i have a very simple function:
function busca(busca){
$("#listagem tr:not(contains('"+busca+"'))").css("display", "none");
$("#listagem tr:contains('"+busca+"')").css("display", "");
}
Update-Package -ProjectName 'YourProjectNameGoesHere' -Reinstall
This is best and easiest example I found. It will reinstall all nugets that are listed in packages.config and it will preserve current versions. Replace YourProjectNameGoesHere
with the project name.
The best way to do it From Android O preview release is this way:
It works only if you have android studio-2.4 or above
R.font.dancing_script
, R.font.la_la
, and R.font.ba_ba
.Next we must create a font family:
Enclose each font file, style, and weight attribute in the font tag element. The following XML illustrates adding font-related attributes in the font resource XML:
Adding fonts to a TextView:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/hey_fontfamily"/>
As from the documentation
All the steps are correct.
Refer this code, auth.ts file
import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { } from 'angular-2-local-storage';
import { Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(public localStorageService:LocalStorageService, private router: Router){}
canActivate() {
// Imaginary method that is supposed to validate an auth token
// and return a boolean
var logInStatus = this.localStorageService.get('logInStatus');
if(logInStatus == 1){
console.log('****** log in status 1*****')
return true;
}else{
console.log('****** log in status not 1 *****')
this.router.navigate(['/']);
return false;
}
}
}
// *****And the app.routes.ts file is as follow ******//
import { Routes } from '@angular/router';
import { HomePageComponent } from './home-page/home- page.component';
import { WatchComponent } from './watch/watch.component';
import { TeachersPageComponent } from './teachers-page/teachers-page.component';
import { UserDashboardComponent } from './user-dashboard/user- dashboard.component';
import { FormOneComponent } from './form-one/form-one.component';
import { FormTwoComponent } from './form-two/form-two.component';
import { AuthGuard } from './authguard';
import { LoginDetailsComponent } from './login-details/login-details.component';
import { TransactionResolver } from './trans.resolver'
export const routes:Routes = [
{ path:'', component:HomePageComponent },
{ path:'watch', component:WatchComponent },
{ path:'teachers', component:TeachersPageComponent },
{ path:'dashboard', component:UserDashboardComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'formone', component:FormOneComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'formtwo', component:FormTwoComponent, canActivate: [AuthGuard], resolve: { dashboardData:TransactionResolver } },
{ path:'login-details', component:LoginDetailsComponent, canActivate: [AuthGuard] },
];
All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html
I asked the same question some time ago and had to answer it myself. Here's what I came up with:
It seems, my first thought [that it comes from its JavaScript roots] was correct.
'\/' === '/'
in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like\z
) not allowed in JSON?The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
Hard to find a clear answer from the Oracle site. The following is from javax.ws.rs.core.HttpHeaders.java
:
/**
* See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">HTTP/1.1 documentation</a>}.
*/
public static final String ACCEPT = "Accept";
/**
* See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2">HTTP/1.1 documentation</a>}.
*/
public static final String ACCEPT_CHARSET = "Accept-Charset";
For my mac Big Sur, with gist from answers above, following steps work for me.
$ ssh-keygen -q -t rsa -N 'password' -f ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa
And added ssh public key to git hub by following instruction;
If all gone well, you should be able to get the following result;
$ ssh -T [email protected]
Hi user_name! You've successfully authenticated,...
This should work:
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <[email protected]>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
function Utf8ArrayToStr(array) {
var out, i, len, c;
var char2, char3;
out = "";
len = array.length;
i = 0;
while(i < len) {
c = array[i++];
switch(c >> 4)
{
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12: case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
return out;
}
Check out the JSFiddle demo.
Since you know how many types of layout you would have - it's possible to use those methods.
getViewTypeCount()
- this methods returns information how many types of rows do you have in your list
getItemViewType(int position)
- returns information which layout type you should use based on position
Then you inflate layout only if it's null and determine type using getItemViewType
.
Look at this tutorial for further information.
To achieve some optimizations in structure that you've described in comment I would suggest:
ViewHolder
. It would increase speed because you won't have to call findViewById()
every time in getView
method. See List14 in API demos.I hope that will help you. If you could provide some XML stub with your data structure and information how exactly you want to map it into row, I would be able to give you more precise advise. By pixel.
Actually, to make your favicon work in all browsers properly, you will have to add more than 10 files in the correct sizes and formats.
My friend and I have created an App just for this! you can find it in faviconit.com
We did this, so people don't have to create all these images and the correct tags by hand, create all of them used to annoy me a lot!
When you want the super class constructor to be called - to initialize the fields within it. Take a look at this article for an understanding of when to use it:
http://download.oracle.com/javase/tutorial/java/IandI/super.html
If you are using Twig in your application as a component you can do this:
$twig = new Twig_Environment($loader, array(
'autoescape' => false
));
$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
Then in your templates:
{{ my_variable | var_dump }}
Putting the other answers all together, here's a command line that will work:
env vblank_mode=0 __GL_SYNC_TO_VBLANK=0 glxgears
This has the advantages of working for both Mesa and NVidia drivers, and not requiring any changes to configuration files.
In my case I needed to load a whole module only when the div existed in the template, meaning the outlet was inside an ngif. This way everytime angular detected the element #geolocalisationOutlet it created the component inside of it. The module only loads once as well.
constructor(
public wlService: WhitelabelService,
public lmService: LeftMenuService,
private loader: NgModuleFactoryLoader,
private injector: Injector
) {
}
@ViewChild('geolocalisationOutlet', {read: ViewContainerRef}) set geolocalisation(geolocalisationOutlet: ViewContainerRef) {
const path = 'src/app/components/engine/sections/geolocalisation/geolocalisation.module#GeolocalisationModule';
this.loader.load(path).then((moduleFactory: NgModuleFactory<any>) => {
const moduleRef = moduleFactory.create(this.injector);
const compFactory = moduleRef.componentFactoryResolver
.resolveComponentFactory(GeolocalisationComponent);
if (geolocalisationOutlet && geolocalisationOutlet.length === 0) {
geolocalisationOutlet.createComponent(compFactory);
}
});
}
<div *ngIf="section === 'geolocalisation'" id="geolocalisation">
<div #geolocalisationOutlet></div>
</div>
Another variant of printing /proc/PID/cmdline
with spaces in Linux is:
cat -v /proc/PID/cmdline | sed 's/\^@/\ /g' && echo
In this way cat
prints NULL characters as ^@
and then you replace them with a space using sed
; echo
prints a newline.
THX for this question! Works good for me on all popular browsers:
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = window.location.pathname;
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
var url = window.location.pathname;
var win = window.open(url, '_blank');
} else {
openNewBackgroundTab();
}
Be aware that Total Server Memory is NOT how much memory SQL Server is currently using.
refer to this Microsoft article: http://msdn.microsoft.com/en-us/library/ms190924.aspx
I just used this, but I don't know if it works across all browsers.
It works in Firefox:
<a href="myfile.pdf" download>Click to Download</a>
I've had this problem before and the conclusion I've come to is that the only way to stop a video in IE is to remove it from the DOM.
You only need this:
JFrame frame = new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
When you use the MAXIMIZED_BOTH modifier, it will max all the way across the window (height and width).
There are some that suggested using this:
frame.setUndecorated(true);
I won't recommend it, because your window won't have a header, thus no close/restore/minimize button.
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
using this you can format date.
you can change the appearance in the way you want then
for more info you can visit here
Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here
Open the sources.list
file:
sudo nano /etc/apt/sources.list
Add a line with the source from where the packages will be retrieved. For example:
deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
Replace https://cloud.r-project.org
with whatever mirror you would like to use, and replace
version/
with whatever version of Ubuntu you are using (eg, trusty/
, xenial/
, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/
and version/
.
Fetch the secure APT key:
gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
or
gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
Add it to keyring:
gpg -a --export E084DAB9 | sudo apt-key add -
Update your sources and upgrade your installation:
sudo apt-get update && sudo apt-get upgrade
Install the new version
sudo apt-get install r-base-dev
Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:
-- copy the packages from R-oldversion/library
to R-newversion/library
, (do not overwrite a package if it already exists in the new version!).
-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE)
.
You can do objects the JavaScript way... It makes no sense but it works ;)
>>> def FakeObject():
... def test():
... print "foo"
... FakeObject.test = test
... return FakeObject
>>> x = FakeObject()
>>> x.test()
foo
vanilla js using es6
document.querySelector('input[name="file"]').addEventListener('change', (e) => {
const file = e.target.files[0];
// todo: use file pointer
});
function msort(arr){
for(var i =0;i<arr.length;i++){
for(var j= i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
var swap = arr[i];
arr[i] = arr[j];
arr[j] = swap;
}
}
}
return arr;
}
I tried %~dp0 in the Start in field and it is working fine in Windows 10 x64
Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});
I used below code and it's working fine for me. :
let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
do {
dictonary = try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" User name is: \(myDictionary["userName"]!)")
}
} catch let error as NSError {
print(error)
}
}
How about something like this for shorter text?
It could even work for longer text if you did something with a loop, repeating the characters with JavaScript. Anyway, the result is something like this:
p.char {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
font-size: 60px;_x000D_
color: red;_x000D_
}_x000D_
_x000D_
p.char:before {_x000D_
position: absolute;_x000D_
content: attr(char);_x000D_
width: 50%;_x000D_
overflow: hidden;_x000D_
color: black;_x000D_
}
_x000D_
<p class="char" char="S">S</p>_x000D_
<p class="char" char="t">t</p>_x000D_
<p class="char" char="a">a</p>_x000D_
<p class="char" char="c">c</p>_x000D_
<p class="char" char="k">k</p>_x000D_
<p class="char" char="o">o</p>_x000D_
<p class="char" char="v">v</p>_x000D_
<p class="char" char="e">e</p>_x000D_
<p class="char" char="r">r</p>_x000D_
<p class="char" char="f">f</p>_x000D_
<p class="char" char="l">l</p>_x000D_
<p class="char" char="o">o</p>_x000D_
<p class="char" char="w">w</p>
_x000D_
This is how I am using it. And it is working fantastically -
public enum Button {
REPORT_ISSUES(0),
CANCEL_ORDER(1),
RETURN_ORDER(2);
private int value;
Button(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
And the switch-case
as shown below
@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
switch (button) {
case REPORT_ISSUES: {
break;
}
case CANCEL_ORDER: {
break;
}
case RETURN_ORDER: {
break;
}
}
}
double d = 2.34568;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println(f.format(d));
The images c, d, e , and f in the following show colorspace conversion they also happen to be numpy arrays <type 'numpy.ndarray'>
:
import numpy, cv2
def show_pic(p):
''' use esc to see the results'''
print(type(p))
cv2.imshow('Color image', p)
while True:
k = cv2.waitKey(0) & 0xFF
if k == 27: break
return
cv2.destroyAllWindows()
b = numpy.zeros([200,200,3])
b[:,:,0] = numpy.ones([200,200])*255
b[:,:,1] = numpy.ones([200,200])*255
b[:,:,2] = numpy.ones([200,200])*0
cv2.imwrite('color_img.jpg', b)
c = cv2.imread('color_img.jpg', 1)
c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)
d = cv2.imread('color_img.jpg', 1)
d = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)
e = cv2.imread('color_img.jpg', -1)
e = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)
f = cv2.imread('color_img.jpg', -1)
f = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)
pictures = [d, c, f, e]
for p in pictures:
show_pic(p)
# show the matrix
print(c)
print(c.shape)
See here for more info: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor
OR you could:
img = numpy.zeros([200,200,3])
img[:,:,0] = numpy.ones([200,200])*255
img[:,:,1] = numpy.ones([200,200])*255
img[:,:,2] = numpy.ones([200,200])*0
r,g,b = cv2.split(img)
img_bgr = cv2.merge([b,g,r])
INADDR_ANY
instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0")
.
For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to ::
address for IPv6 socket.
#include <netinet/in.h>
struct in6_addr addr = IN6ADDR_ANY_INIT;
Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT
your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).
If you want to change R's language in terminal to English forever, this works fine for me in macOS:
Open terminal.app, and say:
touch .bash_profile
Then say:
open -a TextEdit.app .bash_profile
These two commands will help you open ".bash_profile" file in TextEdit.
Add this to ".bash_profile" file:
export LANG=en_US.UTF-8
Then save the file, reopen terminal and type R
, you will find it's language has changed to english.
If you want language come back to it's original, just simply add a #
before export LANG=en_US.UTF-8
.
You can use the option -o in sendEmail to send a html email.
-o message-content-type=html to specify the content type of the email.
-o message-file to add the html file to the email content.
I have tried this option in a shell scripts, and it works.
Here is the full command:
/usr/local/bin/sendEmail -f [email protected] -t "[email protected]" -s \
smtp.test.com -u "Title" -xu [email protected] -xp password \
-o message-charset=UTF-8 \
-o message-content-type=html \
-o message-file=test.html
It's not a direct answer to the question but you could just use the OR-operator
( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."
int a = fork();
Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.
The child getting 0 returned, and the parent getting the new pid.
Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.
At each fork
, only one value is modified - the return value from fork
.
Say you have number 1,2,3,4,5,6, in cell A1,A2,A3,A4,A5,A6 respectively. in cell A7 we calculate the sum of A1:Ax. x is specified in cell B1 (in this case, x can be any number from 1 to 6). in cell A7, you can write the following formular:
=SUM(A1:INDIRECT(CONCATENATE("A",B1)))
CONCATENATE will give you the index of the cell Ax(if you put 3 in B1, CONCATENATE("A",B1)) gives A3).
INDIRECT convert "A3" to a index.
see this link Using the value in a cell as a cell reference in a formula?
netstat -ano|grep 443|grep LISTEN
will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).
After trying these solutions I still wasn't satisfied but I found a solution in this article and it works in Chrome, Firefox, Opera, Safari, IE8+
#divId {
display: block;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: url(http://notrealdomain2.com/newbanner.png) no-repeat;
width: 180px; /* Width of new image */
height: 236px; /* Height of new image */
padding-left: 180px; /* Equal to width of new image */
}
You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.
A variation on @AndrewKennan's answer I ended up using recently for types obtained at runtime:
if (serviceType.IsInstanceOfType(service))
{
// 'service' does implement the 'serviceType' type
}
value.replaceAll("[^A-Za-z0-9]", "")
[^abc]
When a caret^
appears as the first character inside square brackets, it negates the pattern. This pattern matches any character except a or b or c.
Looking at the keyword as two function:
[(Pattern)] = match(Pattern)
[^(Pattern)] = notMatch(Pattern)
Moreover regarding a pattern:
A-Z = all characters included from A to Z
a-z = all characters included from a to z
0=9 = all characters included from 0 to 9
Therefore it will substitute all the char NOT included in the pattern
It's been a long time since I've worked in a Windows environment, but I would suggest that you look at using WMI.
SELECT TOP 1 ID, Name, Score, [Date]
FROM myTable
WHERE ID = 2
Order BY [Date]
Using the browser's parser is the probably the best bet in current browsers. The following will work, with the following caveats:
<div>
element. HTML contained within <body>
or <html>
or <head>
tags is not valid within a <div>
and may therefore not be parsed correctly.textContent
(the DOM standard property) and innerText
(non-standard) properties are not identical. For example, textContent
will include text within a <script>
element while innerText
will not (in most browsers). This only affects IE <=8, which is the only major browser not to support textContent
.<script>
elements.null
<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>
Code:
var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
If you want to use a programmatic approach instead of using ProGuard, then by creating your own class with two instances, one for debug and one for release, you can choose what to log in either circumstances.
So, if you don't want to log anything when in release, simply implement a Logger that does nothing, like the example below:
import android.util.Log
sealed class Logger(defaultTag: String? = null) {
protected val defaultTag: String = defaultTag ?: "[APP-DEBUG]"
abstract fun log(string: String, tag: String = defaultTag)
object LoggerDebug : Logger() {
override fun log(string: String, tag: String) {
Log.d(tag, string)
}
}
object LoggerRelease : Logger() {
override fun log(string: String, tag: String) {}
}
companion object {
private val isDebugConfig = BuildConfig.DEBUG
val instance: Logger by lazy {
if(isDebugConfig)
LoggerDebug
else
LoggerRelease
}
}
}
Then to use your logger class:
class MainActivity : AppCompatActivity() {
private val logger = Logger.instance
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
logger.log("Activity launched...")
...
myView.setOnClickListener {
...
logger.log("My View clicked!", "View-click")
}
}
== UPDATE ==
If we want to avoid string concatenations for better performances, we can add an inline function with a lambda that will be called only in debug config:
// Add this function to the Logger class.
inline fun commit(block: Logger.() -> Unit) {
if(this is LoggerDebug)
block.invoke(this)
}
And then:
logger.commit {
log("Logging without $myVar waste of resources"+ "My fancy concat")
}
Since we are using an inline function, there are no extra object allocation and no extra virtual method calls.
Based on above solutions, here comes a extension class which you can use to serialize and deserialize any object. Any other XML attributions are up to you.
Just use it like this:
string s = new MyObject().Serialize(); // to serialize into a string
MyObject b = s.Deserialize<MyObject>();// deserialize from a string
internal static class Extensions
{
public static T Deserialize<T>(this string value)
{
var xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(new StringReader(value));
}
public static string Serialize<T>(this T value)
{
if (value == null)
return string.Empty;
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
{
xmlSerializer.Serialize(xmlWriter, value);
return stringWriter.ToString();
}
}
}
}
This is because you have wrong selector. According to your markup, .ui-icon
and .ui-icon-circle-triangle-w"
should point to the same <span>
element. So you should use:
$(".ui-icon.ui-icon-circle-triangle-w").html("<<");
or
$(".ui-datepicker-prev .ui-icon").html("<<");
or
$(".ui-datepicker-prev span").html("<<");
You are calling get with the wrong argument.
It should be:
Object value = field.get(object);
It is possible to change the PWD, using JNA/JNI to make calls to libc. The JRuby guys have a handy java library for making POSIX calls called jna-posix Here's the maven info
You can see an example of its use here (Clojure code, sorry). Look at the function chdirToRoot
According to Angular2 documentation you should use:
@RouteConfig([
{path: '/login/:token', name: 'Login', component: LoginComponent},
])
@Component({ template: 'login: {{token}}' })
class LoginComponent{
token: string;
constructor(params: RouteParams) {
this.token = params.get('token');
}
}
Old fashioned way..
private static Date getDateWithMidnight(){
long dateInMillis = new Date().getTime();
return new Date(dateInMillis - dateInMillis%(1000*60*60*24) - TimeZone.getDefault().getOffset(dateInMillis));
}
If you use checkbox
<input
type='checkbox'
onChange={this.checkboxHandler}
/>
stopPropagation and stopImmediatePropagation won't be working.
Because you must using onClick={this.checkboxHandler}
os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'templates'))
As far as where the templates folder should go, I don't know since Django 1.4 just came out and I haven't looked at it yet. You should probably ask another question on SE to solve that issue.
You can also use normpath
to clean up the path, rather than abspath
. However, in this situation, Django expects an absolute path rather than a relative path.
For cross platform compatability, use os.pardir
instead of '..'
.
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
var EM = new events_managment();
EM.addEvent(window, 'resize', function(win,doc, event_){
console.log('resized');
//EM.removeEvent(win,doc, event_);
});
function events_managment(){
this.events = {};
this.addEvent = function(node, event_, func){
if(node.addEventListener){
if(event_ in this.events){
node.addEventListener(event_, function(){
func(node, event_);
this.events[event_](win_doc, event_);
}, true);
}else{
node.addEventListener(event_, function(){
func(node, event_);
}, true);
}
this.events[event_] = func;
}else if(node.attachEvent){
var ie_event = 'on' + event_;
if(ie_event in this.events){
node.attachEvent(ie_event, function(){
func(node, ie_event);
this.events[ie_event]();
});
}else{
node.attachEvent(ie_event, function(){
func(node, ie_event);
});
}
this.events[ie_event] = func;
}
}
this.removeEvent = function(node, event_){
if(node.removeEventListener){
node.removeEventListener(event_, this.events[event_], true);
this.events[event_] = null;
delete this.events[event_];
}else if(node.detachEvent){
node.detachEvent(event_, this.events[event_]);
this.events[event_] = null;
delete this.events[event_];
}
}
}
I solved the space issue by adding a border and removing is by setting a negative margin. Do not know what the underlying problem is though.
header {
border-top: 1px solid gold !important;
margin-top: -1px !important;
}
For me answer was aspx page attribute, i added Async="true" to page attributes and this solved my problem.
<%@ Page Language="C#" MasterPageFile="~/MasterPage/Reports.Master".....
AutoEventWireup="true" Async="true" %>
This is the structure of my update panel
<div>
<asp:UpdatePanel ID="updt" runat="server">
<ContentTemplate>
<asp:DropDownList ID="id" runat="server" AutoPostBack="true" onselectedindexchanged="your server side function" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
Well you have to grab the client for that (surprise), you can either go the simple way:
var io = io.listen(server);
io.clients[sessionID].send()
Which may break, I doubt it, but it's always a possibility that io.clients
might get changed, so use the above with caution
Or you keep track of the clients yourself, therefore you add them to your own clients
object in the connection
listener and remove them in the disconnect
listener.
I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}}
might do the job.
It's fine just to cast your int to Foo:
int i = 1;
Foo f = (Foo)i;
If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.
If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:
int i = 1;
if (Enum.IsDefined(typeof(Foo), i))
{
Foo f = (Foo)i;
}
else
{
// Throw exception, etc.
}
However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.
Also note that you don't have to specify that your enum inherits from int; this is the default behavior.
var strUser = e.options[e.selectedIndex].value;
This is correct and should give you the value. Is it the text you're after?
var strUser = e.options[e.selectedIndex].text;
So you're clear on the terminology:
<select>
<option value="hello">Hello World</option>
</select>
This option has:
Well! As I saw my question now, I realized that I didn't want to mention fixed margin value because of the dynamic height of header.
Here is what I have been using for such scenarios.
Calculate the header height using jQuery and apply that as a top margin value.
var divHeight = $('#header-wrap').height();
$('#container').css('margin-top', divHeight+'px');
You used the egg files install procedure.
This procedure supports installing over git
, git+http
, git+https
, git+ssh
, git+git
and git+file
. Some of these are mentioned.
It's good you can use branches, tags, or hashes to install.
@Steve_K noted it can be slow to install with "git+" and proposed installing via zip file:
pip install https://github.com/user/repository/archive/branch.zip
Alternatively, I suggest you may install using the .whl
file if this exists.
pip install https://github.com/user/repository/archive/branch.whl
It's pretty new format, newer than egg files. It requires wheel and setuptools>=0.8 packages. You can find more in here.
==
and !=
do not take into account the data type of the variables you compare. So these would all return true:
'0' == 0
false == 0
NULL == false
===
and !==
do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:
'0' === 0
false === 0
NULL === false
You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos()
:
// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false); // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned
Here is the code to mock this functionality using PowerMockito API.
Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);
You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .
@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
// your testing code
}
Richard Cox has a good solution to this https://stackoverflow.com/a/5200280/1171321 I have used in the past. It is also worth noting the DPI must be 96 for this to work correctly. Several of the solutions on this page do not work at all.
Keep in mind that with pointers to struct you'd have to dereference the variable and not compare it with a pointer to empty struct:
session := &Session{}
if (Session{}) == *session {
fmt.Println("session is empty")
}
Check this playground.
Also here you can see that a struct holding a property which is a slice of pointers cannot be compared the same way...
The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready()
then it should work perfectly well:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").show("slow");
});
});
An alternative is to place the <script></script>
at the foot of the page, so it's encountered after the DOM has been loaded and ready.
To make the div
hide again, once the #music
element is clicked, simply use toggle()
:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").toggle();
});
});
And for fading:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").fadeToggle();
});
});
__dirname will give you the root directory, as long as you're in a file that's in the root directory.
// ProjectDirectory.js (this file is in the project's root directory because you are putting it there).
module.exports = {
root() {
return __dirname;
}
}
In some other file:
const ProjectDirectory = require('path/to/ProjectDirectory');
console.log(`Project root directory is ${ProjectDirectory.root}`);
When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.
Strings using set()
:
set(MyString "Some Text")
set(MyStringWithVar "Some other Text: ${MyString}")
set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")
Or with string()
:
string(APPEND MyStringWithContent " ${MyString}")
Lists using set()
:
set(MyList "a" "b" "c")
set(MyList ${MyList} "d")
Or better with list()
:
list(APPEND MyList "a" "b" "c")
list(APPEND MyList "d")
Lists of File Names:
set(MySourcesList "File.name" "File with Space.name")
list(APPEND MySourcesList "File.name" "File with Space.name")
add_excutable(MyExeTarget ${MySourcesList})
set()
Commandstring()
Commandlist()
CommandFirst there are the "Normal Variables" and things you need to know about their scope:
CMakeLists.txt
they are set in and everything called from there (add_subdirectory()
, include()
, macro()
and function()
).add_subdirectory()
and function()
commands are special, because they open-up their own scope.
set(...)
there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).set(... PARENT_SCOPE)
function(xyz _resultVar)
is setting set(${_resultVar} 1 PARENT_SCOPE)
include()
or macro()
scripts will modify variables directly in the scope of where they are called from. Second there is the "Global Variables Cache". Things you need to know about the Cache:
CMakeCache.txt
file in your binary output directory.The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type
and a docstring
. I normally don't use the GUI so I use set(... CACHE INTERNAL "")
to set my global and persistant values.
Please note that the INTERNAL
cache variable type does imply FORCE
In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE)
syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.
cmake -D var:type=value
, just cmake -D var=value
or with cmake -C CMakeInitialCache.cmake
.unset(... CACHE)
.The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...)
and set_property(GLOBAL APPEND PROPERTY ...)
syntax to define my own non-persistant global variables.
To avoid pitfalls you should know the following about variables:
find_...
commands - if successful - do write their results as cached variables "so that no call will search again"set(MyVar a b c)
is "a;b;c"
and set(MyVar "a b c")
is "a b c"
list()
command for handling listsfunctions()
instead of macros()
because you don't want your local variables to show up in the parent scope. project()
and enable_language()
calls. So it could get important to set some variables before those commands are used.Sometimes only debugging variables helps. The following may help you:
printf
debugging style by using the message()
command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmakeCMakeCache.txt
file in your binary output directory. This file is even generated if the actual generation of your make environment fails.cmake --trace ...
to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.$ENV{...}
and write set(ENV{...} ...)
environment variables$<...>
are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)${${...}}
you can give variable names in a variable and reference its content.if()
command)
if(MyVariable)
you can directly check a variable for true/false (no need here for the enclosing ${...}
)1
, ON
, YES
, TRUE
, Y
, or a non-zero number. 0
, OFF
, NO
, FALSE
, N
, IGNORE
, NOTFOUND
, the empty string, or ends in the suffix -NOTFOUND
.if(MSVC)
, but it can be confusing for someone who does not know this syntax shortcut.set(CMAKE_${lang}_COMPILER ...)
if()
commands. Here is an example where CMAKE_CXX_COMPILER_ID
is "MSVC"
and MSVC
is "1"
:
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
is true, because it evaluates to if("1" STREQUAL "1")
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
is false, because it evaluates to if("MSVC" STREQUAL "1")
if(MSVC)
cmake_policy(SET CMP0054 NEW)
to "only interpret if()
arguments as variables or keywords when unquoted."option()
command
ON
or OFF
and they allow some special handling like e.g. dependenciesoption
with the set
command. The value given to option
is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.Use a nice editor like SciTe, select your code, press Ctrl + Q and done.
If you don't have an editor that supports block comments you can use a triple quoted string at the start and the end of your code block to 'effectively' comment it out. It is not the best practice though.
You can use DataColumn.Ordinal
to get the index of the column in the DataTable
. So if you need the next column as mentioned use Column.Ordinal + 1
:
row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;
Select a cell in the cell range in which the data is imported, then Menu > Data > Properties > uncheck save query definition.
Properties will be greyed out unless a cell in the data import range is selected.
You can find out the range in which the data isimported by:
Menu > Data > Connections > (select connection) > Click here to see where the selected connections are used.
To add on to chepner's answer for Python 3.0 you can alternatively do:
x = lambda x: list(map(print, x))
Of course this is only if you have the means of using Python > 3 in the future... Looks a bit cleaner in my opinion, but it also has a weird return value, but you're probably discarding it anyway.
I'll just leave this here for reference.
you can use the DomDocument method to get an individual HTML tag level variable too
$homepage = file_get_contents('https://www.example.com/');
$doc = new DOMDocument;
$doc->loadHTML($homepage);
$titles = $doc->getElementsByTagName('h3');
echo $titles->item(0)->nodeValue;
For v3 users.
http://google.github.io/proto-lens/installing-protoc.html
PROTOC_ZIP=protoc-3.7.1-osx-x86_64.zip
curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.7.1/$PROTOC_ZIP
sudo unzip -o $PROTOC_ZIP -d /usr/local bin/protoc
sudo unzip -o $PROTOC_ZIP -d /usr/local 'include/*'
rm -f $PROTOC_ZIP
Add
"aaSorting": []
And check if default value is not null
only set sortable column then
if ($('#table').DataTable().order().length == 1) {
d.SortColumn = $('#table').DataTable().order()[0][0];
d.SortOrder = $('#table').DataTable().order()[0][1];
}
Even though this is an old question and the OP asked for C# I would like to share a VB.Net solution for those, who work with VB.Net rather than C#:
Dim myObj As Object = Nothing
Dim s As String = If(myObj, "").ToString()
myObj = 42
s = If(myObj, "").ToString()
Unfortunatly VB.Net doesn't allow the ?-operator after a variable so myObj?.ToString isn't valid (at least not in .Net 4.5, which I used for testing the solution). Instead I use the If to return an empty string in case myObj ist Nothing. So the first Tostring-Call return an an empty string, while the second (where myObj is not Nothing) returns "42".
Typically, git commit
brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR
environment variable) for you to edit your commit message in. When you save and exit, the commit completes.
You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.