Using gawk
:
gawk '{$1=$1}1' OFS="\n" file
outside device,we can use :
adb install file.apk
or adb install -r file.apk
adb install [-l] [-r] [-s] [--algo <algorithm name> --key <hex-encoded key> --iv <hex-encoded iv>] <file>
- push this package file to the device and install it
('-l' means forward-lock the app)
('-r' means reinstall the app, keeping its data)
('-s' means install on SD card instead of internal storage)
('--algo', '--key', and '--iv' mean the file is encrypted already)
inside devices also, we can use:
pm install file.apk
or pm install -r file.apk
pm install: installs a package to the system. Options:
-l: install the package with FORWARD_LOCK.
-r: reinstall an exisiting app, keeping its data.
-t: allow test .apks to be installed.
-i: specify the installer package name.
-s: install package on sdcard.
-f: install package on internal flash.
-d: allow version code downgrade.
For more then one apk file on Linux we can use xargs
and on windows we can use for loop
.
Linux / Unix sample :
ls -1 *.apk | xargs -I xxx adb install -r xxx
.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.
.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).
Why don't you just do
>>> m = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> c = np.array([0,1,2])
>>> (m.T * c).T
??
This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:
sh: blabla.py: command not found
If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:
$command = escapeshellcmd('python blabla.py');
There are many PS1 generators but ezprompt has the git status (2nd tab 'Status Elements' ) also.
CodeProject articles discussing and sharing source code for scaling images:
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
I set the NODEJS variable in the system control panel but the only thing that worked to set the path was to do it from command line as administrator.
SET PATH=%NODEJS%;%PATH%
Another trick is that once you set the path you must close the console and open a new one for the new path to be taken into account.
However for the regular user to be able to use node I had to run set path again not as admin and restart the computer
This one gives you the columns that are PK.
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = 'TableName'
A While
/Wend
loop can only be exited prematurely with a GOTO
or by exiting from an outer block (Exit sub
/function
or another exitable loop)
Change to a Do
loop instead:
Do While True
count = count + 1
If count = 10 Then
Exit Do
End If
Loop
Or for looping a set number of times:
for count = 1 to 10
msgbox count
next
(Exit For
can be used above to exit prematurely)
Try to open Services Window, by writing services.msc
into Start->Run and hit Enter.
When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.
This is if you publish your app in both Google Play Store and Amazon Appstore. I also handle the case that users (especially in China) don't have both app store and browser.
public void goToMyApp(boolean googlePlay) {//true if Google Play, false if Amazone Store
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse((googlePlay ? "market://details?id=" : "amzn://apps/android?p=") +getPackageName())));
} catch (ActivityNotFoundException e1) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse((googlePlay ? "http://play.google.com/store/apps/details?id=" : "http://www.amazon.com/gp/mas/dl/android?p=") +getPackageName())));
} catch (ActivityNotFoundException e2) {
Toast.makeText(this, "You don't have any app that can open this link", Toast.LENGTH_SHORT).show();
}
}
}
FWIW, I was getting this error when I was accidentally making a GET request to an endpoint that was expecting a POST request. Presumably that was just that particular servers way of handling the problem.
If you use code.google.com
to host your Subversion repository.
You know below things, right?
If you plan to make changes, use this command to check out the code as yourself using HTTPS:
# Project members authenticate over HTTPS to allow committing changes.
svn checkout https://.../svn/trunk/ user-...
When prompted, enter your generated googlecode.com password.
Use this command to anonymously check out the latest project source code:
# Non-members may check out a read-only working copy anonymously over HTTP.
svn checkout http://.../svn/trunk/ ...-read-only
The error you mentioned exactly you are using Non-members may check out a read-only working copy anonymously over HTTP
status. Therefore, you can not commit or do anything so far.
You must use Project members authenticate over HTTPS to allow committing changes
thing.
It will be fine now.
You can use the status command in MySQL client.
mysql> status;
--------------
mysql Ver 14.14 Distrib 5.5.8, for Win32 (x86)
Connection id: 1
Current database: test
Current user: ODBC@localhost
SSL: Not in use
Using delimiter: ;
Server version: 5.5.8 MySQL Community Server (GPL)
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: latin1
Db characterset: latin1
Client characterset: gbk
Conn. characterset: gbk
TCP port: 3306
Uptime: 7 min 16 sec
Threads: 1 Questions: 21 Slow queries: 0 Opens: 33 Flush tables: 1 Open tables: 26 Queries per second avg: 0.48
--------------
mysql>
In Your RecyclerView in Kotlin
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
textViewcolor.text = t.name
}
}
You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.
Or better, try to avoid naming your classes "Date".
Since upgrading my typings to react 0.14.43 (I'm not sure exactly when this was introduced), the React.FormEvent type is now generic and this removes the need for a cast.
import React = require('react');
interface ITestState {
selectedValue: string;
}
export class Test extends React.Component<{}, ITestState> {
constructor() {
super();
this.state = { selectedValue: "A" };
}
change(event: React.FormEvent<HTMLSelectElement>) {
// No longer need to cast to any - hooray for react!
var safeSearchTypeValue: string = event.currentTarget.value;
console.log(safeSearchTypeValue); // in chrome => B
this.setState({
selectedValue: safeSearchTypeValue
});
}
render() {
return (
<div>
<label htmlFor="searchType">Safe</label>
<select className="form-control" id="searchType" onChange={ e => this.change(e) } value={ this.state.selectedValue }>
<option value="A">A</option>
<option value="B">B</option>
</select>
<h1>{this.state.selectedValue}</h1>
</div>
);
}
}
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
git pull origin master --allow-unrelated-histories
You might want to use this if your histories doesnt match and want to merge it anyway..
refer here
If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:
window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")
Then, in your new route, you can do the following to retrieve the previous URL:
window.history.state.prevUrl // your previous url
Just Add the JRE PATH FOR Ex: C:\Program Files\Java\jre5\bin in the environmental variable Put ";" in between every path. Then click the eclipse.exe It will work.....
To align some elements (headerElement) in the center and the last element to the right (headerEnd).
.headerElement {
margin-right: 5%;
margin-left: 5%;
}
.headerEnd{
margin-left: auto;
}
Update:
This linked answer describes a cleaner, simpler way of doing the same thing with C# syntax.
Original post
This is Microsoft's recommended way to handle WCF client calls:
For more detail see: Expected Exceptions
try
{
...
double result = client.Add(value1, value2);
...
client.Close();
}
catch (TimeoutException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
catch (CommunicationException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
Additional information
So many people seem to be asking this question on WCF that Microsoft even created a dedicated sample to demonstrate how to handle exceptions:
c:\WF_WCF_Samples\WCF\Basic\Client\ExpectedExceptions\CS\client
Considering that there are so many issues involving the using statement, (heated?) Internal discussions and threads on this issue, I'm not going to waste my time trying to become a code cowboy and find a cleaner way. I'll just suck it up, and implement WCF clients this verbose (yet trusted) way for my server applications.
System.Text.StringBuilder hash = new System.Text.StringBuilder();
System.Security.Cryptography.MD5CryptoServiceProvider md5provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bytes = md5provider.ComputeHash(new System.Text.UTF8Encoding().GetBytes(YourEntryString));
for (int i = 0; i < bytes.Length; i++)
{
hash.Append(bytes[i].ToString("x2")); //lowerCase; X2 if uppercase desired
}
return hash.ToString();
I know this is an old thread, but none of the answers really did it for me - either inefficient, or not encapsulated for easy reuse. I also wanted to ensure it returned false if the string was empty or null. TryParse returns true in this case (an empty string does not cause an error when parsing as a number). So, here's my string extension method:
public static class Extensions
{
/// <summary>
/// Returns true if string is numeric and not empty or null or whitespace.
/// Determines if string is numeric by parsing as Double
/// </summary>
/// <param name="str"></param>
/// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
/// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
/// <returns></returns>
public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
CultureInfo culture = null)
{
double num;
if (culture == null) culture = CultureInfo.InvariantCulture;
return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
}
}
Simple to use:
var mystring = "1234.56789";
var test = mystring.IsNumeric();
Or, if you want to test other types of number, you can specify the 'style'. So, to convert a number with an Exponent, you could use:
var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);
Or to test a potential Hex string, you could use:
var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)
The optional 'culture' parameter can be used in much the same way.
It is limited by not being able to convert strings that are too big to be contained in a double, but that is a limited requirement and I think if you are working with numbers larger than this, then you'll probably need additional specialised number handling functions anyway.
It's as easy as using select:
Get-Content file.txt | Select -Index (line - 1)
E.g. to get line 5
Get-Content file.txt | Select -Index 4
Or you can use:
(Get-Content file.txt)[4]
You can use float on that particular div, e.g.
<div style="float:right;">
Float the div you want more space to have to the left as well:
<div style="float:left;">
If all else fails give the div on the right position:absolute and then move it as right as you want it to be.
<div style="position:absolute; left:-500px; top:30px;">
etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.
From System Preferences, turn on the "Show Keyboard & Character Viewer in menu bar" setting.
Then, the "Character Viewer" menu will pop up a tool that will let you search for any unicode character (by name) and insert it ? you're all set.
Opacity serves your purpose?
If so, try this:
$('#elem').css('opacity','0.3')
Permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Using HttpURLConnection
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class DownloadFileUseHttpURLConnection extends Activity {
ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
String dwnload_file_path =
"http://coderzheaven.com/sample_folder/sample_file.png";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.b1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showProgress(dwnload_file_path);
new Thread(new Runnable() {
public void run() {
downloadFile();
}
}).start();
}
});
}
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"downloaded_file.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize/totalSize) *
100;
cur_val.setText("Downloaded " + downloadedSize +
"KB / " + totalSize + "KB (" + (int)per + "%)" );
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// pb.dismiss(); // if you want close it..
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
showError("Error : Please check your internet connection " +
e);
}
}
void showError(final String err){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(DownloadFileDemo1.this, err,
Toast.LENGTH_LONG).show();
}
});
}
void showProgress(String file_path){
dialog = new Dialog(DownloadFileDemo1.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.myprogressdialog);
dialog.setTitle("Download Progress");
TextView text = (TextView) dialog.findViewById(R.id.tv1);
text.setText("Downloading file from ... " + file_path);
cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
cur_val.setText("Starting download...");
dialog.show();
pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
pb.setProgress(0);
pb.setProgressDrawable(
getResources().getDrawable(R.drawable.green_progress));
}
}
I wrote an App that runs a WebServer (REST-Like) on your Android Phone, so you can set the GPS position remotely. The website provides an Map on which you can click to set a new position, or use the "wasd" keys to move in any direction. The app was a quick solution so there is nearly no UI nor Documentation, but the implementation is straight forward and you can look everything up in the (only four) classes.
Project repository: https://github.com/juliusmh/RemoteGeoFix
insert into table1 values("sunil''s book",123,99382932938);
use double apostrophe inside of single apostrophe, it will work
MD5 worked for me changing my database manually. See: Resetting Your Password
Task.GetAwaiter().GetResult()
is preferred over Task.Wait
and Task.Result
because it propagates exceptions rather than wrapping them in an AggregateException
. However, all three methods cause the potential for deadlock and thread pool starvation issues. They should all be avoided in favor of async/await
.
The quote below explains why Task.Wait
and Task.Result
don't simply contain the exception propagation behavior of Task.GetAwaiter().GetResult()
(due to a "very high compatibility bar").
As I mentioned previously, we have a very high compatibility bar, and thus we’ve avoided breaking changes. As such,
Task.Wait
retains its original behavior of always wrapping. However, you may find yourself in some advanced situations where you want behavior similar to the synchronous blocking employed byTask.Wait
, but where you want the original exception propagated unwrapped rather than it being encased in anAggregateException
. To achieve that, you can target the Task’s awaiter directly. When you write “await task;
”, the compiler translates that into usage of theTask.GetAwaiter()
method, which returns an instance that has aGetResult()
method. When used on a faulted Task,GetResult()
will propagate the original exception (this is how “await task;
” gets its behavior). You can thus use “task.GetAwaiter().GetResult()
” if you want to directly invoke this propagation logic.
https://blogs.msdn.microsoft.com/pfxteam/2011/09/28/task-exception-handling-in-net-4-5/
“
GetResult
” actually means “check the task for errors”In general, I try my best to avoid synchronously blocking on an asynchronous task. However, there are a handful of situations where I do violate that guideline. In those rare conditions, my preferred method is
GetAwaiter().GetResult()
because it preserves the task exceptions instead of wrapping them in anAggregateException
.
http://blog.stephencleary.com/2014/12/a-tour-of-task-part-6-results.html
With all due respect to all involved parties; I'm very surprised to see how many of you could clear the entire fragment back stack with a simple
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
According to Android documentation (regarding the name
argument - the "null" in the claimed working proposals).
If null, only the top state is popped
Now, I do realize that I'm lacking knowledge of your particular implementations (like how many entries you have in the back stack at the given point in time), but I would bet all my money on the accepted answer when expecting a well defined behaviour over a wider range of devices and vendors:
(for reference, something along with this)
FragmentManager fm = getFragmentManager(); // or 'getSupportFragmentManager();'
int count = fm.getBackStackEntryCount();
for(int i = 0; i < count; ++i) {
fm.popBackStack();
}
If you want to use std::string
reliably, you must #include <string>
.
You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.
So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filter
s.
You don't fetch a branch, you fetch an entire remote:
git fetch origin
git merge origin/an-other-branch
Short answer:
There is no difference in semantic.
Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
Further reading:
RequestMapping
can be used at class level:
This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.
while GetMapping
only applies to method:
Annotation for mapping HTTP GET requests onto specific handler methods.
A general fast function that will react well:
A minified function for fast, safe and low weight with:
function sepNum(r,e){return e=e||",",r=String(r).replace(/[\u0660-\u0669\u06f0-\u06f9]/g,function(r){return 15&r.charCodeAt(0)}).replace(/(?:[^\.]|^)\b(\d+)/g,function(r){return r=r.replace(/\B(?=(\d{3})+\b)/g,e)})}_x000D_
_x000D_
Text='1000000 and .0002 5000.1234 with 500000Kg but not V10012.231';_x000D_
console.log(sepNum(Text));
_x000D_
+ Explain:
function thousandSeparatorAllNonDecimal (x,sep) {
if(!sep) sep=','; //seprator by defualt is comma but can be changed
x=String(x) // Making Sure the X is String, because RegEx will work just with strings
.replace(/[\u0660-\u0669\u06f0-\u06f9]/g, // [Optional] RegEx for Finding all non English Digit (like ["?", "?", "?", "?", "?", "?", "?", "?", "?", "?"]
function (c) { return c.charCodeAt(0) & 0xf; }) // return of the function of the Regex => Replacing all with the same Englsih Digit (possible some android keyboards just type non english digit)
.replace(/(?:[^\.]|^)\b(\d+)/g, // Finding all numbers that are not started by dot by the RegEx :
// 0) (?:) : any that
// 1) [^\.] : not same to dot
// 2) |^ or any thing else that
// 3) \b : not sticked to any word from behind [Optional] (it can have another \b in end to check if not sticked from front to any word too, or no any \b too, but we want it take some numbers like 50000Kg)
// +5)
function(x){ // Process them one by one separated, by this function
x=x.replace(/\B(?=(\d{3})+\b)/g, // Now by this RegEx replacing any 3 by 3 digit
sep); // now using separator in the RegEx replace
return x;} // now return the result to main function
);return x // and returning the main result out
}
And the fastest regex can be JUST for both Non-decimal and decimals :
/\B(?=(\d{3})+\b)/g
But i think still as @uKolka said, the right idea for a single value, with some prefixing [Optional : parseFloat] and postfixing [Optional : Replacing '.00'] is:
Num=parseFloat(Num).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:true}).replace('.00','');
as the full example here: https://jsfiddle.net/PAPIONbit/198xL3te/
Xcode 8 and Swift 3.0
Using URLSession:
let url = URL(string:"Download URL")!
let req = NSMutableURLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)
let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()
URLSession Delegate call:
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
print("downloaded \(100*writ/exp)" as AnyObject)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
}
Using Block GET/POST/PUT/DELETE:
let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:"Your request timeout time in Seconds")
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers as? [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
let httpResponse = response as? HTTPURLResponse
if (error != nil) {
print(error)
} else {
print(httpResponse)
}
DispatchQueue.main.async {
//Update your UI here
}
}
dataTask.resume()
Working fine for me.. try it 100% result guarantee
If you want to fire the event only on changes of your input use:
$('.s').bind('input', function(){
console.log("search!");
doSearch();
});
tracert
/traceroute
to find number of hopsTry This
import hashlib
user = input("Enter text here ")
h = hashlib.md5(user.encode())
h2 = h.hexdigest()
print(h2)
in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)
e.g.
<?php
//plum or data...
$output = array("data","plum");
echo json_encode($output);
?>
in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
success function(json_data){
var data_array = $.parseJSON(json_data);
//access your data like this:
var plum_or_whatever = data_array['output'];.
//continue from here...
}
});
Code:
using System;
using System.Diagnostics;
namespace playSound
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(args[0]);
Process amixerMediaProcess = new Process();
amixerMediaProcess.StartInfo.CreateNoWindow = false;
amixerMediaProcess.StartInfo.UseShellExecute = false;
amixerMediaProcess.StartInfo.ErrorDialog = false;
amixerMediaProcess.StartInfo.RedirectStandardOutput = false;
amixerMediaProcess.StartInfo.RedirectStandardInput = false;
amixerMediaProcess.StartInfo.RedirectStandardError = false;
amixerMediaProcess.EnableRaisingEvents = true;
amixerMediaProcess.StartInfo.Arguments = string.Format("{0}","-ssh username@"+args[0]+" -pw password -m commands.txt");
amixerMediaProcess.StartInfo.FileName = "plink.exe";
amixerMediaProcess.Start();
Console.Write("Presskey to continue . . . ");
Console.ReadKey(true);
}
}
}
Sample commands.txt:
ps
go to cmd get into file directory and type jupyter notebook filename.ipynb in my case it open code editor and provide local host connection string copy that string and paste in any browser!done
You can "style echo" with adding new HTML code.
echo '<span class="city">' . $ip['cityName'] . '</span>';
My answer on this question might help you:
int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
iv.getViewTreeObserver().removeOnPreDrawListener(this);
finalHeight = iv.getMeasuredHeight();
finalWidth = iv.getMeasuredWidth();
tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
return true;
}
});
You can then add your image scaling work from within the onPreDraw() method.
Here is a solution that works in Chrome and Chromium (have only tested these platforms). It seems Chrome has some bug or own approach to handling key codes so this property has to be added separately to the KeyboardEvent.
function simulateKeydown (keycode,isCtrl,isAlt,isShift){
var e = new KeyboardEvent( "keydown", { bubbles:true, cancelable:true, char:String.fromCharCode(keycode), key:String.fromCharCode(keycode), shiftKey:isShift, ctrlKey:isCtrl, altKey:isAlt } );
Object.defineProperty(e, 'keyCode', {get : function() { return this.keyCodeVal; } });
e.keyCodeVal = keycode;
document.dispatchEvent(e);
}
simulateKeydown(39, false, false, false);
_x000D_
For context, I created a project using the ASP.NET Core 2 Web Application template. Then, select the Web Application (MVC) then hit the Change Authentication button and select Individual User accounts.
There is a lot of infrastructure built up for you from this template. Find the ManageController
in the Controllers folder.
This ManageController
class constructor requires this UserManager variable to populated:
private readonly UserManager<ApplicationUser> _userManager;
Then, take a look at the the [HttpPost] Index method in this class. They get the current user in this fashion:
var user = await _userManager.GetUserAsync(User);
As a bonus note, this is where you want to update any custom fields to the user Profile you've added to the AspNetUsers table. Add the fields to the view, then submit those values to the IndexViewModel which is then submitted to this Post method. I added this code after the default logic to set the email address and phone number:
user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.Address1 = model.Address1;
user.Address2 = model.Address2;
user.City = model.City;
user.State = model.State;
user.Zip = model.Zip;
user.Company = model.Company;
user.Country = model.Country;
user.SetDisplayName();
user.SetProfileID();
_dbContext.Attach(user).State = EntityState.Modified;
_dbContext.SaveChanges();
You should never have an empty catch block. It is like hiding a mistake you know about. At the very least you should write out an exception to a log file to review later if you are pressed for time.
What about replace the item if you know the position:
aList[0]=2014
Or if you don't know the position loop in the list, find the item and then replace it
aList = [123, 'xyz', 'zara', 'abc']
for i,item in enumerate(aList):
if item==123:
aList[i]=2014
break
print aList
You could simply have: var result = (str == "true")
.
Xenph Yan's answer was far cleaner than mine but here is mine all the same.
DECLARE @startStr AS Varchar (20)
SET @startStr = 'tableName'
DECLARE @startStrLen AS int
SELECT @startStrLen = LEN(@startStr)
SELECT 'DROP TABLE ' + name FROM sysobjects
WHERE type = 'U' AND LEFT(name, @startStrLen) = @startStr
Just change tableName
to the characters that you want to search with.
You can use this JQuery for uncheck radiobutton
$('input:radio[name="IntroducerType"]').removeAttr('checked');
$('input:radio[name="IntroducerType"]').prop('checked', false);
I found after trying lots of convoluted examples that very simple approach worked for me.
I just wanted to take a dump of a db from local and import it on a remote instance:
on the local machine:
mongodump -d databasename
then I scp'd my dump to my server machine:
scp -r dump [email protected]:~
then from the parent dir of the dump simply:
mongorestore
and that imported the database.
assuming mongodb service is running of course.
Instance variable is the variable declared inside a class, but outside a method: something like:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
Now this IronMan Class can be instantiated in another class to use these variables. Something like:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.
(Your question is still unclear on whether your code is calling printStackTrace()
or this is being done by a logging handler.)
Here are some possible explanations about what might be happening:
The logger / handler being used has been configured to only output the exception's message string, not a full stack trace.
Your application (or some third-party library) is logging the exception using LOG.error(ex);
rather than the 2-argument form of (for example) the log4j Logger method.
The message is coming from somewhere different to where you think it is; e.g. it is actually coming some third-party library method, or some random stuff left over from earlier attempts to debug.
The exception that is being logged has overloaded some methods to obscure the stacktrace. If that is the case, the exception won't be a genuine NullPointerException, but will be some custom subtype of NPE or even some unconnected exception.
I think that the last possible explanation is pretty unlikely, but people do at least contemplate doing this kind of thing to "prevent" reverse engineering. Of course it only really succeeds in making life difficult for honest developers.
Try this it works
<ul class="sub-menu" type="none">
<li class="sub-menu-list" ng-repeat="menu in list.components">
<a class="sub-menu-link">
{{ menu.component }}
</a>
</li>
</ul>
Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp
If that's not an option for any reason, you could try giving the list items classes:
<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>
Then in your css:
li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/
You can install unix2dos with Homebrew
brew install unix2dos
Then you can do this:
unix2dos file-to-convert
You can also convert dos files to unix:
dos2unix file-to-convert
I thought I'd add another perspective here. The answer depends on whether the question is assuming weak scaling or strong scaling.
From Wikipedia:
Weak scaling: how the solution time varies with the number of processors for a fixed problem size per processor.
Strong scaling: how the solution time varies with the number of processors for a fixed total problem size.
If the question is assuming weak scaling then @Gonzalo's answer suffices. However if the question is assuming strong scaling, there's something more to add. In strong scaling you're assuming a fixed workload size so if you increase the number of threads, the size of the data that each thread needs to work on decreases. On modern CPUs memory accesses are expensive and would be preferable to maintain locality by keeping the data in caches. Therefore, the likely optimal number of threads can be found when the dataset of each thread fits in each core's cache (I'm not going into the details of discussing whether it's L1/L2/L3 cache(s) of the system).
This holds true even when the number of threads exceeds the number of cores. For example assume there's 8 arbitrary unit (or AU) of work in the program which will be executed on a 4 core machine.
Case 1: run with four threads where each thread needs to complete 2AU. Each thread takes 10s to complete (with a lot of cache misses). With four cores the total amount of time will be 10s (10s * 4 threads / 4 cores).
Case 2: run with eight threads where each thread needs to complete 1AU. Each thread takes only 2s (instead of 5s because of the reduced amount of cache misses). With four cores the total amount of time will be 4s (2s * 8 threads / 4 cores).
I've simplified the problem and ignored overheads mentioned in other answers (e.g., context switches) but hope you get the point that it might be beneficial to have more number of threads than the available number of cores, depending on the data size you're dealing with.
Actually you don't have to create an image at all. drawImage()
will accept a Canvas
as well as an Image
object.
//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');
//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);
Way faster than using an ImageData
object or Image
element.
Note that sourceCanvas
can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas
.
Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element
The code
my_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
print t
prints
(1, 2)
(3, 4)
(5, 6)
The loop iterates over my_list
, and assigns the elements of my_list
to t
one after the other. The elements of my_list
happen to be tuples, so t
will always be a tuple. To access the first element of the tuple t
, use t[0]
:
for t in my_list:
print t[0]
To access the first element of the tuple at the given index i
in the list, you can use
print my_list[i][0]
I got this error due to not pointing the script to the correct path. So make absolutely sure that you are pointing to the correct path in you html file.
Using ignore Duplicates
on the unique index as suggested by IanC here was my solution for a similar issue, creating the index with the Option WITH IGNORE_DUP_KEY
In backward compatible syntax
, WITH IGNORE_DUP_KEY is equivalent to WITH IGNORE_DUP_KEY = ON.
Ref.: index_option
For WINDOWS users
"standard" packaging tools situation is improving recently:
on pypi itself, there are now 48% of wheel packages as of sept. 11th 2015 (up from 38% in may 2015 , 24% in sept. 2014),
the wheel format is now supported out-of-the-box per latest python 2.7.9,
"standard"+"tweaks" packaging tools situation is improving also:
you can find nearly all scientific packages on wheel format at http://www.lfd.uci.edu/~gohlke/pythonlibs,
the mingwpy project may bring one day a 'compilation' package to windows users, allowing to install everything from source when needed.
"Conda" packaging remains better for the market it serves, and highlights areas where the "standard" should improve.
(also, the dependency specification multiple-effort, in standard wheel system and in conda system, or buildout, is not very pythonic, it would be nice if all these packaging 'core' techniques could converge, via a sort of PEP)
For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.
This ultimately ends up being subjective. The discussion thus far is useful, but I don't think there is a correct or decisive answer to this. A lot will depend on style guidelines and your needs at the time.
While there are some different capabilities (whether or not something can be NULL) with a pointer, the largest practical difference for an output parameter is purely syntax. Google's C++ Style Guide (https://google.github.io/styleguide/cppguide.html#Reference_Arguments), for example, mandates only pointers for output parameters, and allows only references that are const. The reasoning is one of readability: something with value syntax should not have pointer semantic meaning. I'm not suggesting that this is necessarily right or wrong, but I think the point here is that it's a matter of style, not of correctness.
my customize list hope it illustrate concept
public class second extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
// TextView textview=(TextView)findViewById(R.id.textView1);
// textview.setText(getIntent().getExtras().getString("value"));
setListAdapter(new MyAdapter(this,R.layout.list_item,R.id.textView1, getResources().getStringArray(R.array.counteries)));
}
private class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] objects) {
super(context, resource, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.list_item,parent,false);
String[]items=getResources().getStringArray(R.array.counteries);
ImageView iv=(ImageView) row.findViewById(R.id.imageView1);
TextView tv=(TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("unitedstates")){
iv.setImageResource(R.drawable.usa);
}else if(items[position].equals("Russia")){
iv.setImageResource(R.drawable.russia);
}else if(items[position].equals("Japan")){
iv.setImageResource(R.drawable.japan);
}
// TODO Auto-generated method stub
return row;
}
}
}
There are several ways to reload the current page using a button or other trigger. The examples below use a button click to reload the page but you can use a text hyperlink or any trigger you like.
<input type="button" value="Reload Page" onClick="window.location.reload()">
<input type="button" value="Reload Page" onClick="history.go(0)">
<input type="button" value="Reload Page" onClick="window.location.href=window.location.href">
What you want is a timer:
// RxJS v6+
import { timer } from 'rxjs';
//emit [1, 2, 3] after 1 second.
const source = timer(1000).map(([1, 2, 3]);
//output: [1, 2, 3]
const subscribe = source.subscribe(val => console.log(val));
Try the following:
SELECT *, (FieldA + FieldB) AS Sum
FROM Table
From MySQL docs:
A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.
Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.
Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.
But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.
In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).
AngularJS and jQuery adopt very different ideologies. If you're coming from jQuery you may find some of the differences surprising. Angular may make you angry.
This is normal, you should push through. Angular is worth it.
jQuery gives you a toolkit for selecting arbitrary bits of the DOM and making ad-hoc changes to them. You can do pretty much anything you like piece by piece.
AngularJS instead gives you a compiler.
What this means is that AngularJS reads your entire DOM from top to bottom and treats it as code, literally as instructions to the compiler. As it traverses the DOM, It looks for specific directives (compiler directives) that tell the AngularJS compiler how to behave and what to do. Directives are little objects full of JavaScript which can match against attributes, tags, classes or even comments.
When the Angular compiler determines that a piece of the DOM matches a particular directive, it calls the directive function, passing it the DOM element, any attributes, the current $scope (which is a local variable store), and some other useful bits. These attributes may contain expressions which can be interpreted by the Directive, and which tell it how to render, and when it should redraw itself.
Directives can then in turn pull in additional Angular components such as controllers, services, etc. What comes out the bottom of the compiler is a fully formed web application, wired up and ready to go.
This means that Angular is Template Driven. Your template drives the JavaScript, not the other way around. This is a radical reversal of roles, and the complete opposite of the unobtrusive JavaScript we have been writing for the last 10 years or so. This can take some getting used to.
If this sounds like it might be over-prescriptive and limiting, nothing could be farther from the truth. Because AngularJS treats your HTML as code, you get HTML level granularity in your web application. Everything is possible, and most things are surprisingly easy once you make a few conceptual leaps.
Let's get down to the nitty gritty.
Angular and jQuery do different things. AngularJS gives you a set of tools to produce web applications. jQuery mainly gives you tools for modifying the DOM. If jQuery is present on your page, AngularJS will use it automatically. If it isn't, AngularJS ships with jQuery Lite, which is a cut down, but still perfectly usable version of jQuery.
Misko likes jQuery and doesn't object to you using it. However you will find as you advance that you can get a pretty much all of your work done using a combination of scope, templates and directives, and you should prefer this workflow where possible because your code will be more discrete, more configurable, and more Angular.
If you do use jQuery, you shouldn't be sprinkling it all over the place. The correct place for DOM manipulation in AngularJS is in a directive. More on these later.
jQuery is typically applied unobtrusively. Your JavaScript code is linked in the header (or the footer), and this is the only place it is mentioned. We use selectors to pick out bits of the page and write plugins to modify those parts.
The JavaScript is in control. The HTML has a completely independent existence. Your HTML remains semantic even without JavaScript. Onclick attributes are very bad practice.
One of the first things your will notice about AngularJS is that custom attributes are everywhere. Your HTML will be littered with ng attributes, which are essentially onClick attributes on steroids. These are directives (compiler directives), and are one of the main ways in which the template is hooked to the model.
When you first see this you might be tempted to write AngularJS off as old school intrusive JavaScript (like I did at first). In fact, AngularJS does not play by those rules. In AngularJS, your HTML5 is a template. It is compiled by AngularJS to produce your web page.
This is the first big difference. To jQuery, your web page is a DOM to be manipulated. To AngularJS, your HTML is code to be compiled. AngularJS reads in your whole web page and literally compiles it into a new web page using its built in compiler.
Your template should be declarative; its meaning should be clear simply by reading it. We use custom attributes with meaningful names. We make up new HTML elements, again with meaningful names. A designer with minimal HTML knowledge and no coding skill can read your AngularJS template and understand what it is doing. He or she can make modifications. This is the Angular way.
One of the first questions I asked myself when starting AngularJS and running through the tutorials is "Where is my code?". I've written no JavaScript, and yet I have all this behaviour. The answer is obvious. Because AngularJS compiles the DOM, AngularJS is treating your HTML as code. For many simple cases it's often sufficient to just write a template and let AngularJS compile it into an application for you.
Your template drives your application. It's treated as a DSL. You write AngularJS components, and AngularJS will take care of pulling them in and making them available at the right time based on the structure of your template. This is very different to a standard MVC pattern, where the template is just for output.
It's more similar to XSLT than Ruby on Rails for example.
This is a radical inversion of control that takes some getting used to.
Stop trying to drive your application from your JavaScript. Let the template drive the application, and let AngularJS take care of wiring the components together. This also is the Angular way.
With jQuery your HTML page should contain semantic meaningful content. If the JavaScript is turned off (by a user or search engine) your content remains accessible.
Because AngularJS treats your HTML page as a template. The template is not supposed to be semantic as your content is typically stored in your model which ultimately comes from your API. AngularJS compiles your DOM with the model to produce a semantic web page.
Your HTML source is no longer semantic, instead, your API and compiled DOM are semantic.
In AngularJS, meaning lives in the model, the HTML is just a template, for display only.
At this point you likely have all sorts of questions concerning SEO and accessibility, and rightly so. There are open issues here. Most screen readers will now parse JavaScript. Search engines can also index AJAXed content. Nevertheless, you will want to make sure you are using pushstate URLs and you have a decent sitemap. See here for a discussion of the issue: https://stackoverflow.com/a/23245379/687677
Separation of concerns (SOC) is a pattern that grew up over many years of web development for a variety of reasons including SEO, accessibility and browser incompatibility. It looks like this:
Again, AngularJS does not play by their rules. In a stroke, AngularJS does away with a decade of received wisdom and instead implements an MVC pattern in which the template is no longer semantic, not even a little bit.
It looks like this:
MVC and SOC are not on opposite ends of the same scale, they are on completely different axes. SOC makes no sense in an AngularJS context. You have to forget it and move on.
If, like me, you lived through the browser wars, you might find this idea quite offensive. Get over it, it'll be worth it, I promise.
Plugins extend jQuery. AngularJS Directives extend the capabilities of your browser.
In jQuery we define plugins by adding functions to the jQuery.prototype. We then hook these into the DOM by selecting elements and calling the plugin on the result. The idea is to extend the capabilities of jQuery.
For example, if you want a carousel on your page, you might define an unordered list of figures, perhaps wrapped in a nav element. You might then write some jQuery to select the list on the page and restyle it as a gallery with timeouts to do the sliding animation.
In AngularJS, we define directives. A directive is a function which returns a JSON object. This object tells AngularJS what DOM elements to look for, and what changes to make to them. Directives are hooked in to the template using either attributes or elements, which you invent. The idea is to extend the capabilities of HTML with new attributes and elements.
The AngularJS way is to extend the capabilities of native looking HTML. You should write HTML that looks like HTML, extended with custom attributes and elements.
If you want a carousel, just use a <carousel />
element, then define a directive to pull in a template, and make that sucker work.
The tendency with jQuery is to write great big plugins like lightbox which we then configure by passing in numerous values and options.
This is a mistake in AngularJS.
Take the example of a dropdown. When writing a dropdown plugin you might be tempted to code in click handlers, perhaps a function to add in a chevron which is either up or down, perhaps change the class of the unfolded element, show hide the menu, all helpful stuff.
Until you want to make a small change.
Say you have a menu that you want to unfold on hover. Well now we have a problem. Our plugin has wired in our click handler for us, we're going to need to add a configuration option to make it behave differently in this specific case.
In AngularJS we write smaller directives. Our dropdown directive would be ridiculously small. It might maintain the folded state, and provide methods to fold(), unfold() or toggle(). These methods would simply update $scope.menu.visible which is a boolean holding the state.
Now in our template we can wire this up:
<a ng-click="toggle()">Menu</a>
<ul ng-show="menu.visible">
...
</ul>
Need to update on mouseover?
<a ng-mouseenter="unfold()" ng-mouseleave="fold()">Menu</a>
<ul ng-show="menu.visible">
...
</ul>
The template drives the application so we get HTML level granularity. If we want to make case by case exceptions, the template makes this easy.
JQuery plugins are created in a closure. Privacy is maintained within that closure. It's up to you to maintain your scope chain within that closure. You only really have access to the set of DOM nodes passed in to the plugin by jQuery, plus any local variables defined in the closure and any globals you have defined. This means that plugins are quite self contained. This is a good thing, but can get restrictive when creating a whole application. Trying to pass data between sections of a dynamic page becomes a chore.
AngularJS has $scope objects. These are special objects created and maintained by AngularJS in which you store your model. Certain directives will spawn a new $scope, which by default inherits from its wrapping $scope using JavaScript prototypical inheritance. The $scope object is accessible in the controller and the view.
This is the clever part. Because the structure of $scope inheritance roughly follows the structure of the DOM, elements have access to their own scope, and any containing scopes seamlessly, all the way up to the global $scope (which is not the same as the global scope).
This makes it much easier to pass data around, and to store data at an appropriate level. If a dropdown is unfolded, only the dropdown $scope needs to know about it. If the user updates their preferences, you might want to update the global $scope, and any nested scopes listening to the user preferences would automatically be alerted.
This might sound complicated, in fact, once you relax into it, it's like flying. You don't need to create the $scope object, AngularJS instantiates and configures it for you, correctly and appropriately based on your template hierarchy. AngularJS then makes it available to your component using the magic of dependency injection (more on this later).
In jQuery you make all your DOM changes by hand. You construct new DOM elements programatically. If you have a JSON array and you want to put it to the DOM, you must write a function to generate the HTML and insert it.
In AngularJS you can do this too, but you are encouraged to make use of data binding. Change your model, and because the DOM is bound to it via a template your DOM will automatically update, no intervention required.
Because data binding is done from the template, using either an attribute or the curly brace syntax, it's super easy to do. There's little cognitive overhead associated with it so you'll find yourself doing it all the time.
<input ng-model="user.name" />
Binds the input element to $scope.user.name
. Updating the input will update the value in your current scope, and vice-versa.
Likewise:
<p>
{{user.name}}
</p>
will output the user name in a paragraph. It's a live binding, so if the $scope.user.name
value is updated, the template will update too.
In jQuery making an Ajax call is fairly simple, but it's still something you might think twice about. There's the added complexity to think about, and a fair chunk of script to maintain.
In AngularJS, Ajax is your default go-to solution and it happens all the time, almost without you noticing. You can include templates with ng-include. You can apply a template with the simplest custom directive. You can wrap an Ajax call in a service and create yourself a GitHub service, or a Flickr service, which you can access with astonishing ease.
In jQuery, if we want to accomplish a small non-dom related task such as pulling a feed from an API, we might write a little function to do that in our closure. That's a valid solution, but what if we want to access that feed often? What if we want to reuse that code in another application?
AngularJS gives us service objects.
Services are simple objects that contain functions and data. They are always singletons, meaning there can never be more than one of them. Say we want to access the Stack Overflow API, we might write a StackOverflowService
which defines methods for doing so.
Let's say we have a shopping cart. We might define a ShoppingCartService which maintains our cart and contains methods for adding and removing items. Because the service is a singleton, and is shared by all other components, any object that needs to can write to the shopping cart and pull data from it. It's always the same cart.
Service objects are self-contained AngularJS components which we can use and reuse as we see fit. They are simple JSON objects containing functions and Data. They are always singletons, so if you store data on a service in one place, you can get that data out somewhere else just by requesting the same service.
AngularJS manages your dependencies for you. If you want an object, simply refer to it and AngularJS will get it for you.
Until you start to use this, it's hard to explain just what a massive time boon this is. Nothing like AngularJS DI exists inside jQuery.
DI means that instead of writing your application and wiring it together, you instead define a library of components, each identified by a string.
Say I have a component called 'FlickrService' which defines methods for pulling JSON feeds from Flickr. Now, if I want to write a controller that can access Flickr, I just need to refer to the 'FlickrService' by name when I declare the controller. AngularJS will take care of instantiating the component and making it available to my controller.
For example, here I define a service:
myApp.service('FlickrService', function() {
return {
getFeed: function() { // do something here }
}
});
Now when I want to use that service I just refer to it by name like this:
myApp.controller('myController', ['FlickrService', function(FlickrService) {
FlickrService.getFeed()
}]);
AngularJS will recognise that a FlickrService object is needed to instantiate the controller, and will provide one for us.
This makes wiring things together very easy, and pretty much eliminates any tendency towards spagettification. We have a flat list of components, and AngularJS hands them to us one by one as and when we need them.
jQuery says very little about how you should organise your code. AngularJS has opinions.
AngularJS gives you modules into which you can place your code. If you're writing a script that talks to Flickr for example, you might want to create a Flickr module to wrap all your Flickr related functions in. Modules can include other modules (DI). Your main application is usually a module, and this should include all the other modules your application will depend on.
You get simple code reuse, if you want to write another application based on Flickr, you can just include the Flickr module and voila, you have access to all your Flickr related functions in your new application.
Modules contain AngularJS components. When we include a module, all the components in that module become available to us as a simple list identified by their unique strings. We can then inject those components into each other using AngularJS's dependency injection mechanism.
AngularJS and jQuery are not enemies. It's possible to use jQuery within AngularJS very nicely. If you're using AngularJS well (templates, data-binding, $scope, directives, etc.) you will find you need a lot less jQuery than you might otherwise require.
The main thing to realise is that your template drives your application. Stop trying to write big plugins that do everything. Instead write little directives that do one thing, then write a simple template to wire them together.
Think less about unobtrusive JavaScript, and instead think in terms of HTML extensions.
I got so excited about AngularJS, I wrote a short book on it which you're very welcome to read online http://nicholasjohnson.com/angular-book/. I hope it's helpful.
To get a prompt with the color depending on the last command’s exit status, you could use this:
PS1='%(?.%F{green}.%F{red})%n@%m:%~%# %f'
Just add this line to your ~/.zshrc
.
The documentation lists possible placeholders.
Try this one. It is a code from CSS tricks that I modified, it is pretty straight forward and does both horizontal and vertial scrolling. Needs JQuery. Here is a demo
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top-10, scrollLeft:target.offset().left-10
}, 1000);
return false;
}
}
});
});
Use function gmdate()
only if seconds are less than 86400
(1 day) :
$seconds = 8525;
echo gmdate('H:i:s', $seconds);
# 02:22:05
See: gmdate()
Convert seconds to format by 'foot' no limit* :
$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05
See: floor(), sprintf(), arithmetic operators
Example use of DateTime
extension:
$seconds = 8525;
$zero = new DateTime("@0");
$offset = new DateTime("@$seconds");
$diff = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
# 02:22:05
See: DateTime::__construct(), DateTime::modify(), clone, sprintf()
MySQL example range of the result is constrained to that of the TIME data type, which is from -838:59:59
to 838:59:59
:
SELECT SEC_TO_TIME(8525);
# 02:22:05
See: SEC_TO_TIME
PostgreSQL example:
SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS');
# 02:22:05
Be advised that if you're using nodejs there's (at the time of writing) a dependency on libssl 1.0.* - so installing an alternative SSL library will break your nodejs installation.
An alternative solution to installing a different SSL library is that posted in this answer here: https://stackoverflow.com/a/59927568/13564342 to instead install libcurl4-gnutls-dev
sudo apt install libcurl4-gnutls-dev
There's an easier solution for this, but it requires that you know exactly how much inheritance your current class has gone through. Fortunately, get_parent_class()'s arguments allow your class array member to be the class name as a string as well as an instance itself.
Bear in mind that this also inherently relies on calling a class' __construct() method statically, though within the instanced scope of an inheriting object the difference in this particular case is negligible (ah, PHP).
Consider the following:
class Foo {
var $f = 'bad (Foo)';
function __construct() {
$this->f = 'Good!';
}
}
class Bar extends Foo {
var $f = 'bad (Bar)';
}
class FooBar extends Bar {
var $f = 'bad (FooBar)';
function __construct() {
# FooBar constructor logic here
call_user_func(array(get_parent_class(get_parent_class($this)), '__construct'));
}
}
$foo = new FooBar();
echo $foo->f; #=> 'Good!'
Again, this isn't a viable solution for a situation where you have no idea how much inheritance has taken place, due to the limitations of debug_backtrace(), but in controlled circumstances, it works as intended.
clrscr
is not standard C function. According to internet, it used to be a thing in old Borland C.
Is clrscr(); a function in C++?
a MySQL-only solution would be something like this:
SELECT IF (UNIX_TIMESTAMP(`field`) > UNIX_TIMESTAMP(), `field`,'GO AHEAD') as `yourdate`
FROM `table`
Platform-dependent, toolchain-dependent, ulimit-dependent, parameter-dependent.... It is not at all specified, and there are many static and dynamic properties that can influence it.
Laravel provides a Query Builder with lists() function
In your case, you can replace your code
$items = Items::all(['id', 'name']);
with
$items = Items::lists('name', 'id');
Also, you can chain it with other Query Builder as well.
$items = Items::where('active', true)->orderBy('name')->lists('name', 'id');
source: http://laravel.com/docs/5.0/queries#selects
Update for Laravel 5.2
Thank you very much @jarry. As you mentioned, the function for Laravel 5.2 should be
$items = Items::pluck('name', 'id');
or
$items = Items::where('active', true)->orderBy('name')->pluck('name', 'id');
ref: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0 -- look at Deprecations lists
Re-posted as an answer: Found an alternative (Tested in Win8):
cmdkey /generic:"<server>" /user:"<user>" /pass:"<pass>"
Run that and if you run:
mstsc /v:<server>
You should not get an authentication prompt.
A simple one would be
\d{4}-\d{2}-\d{2}
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
thanks to the answers of Steve Park and Rafal Borowiec I got my code working, however, I had one issue: the DriverManagerDataSource is a "simple" implementation and does NOT give you a ConnectionPool (check http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/DriverManagerDataSource.html).
Hence, I replaced the functions which returns the DataSource
for the secondDB
to.
public DataSource <secondaryDB>DataSource() {
// use DataSourceBuilder and NOT DriverManagerDataSource
// as this would NOT give you ConnectionPool
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.url(databaseUrl);
dataSourceBuilder.username(username);
dataSourceBuilder.password(password);
dataSourceBuilder.driverClassName(driverClassName);
return dataSourceBuilder.build();
}
Also, if do you not need the EntityManager
as such, you can remove both the entityManager()
and the @Bean
annotation.
Plus, you may want to remove the basePackages annotation of your configuration class: maintaining it with the factoryBean.setPackagesToScan()
call is sufficient.
Built off the above but with dynamic creation and a vector image, not drawing.
function svgztruck() {
tok = "{d path value}"
return tok;
}
function buildsvg( eid ) {
console.log("building");
var zvg = "svg" + eid;
var vvg = eval( zvg );
var raw = vvg();
var svg = document.getElementById( eid );
svg.setAttributeNS(null,"d", raw );
svg.setAttributeNS(null,"fill","green");
svg.setAttributeNS(null,"onlick", eid + ".style.fill=#FF0000");
return;
}
You could call with:
<img src="" onerror="buildscript">
Now you can add colors by sub element and manipulate all elements of the dom directly. It is important to implement your viewbox and height width first on the svg html, not done in the example above.
There is no need to make your code 10 pages when it could be one... but who am I to argue. Better use PHP
while your at it.
The inner element that svg builds on is a simple <svg lamencoding id=parenteid><path id=eid><svg>
with nothing else.
After reading the additional details, I agree with robcthegeek: raise an event. Create a custom EventArgs and pass the neccessary parameters through it.
During maven compilation you can skip test execution by adding following plugin in pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
There is GitHub Enterprise to satisfy your needs. And there is an open source "clone" of Github Enterprise.
PS: Now Github provides unlimited private repositories, bitbucket does the same. you can give a try to both. There are several other solutions as well.
You can use recursion here to do this. For example:
jQuery(document).ready(checkContainer);
function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}
Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid()
function. If not, it will wait 50ms and try again.
Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)
You want to pass the function object hi
to your loop()
function, not the result of a call to hi()
(which is None
since hi()
doesn't return anything).
So try this:
>>> loop(hi, 5)
hi
hi
hi
hi
hi
Perhaps this will help you understand better:
>>> print hi()
hi
None
>>> print hi
<function hi at 0x0000000002422648>
Bootstrap 4
Use the data-parent=""
attribute on the collapse element (instead of the trigger element)
<div id="accordion">
<div class="card">
<div class="card-header">
<h5>
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
Collapsible #1 trigger
</button>
</h5>
</div>
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="card-body">
Collapsible #1 element
</div>
</div>
</div>
... (more cards/collapsibles inside #accordion parent)
</div>
Bootstrap 3
See this issue on GitHub: https://github.com/twbs/bootstrap/issues/10966
There is a "bug" that makes the accordion dependent on the .panel
class when using the data-parent
attribute. To workaround it, you can wrap each accordion group in a 'panel' div..
<div class="accordion" id="myAccordion">
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
<div id="collapsible-1" class="collapse">
..
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
<div id="collapsible-2" class="collapse">
..
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
<div id="collapsible-3" class="collapse">
...
</div>
</div>
</div>
Edit
As mentioned in the comments, each section doesn't have to be a .panel
. However...
.panel
must be a direct child of the element used as data-parent=
data-toggle=
) must be a direct child of the .panel
(http://www.bootply.com/AbiRW7BdD6#)I would try to solve this without VBA. Just select this space and use replace (change to nothing) on that worksheet you're trying to get rid off those spaces.
If you really want to use VBA I believe you could select first character
strSpace = left(range("A1").Value,1)
and use replace function in VBA the same way
Range("A1").Value = Replace(Range("A1").Value, strSpace, "")
or
for each cell in selection.cells
cell.value = replace(cell.value, strSpace, "")
next
@Shaikovsky's answer is excellent (…and heavily edited since I posted this answer), but I wanted to clarify a couple of points.
[next(generator) for _ in range(n)]
This is the most simple approach, but throws StopIteration
if the generator is prematurely exhausted.
On the other hand, the following approaches return up to n
items which is preferable in many circumstances:
List:
[x for _, x in zip(range(n), records)]
Generator:
(x for _, x in zip(range(n), records))
If you use MVC, tables, it works like this:
<td>@(((DateTime)detalle.fec).ToString("dd'/'MM'/'yyyy"))</td>
Try deleting the adbkey file from C/.android folder
and then run the commands as mentioned above i.e.
adb kill-server, adb start-server and adb devices
.
Use the CSS function from jQuery to set styles to your items :
$('#buttonId').css({ "background-color": 'brown'});
So after reading a bit on how git sets up the repo. I realized that I ran the command
git push origin master
but instead for the first time I should have ran
git push -u origin master
which sets up the upstream initially. Way to go!
toCharArray
followed by Arrays.sort
followed by a String constructor call:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String original = "edcba";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println(sorted);
}
}
EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.
You have to tell your SQLCommand objects to use the transaction:
cmd1.Transaction = transaction;
or in the constructor:
SqlCommand cmd1 = new SqlCommand("select...", connectionsql, transaction);
Make sure to have the connectionsql object open, too.
But all you are doing are SELECT statements. Transactions would benefit more when you use INSERT, UPDATE, etc type actions.
Text to speech is built into Android 1.6+. Here is a simple example of how to do it.
TextToSpeech tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);
More info: http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html
Here are instructions on how to download sample code from the Android SDK Manager:
Launch the Android SDK Manager.
a. On Windows, double-click the SDK Manager.exe file at the root of the Android SDK directory.
b. On Mac or Linux, open a terminal to the tools/ directory in the Android SDK, then execute android sdk.
Expand the list of packages for the latest Android platform.
/sdk/samples/android-version/
(i.e. \android-sdk-windows\samples\android-16\ApiDemos\src\com\example\android\apis\app\TextToSpeechActivity.java)
Similar to what Mark E has proposed, you have to come up with your own. Just to help you a bit, there is a neat article http://gleichmann.wordpress.com/2008/01/15/building-your-own-literals-in-java-tuples-and-maps/ which gives you a really neat way of creating tuples and maps that might be something you might want to consider.
Use a linked list. It was designed for this exact situation.
If you still need the dictionary O(1) lookups, use both a dictionary and a linked list.
It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)
git pull origin master
for me that simple call solved those error messages:
For people that have PowerShell 3 or later (i.e. Windows Server 2012+ or Windows Server 2008 R2 with the Windows Management Framework 4.0 update), you can do this one-liner instead of invoking System.Net.WebRequest
:
$statusCode = wget http://stackoverflow.com/questions/20259251/ | % {$_.StatusCode}
At first glance it doesn't look like you are doing anything wrong but you don't show all your code. The following worked for me when I was first checking out S3 and Node:
var AWS = require('aws-sdk');
if (typeof process.env.API_KEY == 'undefined') {
var config = require('./config.json');
for (var key in config) {
if (config.hasOwnProperty(key)) process.env[key] = config[key];
}
}
var s3 = new AWS.S3({accessKeyId: process.env.AWS_ID, secretAccessKey:process.env.AWS_KEY});
var objectPath = process.env.AWS_S3_FOLDER +'/test.xml';
s3.putObject({
Bucket: process.env.AWS_S3_BUCKET,
Key: objectPath,
Body: "<rss><data>hello Fred</data></rss>",
ACL:'public-read'
}, function(err, data){
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data); // successful response
s3.getObject({
Bucket: process.env.AWS_S3_BUCKET,
Key: objectPath
}, function(err, data){
console.log(data.Body.toString());
});
}
});
I got here googling for C# compiler error CS0176, through (duplicate) question Static member instance reference issue.
In my case, the error happened because I had a static method and an extension method with the same name. For that, see Static method and extension method with same name.
[May be this should have been a comment. Sorry that I don't have enough reputation yet.]
To push up through a given commit, you can write:
git push <remotename> <commit SHA>:<remotebranchname>
provided <remotebranchname>
already exists on the remote. (If it doesn't, you can use git push <remotename> <commit SHA>:refs/heads/<remotebranchname>
to autocreate it.)
If you want to push a commit without pushing previous commits, you should first use git rebase -i
to re-order the commits.
Since you have only one edit text then just call action done for that edit text inside your button click and the rest is handled by the system. If you had more than one edittext then this would not be so efficent because you have to get the focused edittext first. But in your case it will work perfectly
myedittext.onEditorAction(EditorInfo.IME_ACTION_DONE)
It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.
I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
End Sub
http://php.net/manual/en/reserved.variables.post.php
The first comment answers this.
<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>
<?php
var_dump($_POST['person']);
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>
The name tag can work as an array.
Following up on Mark's answer, if you're not using Jupyter for some reason, e.g. you want to do some quick testing on the console, you can use the DataFrame.to_string
method, which works from -- at least -- Pandas 0.12 (2014) onwards.
import pandas as pd
matrix = [(1, 23, 45), (789, 1, 23), (45, 678, 90)]
df = pd.DataFrame(matrix, columns=list('abc'))
print(df.to_string())
# outputs:
# a b c
# 0 1 23 45
# 1 789 1 23
# 2 45 678 90
You don't have the last version of typescript.
Running :
npm install -g typescript
npm
checks if tsc
command is already installed.
And it might be, by another software like Visual Studio
. If so, npm
doesn't override it. So you have to remove the previous deprecated tsc
installed command.
Run where tsc
to know its bin location. It should be in C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\
in windows. Once found, delete the folder, and re-run npm install -g typescript
. This should now install the last version of typescript.
Not exactly what the user asked, but an easy way to just count unique values:
Google introduced a new function to count unique values in just one step, and you can use this as an input for other formulas:
=COUNTUNIQUE(A1:B10)
If you using Android Studio 3.1.+ or above
just put this in your gradle depedencies:
implementation 'com.android.support:support-annotations:27.1.1'
Overall like this:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:support-annotations:27.1.1'
}
This code sums both the variables! Put it into your function
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = (y +z);
document.getElementById("demo").innerHTML = x;`
Goto the Start Menu Right Click "Computer" Select "Properties" A dialog should pop up with a link on the left called "Advanced system settings". Click it. In the System Properties dialog, click the button called "Environment Variables". In the Environment Variables dialog look for "Path" under the System Variables window. Add ";C:\Python27" to the end of it. The semicolon is the path separator on windows. Click Ok and close the dialogs. Now open up a new command prompt and type "python"
If still the problem persists then type "py" instead of "python" in command prompt. might help!!!!
There is a simple solution, which is the HTML5 input
event. It's supported in current versions of all major browsers for <input type="text">
elements and there's a simple workaround for IE < 9. See the following answers for more details:
Example (except IE < 9: see links above for workaround):
$("#your_id").on("input", function() {
alert("Change to " + this.value);
});
Normally, Visual Studio creates it automatically if you add three single comment-markers above the thing you like to comment (method, class).
In C# this would be ///
.
If Visual Studio doesn't do this, you can enable it in
Options->Text Editor->C#->Advanced
and check
Generate XML documentation comments for ///
Don't know if this is too late, but the way I solved this was to draw four thin rectangles that together made up a one big border. Drawing the border with one rectangle seems to be undoable since they're all opaque, so you should draw each edge of the border separately.
CREATE OR REPLACE FUNCTION IS_NUMERIC(P_INPUT IN VARCHAR2) RETURN INTEGER IS
RESULT INTEGER;
NUM NUMBER ;
BEGIN
NUM:=TO_NUMBER(P_INPUT);
RETURN 1;
EXCEPTION WHEN OTHERS THEN
RETURN 0;
END IS_NUMERIC;
/
You can use this regular expression (any whitespace or any non-whitespace) as many times as possible down to and including 0.
[\s\S]*
This expression will match as few as possible, but as many as necessary for the rest of the expression.
[\s\S]*?
For example, in this regex [\s\S]*?B
will match aB
in aBaaaaB
. But in this regex [\s\S]*B
will match aBaaaaB
in aBaaaaB
.
Just in case it helps someone - In my scenario, I have some shared libraries (Which have their own TFS projects/solutions) all combined into one solution.
Nuget would restore projects successfully, but the DLL would be missing.
The underlying issue was that, whilst your solution has its own packages folder and has restored them correctly to that folder, the project file (e.g. .csproj) is referencing a different project which may not have the package downloaded. Open the file in a text editor to see where your references are coming from.
This can occur when managing packages on different interlinked shared solutions - since you probably want to make sure all DLLs are on the same level you might set this at the top level. This means it that sometimes it will be looking in a completely different solution for a referenced DLL and so if you don't have all projects/solutions downloaded and up-to-date then you may get the above problem.
String st="2202";
int cp=Integer.parseInt(st,16);// it convert st into hex number.
char c[]=Character.toChars(cp);
System.out.println(c);// its display the character corresponding to '\u2202'.
That code should work, but you need to include the localization in your page (it isn't included by default). Try putting this in your <head>
tag, somewhere after you include jQuery and jQueryUI:
<script type="text/javascript"
src="https://raw.githubusercontent.com/jquery/jquery-ui/master/ui/i18n/datepicker-fr.js">
</script>
I can't find where this is documented on the jQueryUI site, but if you view the source of this demo you'll see that this is how they do it. Also, please note that including this JS file will set the datepicker defaults to French, so if you want only some datepickers to be in French, you'll have to set the default back to English.
You can find all languages here at github: https://github.com/jquery/jquery-ui/tree/master/ui/i18n
you can't force refresh but you can forward all old ip requests to new one. for a website:
replace [OLD_IP] with old server's ip
replace [NEW_IP] with new server's ip
run & win.
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 80 -j DNAT --to-destination [NEW_IP]:80
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 443 -j DNAT --to-destination [NEW_IP]:443
iptables -t nat -A POSTROUTING -j MASQUERADE
string.replace(/^\s+|\s+$/g, "");
I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information
Im a bit late to the party and I know the OP said html, but if you needed to do this in MVC you can set true
in the third param.
eg:
<p>Option One :@Html.RadioButton("options", "option1", true})</p>
// true will set it checked
<p>Option Two :@Html.RadioButton("options", "option2"})</p>
//nothing will leave it unchecked
If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:
javascript:alert("hello world");
And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.
Completing @chuck answer for using composite indices with foreign keys.
You need to define a property that will hold the value of the foreign key. You can then use this property inside the index definition.
For example, we have company with employees and only we have a unique constraint on (name, company) for any employee:
class Company
{
public Guid Id { get; set; }
}
class Employee
{
public Guid Id { get; set; }
[Required]
public String Name { get; set; }
public Company Company { get; set; }
[Required]
public Guid CompanyId { get; set; }
}
Now the mapping of the Employee class:
class EmployeeMap : EntityTypeConfiguration<Employee>
{
public EmployeeMap ()
{
ToTable("Employee");
Property(p => p.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(p => p.Name)
.HasUniqueIndexAnnotation("UK_Employee_Name_Company", 0);
Property(p => p.CompanyId )
.HasUniqueIndexAnnotation("UK_Employee_Name_Company", 1);
HasRequired(p => p.Company)
.WithMany()
.HasForeignKey(p => p.CompanyId)
.WillCascadeOnDelete(false);
}
}
Note that I also used @niaher extension for unique index annotation.
For MySQL 8*
SET GLOBAL validate_password.policy=LOW
Reference Link to explain about policy - Click Here
You can use .toggle()
function instead of .click()
....
HttpWebRequest myHttprequest = null;
HttpWebResponse myHttpresponse = null;
myHttpRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.ContentLength = urinfo.Length;
StreamWriter writer = new StreamWriter(myHttprequest.GetRequestStream());
writer.Write(urinfo);
writer.Close();
myHttpresponse = (HttpWebResponse)myHttpRequest.GetResponse();
if (myHttpresponse.StatusCode == HttpStatusCode.OK)
{
//Perform necessary action based on response
}
myHttpresponse.Close();
I have slightly improved answer, which handles extended CSS definitions like:
background-image: url(http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png), -webkit-linear-gradient(top, rgb(81, 127, 164), rgb(48, 96, 136))
JavaScript code:
var bg = $("div").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
Result:
"http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png"
Based on drspaceboo's solution, with Kotlin you can use an extension to convert Float
to dips more easily.
fun Float.toDips() =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, resources.displayMetrics);
Usage:
(65f).toDips()
Easy and fast solution.
I just scroll to the right cell whenever scrolling happens
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
Assuming I know table now is in this mode "_keepMyCellOnTop" & I know selected cell "_selectedCellIndex" or scroll to selected cell
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (_keepMyCellOnTop)
{
[self.tableView scrollToRowAtIndexPath:_selectedCellIndex atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
}
This will prevent scrolling.
Placing the code in -(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
will result a scroll up and down
The "dropzone.js" is the most common library for uploading images. If you want to have the "dropzone.js" as just part of your form, you should do the following steps:
1) for the client side:
HTML :
<form action="/" enctype="multipart/form-data" method="POST">
<input type="text" id ="Username" name ="Username" />
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
</form>
<div>
<button type="submit" id="submit-all"> upload </button>
</div>
JQuery:
<script>
Dropzone.options.myDropzone = {
url: "/Account/Create",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
acceptedFiles: "image/*",
init: function () {
var submitButton = document.querySelector("#submit-all");
var wrapperThis = this;
submitButton.addEventListener("click", function () {
wrapperThis.processQueue();
});
this.on("addedfile", function (file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-lg dark'>Remove File</button>");
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
wrapperThis.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
this.on('sendingmultiple', function (data, xhr, formData) {
formData.append("Username", $("#Username").val());
});
}
};
</script>
2) for the server side:
ASP.Net MVC
[HttpPost]
public ActionResult Create()
{
var postedUsername = Request.Form["Username"].ToString();
foreach (var imageFile in Request.Files)
{
}
return Json(new { status = true, Message = "Account created." });
}
Since Singleton Pattern is about having a private constructor and calling some method to control the instantiations (like some getInstance
), in Enums we already have an implicit private constructor.
I don't exactly know how the JVM or some container controls the instances of our Enums
, but it seems it already use an implicit Singleton Pattern
, the difference is we don't call a getInstance
, we just call the Enum.
For me it was because of vmware (services-it has about 2 or 3 different services),stop it and every thing works fine
Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.
The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.
The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.
When I align elements in center I use the bootstrap class text-center:
<div class="text-center">Centered content goes here</div>
Create the data/db directory in your main (windows) partition:
C:\> mkdir \data
C:\> mkdir \data\db
and then go to your mongo_directory/bin and run mongod.exe:
C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongod
DON't CLOSE THIS WINDOW
Now in a different command prompt window run Mongo:
C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongo
(REMEMBER YOU HAVE TO KEEP THAT OTHER WINDOW OPEN)
This solved the problem for me.
The default execution policy, "Restricted", prevents all scripts from running, including scripts that you write on the local computer.
The execution policy is saved in the registry, so you need to change it only once on each computer.
To change the execution policy, use the following procedure:
Start Windows PowerShell with the "Run as administrator" option.
At the command prompt, type:
Set-ExecutionPolicy AllSigned
-or-
Set-ExecutionPolicy RemoteSigned
The change is effective immediately.
To run a script, type the full name and the full path to the script file.
For example, to run the Get-ServiceLog.ps1
script in the C:\Scripts
directory, type:
C:\Scripts\Get-ServiceLog.ps1
And to the Python file, you have two points. Try to add your Python folder to your PATH and the extension .py
.
To PATHEXT from go properties of computer. Then click on advanced system protection. Then environment variable. Here you will find the two points.
If you use Java 8 date api, you can directly get it in one line!
LocalDate today = LocalDate.now();
int month = today.getMonthValue();
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
You seem to be specifying the form to use a HTTP 'GET' request using FormMethod.Get
. This will not work unless you tell it to do a post as that is what you seem to want the ActionResult to do. This will probably work by changing FormMethod.Get
to FormMethod.Post
.
As well as this you may also want to think about how Get and Post requests work and how these interact with the Model.
This procedure works even if ADB is not available.
All major browsers now include native JSON encoding/decoding.
// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject);
// To decode (This produces an object)
var obj = JSON.parse(json_str);
Note that only valid JSON data will be encoded. For example:
var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"
Valid JSON types are: objects, strings, numbers, arrays, true
, false
, and null
.
Some JSON resources:
<?php
if ($_POST['parse_var'] == "contactform"){
$emailTitle = 'New Email From KumbhAqua';
$yourEmail = '[email protected]';
$emailField = $_POST['email'];
$nameField = $_POST['name'];
$numberField = $_POST['number'];
$messageField = $_POST['message'];
$body = <<<EOD
<br><hr><br>
Email: $emailField <br />
Name: $nameField <br />
Message: $messageField <br />
EOD;
$headers = "from: $emailField\r\n";
$headers .= "Content-type: text/htmml\r\n";
$success = mail("$yourEmail", "$emailTitle", "$body", "$headers");
$sent ="Thank You ! Your Message Has Been sent.";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>:: KumbhAqua ::</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<link rel="stylesheet" href="style1.css" type="text/css">
</head>
<body>
<div class="container">
<div class="mainHeader">
<div class="transbox">
<p><font color="red" face="Matura MT Script Capitals" size="+5">Kumbh</font><font face="Matura MT Script Capitals" size="+5" color= "skyblue">Aqua</font><font color="skyblue"> Solution</font></p>
<p ><font color="skyblue">Your First Destination for Healthier Life.</font></p>
<nav><ul>
<li> <a href="KumbhAqua.html">Home</a></li>
<li> <a href="aboutus.html">KumbhAqua</a></li>
<li> <a href="services.html">Products</a></li>
<li class="active"> <a href="contactus.php">ContactUs</a></li>
</ul></nav>
</div>
</div>
</div>
<div class="main">
<div class="mainContent">
<h1 style="font-size:28px; letter-spacing: 16px; padding-top: 20px; text-align:center; text-transform: uppercase; color: #a7a7a7"><font color="red">Kumbh</font><font color="skyblue">Aqua</font> Symbol of purity</h1>
<div class="contactForm">
<form name="contactform" id="contactform" method="POST" action="contactus.php" >
Name :<br />
<input type="text" id="name" name="name" maxlength="30" size="30" value="<?php echo "nameField"; ?>" /><br />
E-mail :<br />
<input type="text" id="email" name="email" maxlength="50" size="50" value="<?php echo "emailField"; ?>" /><br />
Phone Number :<br />
<input type="text" id="number" name="number" value="<?php echo "numberField"; ?>"/><br />
Message :<br />
<textarea id="message" name="message" rows="10" cols="20" value="<?php echo "messageField"; ?>" >Some Text... </textarea>
<input type="reset" name="reset" id="reset" value="Reset">
<input type="hidden" name="parse_var" id="parse_var" value="contactform" />
<input type="submit" name="submit" id="submit" value="Submit"> <br />
<?php echo "$sent"; ?>
</form>
</div>
<div class="contactFormAdd">
<img src="Images/k1.JPG" width="200" height="200" title="Contactus" />
<h1>KumbhAqua Solution,</h1>
<strong><p>Saraswati Vihar Colony,<br />
New Cantt Allahabad, 211001
</p></strong>
<b>DEEPAK SINGH RISHIRAJ SINGH<br />
8687263459 8115120821 </b>
</div>
</div>
</div>
<footer class="mainFooter">
<nav>
<ul>
<li> <a href="KumbhAqua.html"> Home </a></li>
<li> <a href="aboutus.html"> KumbhAqua </a></li>
<li> <a href="services.html"> Products</a></li>
<li class="active"> <a href="contactus.php"> ContactUs </a></li>
</ul>
<div class="r_footer">
Copyright © 2015 <a href="#" Title="KumbhAqua">KumbhAqua.in</a> Created and Maintained By- <a title="Randheer Pratap Singh "href="#">RandheerSingh</a> </div>
</nav>
</footer>
</body>
</html>
enter code here
use typescript for your coding, because it's object oriented, strictly typed and easy to maintain the code ...
for more info about typescipt click here
Here one simple example I have created to share data between two controller using Typescript...
module Demo {
//create only one module for single Applicaiton
angular.module('app', []);
//Create a searvie to share the data
export class CommonService {
sharedData: any;
constructor() {
this.sharedData = "send this data to Controller";
}
}
//add Service to module app
angular.module('app').service('CommonService', CommonService);
//Create One controller for one purpose
export class FirstController {
dataInCtrl1: any;
//Don't forget to inject service to access data from service
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl1 = this.commonService.sharedData;
}
}
//add controller to module app
angular.module('app').controller('FirstController', FirstController);
export class SecondController {
dataInCtrl2: any;
static $inject = ['CommonService']
constructor(private commonService: CommonService) { }
public getDataFromService() {
this.dataInCtrl2 = this.commonService.sharedData;
}
}
angular.module('app').controller('SecondController', SecondController);
}
To answer the "How to print dataframe without an index" question, you can set the index to be an array of empty strings (one for each row in the dataframe), like this:
blankIndex=[''] * len(df)
df.index=blankIndex
If we use the data from your post:
row1 = (123, '2014-07-08 00:09:00', 1411)
row2 = (123, '2014-07-08 00:49:00', 1041)
row3 = (123, '2014-07-08 00:09:00', 1411)
data = [row1, row2, row3]
#set up dataframe
df = pd.DataFrame(data, columns=('User ID', 'Enter Time', 'Activity Number'))
print(df)
which would normally print out as:
User ID Enter Time Activity Number
0 123 2014-07-08 00:09:00 1411
1 123 2014-07-08 00:49:00 1041
2 123 2014-07-08 00:09:00 1411
By creating an array with as many empty strings as there are rows in the data frame:
blankIndex=[''] * len(df)
df.index=blankIndex
print(df)
It will remove the index from the output:
User ID Enter Time Activity Number
123 2014-07-08 00:09:00 1411
123 2014-07-08 00:49:00 1041
123 2014-07-08 00:09:00 1411
And in Jupyter Notebooks would render as per this screenshot: Juptyer Notebooks dataframe with no index column
In handlebar version 4.0 onwards,
{{#list array}}
{{@index}}
{{/list}}
In this article, they explain it in a very easy way but basically, we just need to execute a git remote set-url origin "https://<yourUserName>@bitbucket.org/<yourRepo>"
and next time you do a git pull
or a git push
you will have to put your password.
Here is how I resolved stated issue, hope it helps:
install python 3.7 using official website for python, while installing include installing PATH by checking it's box
after that open cmd (be sure to open it after step 1) and write: pip install jupyter ENTER
now you should be able to open jupyter notebook by using command: jupyter notebook
Seems simple, but it may as well help.
This question is a fairly difficult one. There is no real software limitation on the number of active connections a machine can have, though some OS's are more limited than others. The problem becomes one of resources. For example, let's say a single machine wants to support 64,000 simultaneous connections. If the server uses 1MB of RAM per connection, it would need 64GB of RAM. If each client needs to read a file, the disk or storage array access load becomes much larger than those devices can handle. If a server needs to fork one process per connection then the OS will spend the majority of its time context switching or starving processes for CPU time.
The C10K problem page has a very good discussion of this issue.
NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
This returns true only for NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.
1.3 Quick Checklist for Choosing HTTP GET
or POST
The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).
The interaction is more like an order, or
The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
The user be held accountable for the results of the interaction.
Here are some other files that may be left behind by setuptools:
MANIFEST
*.egg-info
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
You may consider writing a generic escape function:
def mk_esc(esc_chars):
return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
>>> esc = mk_esc('&#')
>>> print esc('Learn & be #1')
Learn \& be \#1
This way you can make your function configurable with a list of character that should be escaped.
Some troubleshooting tips, after I managed to waste two hours on the most trivial CORS issue:
If you see CORS policy execution failed
logged... Don't assume that your CORS policy is not executing properly. In fact, the CORS middleware works, and your policy is executing properly. The only thing this badly worded message means is that the request's origin doesn't match any of the allowed origins (see source), i.e. the request is disallowed.
The origin check (as of ASP.NET Core 5.0) happens in a very simple way... i.e. case-sensitive ordinal string comparison (see source) between the strings you provided via WithOrigins()
and what exists in HttpContext.Request.Headers[Origin]
.
CORS can fail if you set an allowed origin with a trailing slash /
, or if it contains uppercase letters. (In my case I did in fact accidentally copy the host with a trailing slash.)
View more detail from my previous answer I have created an nuget package Nuget
Code on Github
sample : you can use :
string login = "";
string domain = "";
string password = "";
using (UserImpersonation user = new UserImpersonation(login, domain, password))
{
if (user.ImpersonateValidUser())
{
File.WriteAllText("test.txt", "your text");
Console.WriteLine("File writed");
}
else
{
Console.WriteLine("User not connected");
}
}
Vieuw the full code :
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
/// <summary>
/// Object to change the user authticated
/// </summary>
public class UserImpersonation : IDisposable
{
/// <summary>
/// Logon method (check athetification) from advapi32.dll
/// </summary>
/// <param name="lpszUserName"></param>
/// <param name="lpszDomain"></param>
/// <param name="lpszPassword"></param>
/// <param name="dwLogonType"></param>
/// <param name="dwLogonProvider"></param>
/// <param name="phToken"></param>
/// <returns></returns>
[DllImport("advapi32.dll")]
private static extern bool LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
/// <summary>
/// Close
/// </summary>
/// <param name="handle"></param>
/// <returns></returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
private WindowsImpersonationContext _windowsImpersonationContext;
private IntPtr _tokenHandle;
private string _userName;
private string _domain;
private string _passWord;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
/// <summary>
/// Initialize a UserImpersonation
/// </summary>
/// <param name="userName"></param>
/// <param name="domain"></param>
/// <param name="passWord"></param>
public UserImpersonation(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
/// <summary>
/// Valiate the user inforamtion
/// </summary>
/// <returns></returns>
public bool ImpersonateValidUser()
{
bool returnValue = LogonUser(_userName, _domain, _passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref _tokenHandle);
if (false == returnValue)
{
return false;
}
WindowsIdentity newId = new WindowsIdentity(_tokenHandle);
_windowsImpersonationContext = newId.Impersonate();
return true;
}
#region IDisposable Members
/// <summary>
/// Dispose the UserImpersonation connection
/// </summary>
public void Dispose()
{
if (_windowsImpersonationContext != null)
_windowsImpersonationContext.Undo();
if (_tokenHandle != IntPtr.Zero)
CloseHandle(_tokenHandle);
}
#endregion
}
Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there
ADB Build-Tools Will Not be downloaded automatically, by command android update sdk --no-ui
So for installing Buil-Tool type (in console):
android list sdk --all
Remember the number that is listed before the item and execute the following:
android update sdk -u --all --filter <number>
commands should be typed in /YourFolder/android-sdk-linux/tools
Also for remote folder (server opened by ssh for example) type:
**./android** list sdk --all
**./android** update sdk -u --all --filter <number>
For simple list of ADB packages type in terminal:
android list sdk
for install all packages:
android update sdk --no-ui
Or with filters (comma is separator):
android update sdk --no-ui --filter 3,5,8,14
The European Central Bank (ECB) also has the most reliable free feed that I know of. It contains approx 28 currencies and is updated at least daily.
http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
For more formats and tools see the ECB reference page: http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:
You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.
Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.
private async Task<DateTime> CountToAsync(int num = 1000)
{
await Task.Yield();
for (int i = 0; i < num; i++)
{
Console.WriteLine("#{0}", i);
}
return DateTime.Now;
}
Try this:
java -jar -Dserver.port=8080 build/libs/APP_NAME_HERE.jar
JetBrains is going to add a decompiler to its ReSharper, and release a stand-alone decompiler too.
The good news is that we’re preparing a standalone binary-as-a-source application, i.e. a decompiler + assembly browser to explore whatever .NET compiled code is legal to explore. We don’t have any specific date for release, but it’s going to be released this year, and it’s going to be free of charge. And by saying “free”, we actually mean “free”.
Here is more information.
UPDATE: JetBrains has now released the product called dotPeek and it can be found here.
var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"
You can tweak the string to split by - if you use "code : "
, the second member of the returned array ([1]
) will contain "-1"
, using your example.
now append is a method in JavaScript
MDN documentation on append method
Quoting MDN
The
ParentNode.append
method inserts a set of Node objects orDOMString
objects after the last child of theParentNode
.DOMString
objects are inserted as equivalent Text nodes.
This is not supported by IE and Edge but supported by Chrome(54+), Firefox(49+) and Opera(39+).
The JavaScript's append is similar to jQuery's append.
You can pass multiple arguments.
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&modestbranding=1&controls=2&showinfo=1
That worked for me, it still showed subscribe and it showed share link, but no youtube button to take them off the page to another. So that's the line I will use that I think will keep traffic my site and not take off to all the other sites.
1 - You can use the same activity as both dialog and full screen, dynamically:
Call setTheme(android.R.style.Theme_Dialog)
before calling setContentView(...)
and super.oncreate()
in your Activity.
2 - If you don't plan to change the activity theme style you can use
<activity android:theme="@android:style/Theme.Dialog" />
(as mentioned by @faisal khan)
You can use str.replaceAll("[^0-9]", "");
private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter pressed");
}
}
Worked for me.
I am suggesting a much simpler utility I just wrote. It's currently called par, but will be renamed soon to either parl or pll, haven't decided yet.
API is as simple as:
par "script1.sh" "script2.sh" "script3.sh"
Prefixing commands can be done via:
par "PARPREFIX=[script1] script1.sh" "script2.sh" "script3.sh"
Here's how I "automate" Dropping connected users in Oracle database:
# A shell script to Drop a Database Schema, forcing off any Connected Sessions (for example, before an Import)
# Warning! With great power comes great responsibility.
# It is often advisable to take an Export before Dropping a Schema
if [ "$1" = "" ]
then
echo "Which Schema?"
read schema
else
echo "Are you sure? (y/n)"
read reply
[ ! $reply = y ] && return 1
schema=$1
fi
sqlplus / as sysdba <<EOF
set echo on
alter user $schema account lock;
-- Exterminate all sessions!
begin
for x in ( select sid, serial# from v\$session where username=upper('$schema') )
loop
execute immediate ( 'alter system kill session '''|| x.Sid || ',' || x.Serial# || ''' immediate' );
end loop;
dbms_lock.sleep( seconds => 2 ); -- Prevent ORA-01940: cannot drop a user that is currently connected
end;
/
drop user $schema cascade;
quit
EOF
You can also use this, it's simpler. The only thing you need to set is "YourDataBaseName".
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Where to place the connection string
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings>
<clear />
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
</configuration>
One solution to this is to do what msysGit's rebasing merge script does - after the rebase, merge in the old head of feature
with -s ours
. You end up with the commit graph:
A--B--C------F--G (master)
\ \
\ D'--E' (feature)
\ /
\ --
\ /
D--E (old-feature)
... and your push of feature
will be a fast-forward.
In other words, you can do:
git checkout feature
git branch old-feature
git rebase master
git merge -s ours old-feature
git push origin feature
(Not tested, but I think that's right...)
Simply the response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o" however you have to specify datatype in your request to be of type dataType='json'
Unfortunately, No. You will you have to go through a loop and count them.
EDIT :
var arrLength = arr.filter(Number);
alert(arrLength);
You can use the %in%
operator:
vec <- c(1, 2, 3, 4, 5)
1 %in% vec # true
10 %in% vec # false
Use a margin to space around an element.
.box {
margin: top right bottom left;
}
.box {
margin: 10px 5px 10px 5px;
}
This adds space outside of the element. So background colours, borders etc will not be included.
If you want to add spacing within an element use padding instead. It can be called in the same way as above.
From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.
In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).
Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family
list or to use a downloadable font. See my Guide to using special characters in HTML.
Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum
Indeed simplest way. Don't bother with changing the headers.
Make sure you have:
<%= csrf_meta_tag %> in your layouts/application.html.erb
Just do a hidden input field like so:
<input name="authenticity_token"
type="hidden"
value="<%= form_authenticity_token %>"/>
Or if you want a jQuery ajax post:
$.ajax({
type: 'POST',
url: "<%= someregistration_path %>",
data: { "firstname": "text_data_1", "last_name": "text_data2", "authenticity_token": "<%= form_authenticity_token %>" },
error: function( xhr ){
alert("ERROR ON SUBMIT");
},
success: function( data ){
//data response can contain what we want here...
console.log("SUCCESS, data="+data);
}
});
'size_t' and 'ptrdiff_t' are required to match your architecture (whatever it is). Therefore, I think rather than using 'int', you should be able to use 'size_t', which on a 64 bit system should be a 64 bit type.
This discussion unsigned int vs size_t goes into a bit more detail.
How to find out what this MySQL Error is trying to say:
#1064 - You have an error in your SQL syntax;
This error has no clues in it. You have to double check all of these items to see where your mistake is:
!@#$%^&*()-_=+[]{}\|;:'",<>/?
select
, into
, or countless others. Take away as much as you can from the broken query until it starts working. And then use PostgreSQL next time that has a sane syntax reporting system.
No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below.
From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.
mvn eclipse:clean
then from eclipse: "Maven Update Project" does the trick!