As RichieHindle pointed out the shortcut for column (block) selection is Alt+Shift+A
. The problem I ran into is that the Android SDK on Eclipse uses 3 shortcuts that all start with Alt+Shift+A
, so if you type that, you'll be given a choice of continuing with D
, S
, or R
.
To solve this I redefined the column selection as Alt+Shift+A,A
(Alt
, Shift
, A
pressed together and then followed by a subsequent A
). To do this go to Windows > Preferences
then type keys
or navigate to General > Keys
. Under the Keys enter the filter text
of block selection
to quickly find the shortcut listing for toggle block selection
. Here you can adjust the shortcut for column selection as you wish.
Yeah that can be quite complicated since the *
is used for many different purposes in C/C++.
If *
appears in front of an already declared variable/function, it means either that:
*
gives access to the value of that variable (if the type of that variable is a pointer type, or overloaded the *
operator).*
has the meaning of the multiply operator, in that case, there has to be another variable to the left of the *
If *
appears in a variable or function declaration it means that that variable is a pointer:
int int_value = 1;
int * int_ptr; //can point to another int variable
int int_array1[10]; //can contain up to 10 int values, basically int_array1 is an pointer as well which points to the first int of the array
//int int_array2[]; //illegal, without initializer list..
int int_array3[] = {1,2,3,4,5}; // these two
int int_array4[5] = {1,2,3,4,5}; // are identical
void func_takes_int_ptr1(int *int_ptr){} // these two are identical
void func_takes_int_ptr2(int int_ptr[]){}// and legal
If &
appears in a variable or function declaration, it generally means that that variable is a reference to a variable of that type.
If &
appears in front of an already declared variable, it returns the address of that variable
Additionally you should know, that when passing an array to a function, you will always have to pass the array size of that array as well, except when the array is something like a 0-terminated cstring (char array).
Another gotcha I recently came across is that in IE 8, "abcd".substr(-1)
erroneously returns "abcd"
, whereas Firefox 3.6 returns "d"
as it should. slice
works correctly on both.
More on this topic can be found here.
I think this is what you want:
/grand/parent/child[@id="#grand"]
For PHPStorm 2020.3.2 on ubuntu inorder to reset expiration license, you should run following commands:
sudo rm ~/.config/JetBrains/PhpStorm2020.3/options/other.xml
sudo rm ~/.config/JetBrains/PhpStorm2020.3/eval/*
sudo rm -rf .java/.userPrefs
I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!
Because time()
and some other functions are builtin
defined in the C library (libc
) itself and GCC always links to libc unless you use the -ffreestanding
compile option. However math functions live in libm
which is not implicitly linked by gcc.
It's as simple as that:
precondition vs postcondition
Now that you know the secret .. use them wisely :)
As @qiao said, you can't use __dirname
in the node repl. However, if you need need this value in the console, you can use path.resolve()
or path.dirname()
. Although, path.dirname()
will just give you a "." so, probably not that helpful. Be sure to require('path')
.
check this..
string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
Array.IndexOf(strArray, "C"); // not found, returns -1
Array.IndexOf(strArray, "CDE"); // found, returns index
Not sure if it was removed before, I heard it was kinda buggy in 0.5.8
but in AS 0.5.9
the settings is there:
Gradle > Global Gradle settings > Offline work
Add overflow: auto;
to the style and the two finger scroll should work.
Could be easier and safer this alternative if you have multiple plots:
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np
cdict = {
'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
'blue' : ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}
cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)
data = 2*( np.sin(X) + np.sin(3*Y) )
data1 = np.clip(data,0,6)
data2 = np.clip(data,-6,0)
vmin = np.min(np.array([data,data1,data2]))
vmax = np.max(np.array([data,data1,data2]))
fig = plt.figure()
ax = fig.add_subplot(131)
mesh = ax.pcolormesh(data, cmap = cm)
mesh.set_clim(vmin,vmax)
ax1 = fig.add_subplot(132)
mesh1 = ax1.pcolormesh(data1, cmap = cm)
mesh1.set_clim(vmin,vmax)
ax2 = fig.add_subplot(133)
mesh2 = ax2.pcolormesh(data2, cmap = cm)
mesh2.set_clim(vmin,vmax)
# Visualizing colorbar part -start
fig.colorbar(mesh,ax=ax)
fig.colorbar(mesh1,ax=ax1)
fig.colorbar(mesh2,ax=ax2)
fig.tight_layout()
# Visualizing colorbar part -end
plt.show()
The best alternative is then to use a single color bar for the entire plot. There are different ways to do that, this tutorial is very useful for understanding the best option. I prefer this solution that you can simply copy and paste instead of the previous visualizing colorbar part of the code.
fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.8,
wspace=0.4, hspace=0.1)
cb_ax = fig.add_axes([0.83, 0.1, 0.02, 0.8])
cbar = fig.colorbar(mesh, cax=cb_ax)
I would suggest using pcolormesh
instead of pcolor
because it is faster (more infos here ).
Another option if you don't have Python 2.6:
import commands
n = commands.getoutput("grep -c processor /proc/cpuinfo")
Just had this problem. For a while I tried the advice about removing the path, git removing the path, removing .gitmodules, removing the entry from .git/config, adding the submodule back, then committing and pushing the change. It was puzzling because it looked like no change when I did "git commit -a" so I tried pushing just the removal, then pushing the readdition to make it look like a change.
After a while I noticed by accident that after removing everything, if I ran "git submodule update --init", it had a message about a specific name that git should no longer have had any reference to: the name of the repository the submodule was linking to, not the path name it was checking it out to. Grepping revealed that this reference was in .git/index. So I ran "git rm --cached repo-name" and then readded the module. When I committed this time, the commit message included a change that it was deleting this unexpected object. After that it works fine.
Not sure what happened, I'm guessing someone misused the git submodule command, maybe reversing the arguments. Could have been me even... Hope this helps someone!
The other answers here work for something like Math, which is a static object. But they don't work for an instance of an object, such as a date. I found the following to work:
function getMethods(o) {
return Object.getOwnPropertyNames(Object.getPrototypeOf(o))
.filter(m => 'function' === typeof o[m])
}
//example: getMethods(new Date()): [ 'getFullYear', 'setMonth', ... ]
https://jsfiddle.net/3xrsead0/
This won't work for something like the original question (Math), so pick your solution based on your needs. I'm posting this here because Google sent me to this question but I was wanting to know how to do this for instances of objects.
In my case my Build Tools version in my build.gradle for the app module was outdated on an old project. Updating it fixed the issue:
android {
...
buildToolsVersion "19.0.1"
...
Updated to the latest build tools version (25.0.1) and sync'd the project and all was well again.
Use this simple code for DataTables custom sorting. Its 100% work
<script>
$(document).ready(function() {
$('#myTable').DataTable( {
"order": [[ 0, "desc" ]] // "0" means First column and "desc" is order type;
} );
} );
</script>
See in Datatables website
https://datatables.net/examples/basic_init/table_sorting.html
In order to remove any URL within a string in Python, you can use this RegEx function :
import re
def remove_URL(text):
"""Remove URLs from a text string"""
return re.sub(r"http\S+", "", text)
You might want to try out Quick JUnit: https://marketplace.eclipse.org/content/quick-junit
The plugin is stable and it allows switching between production and test code. I am currently using Eclipse Mars 4.5 and the plugin is supported for this release as well as for the following:
Luna (4.4), Kepler (4.3), Juno (4.2, 3.8), Previous to Juno (<=4.1)
I believe you can just update your data structure, then:
[tableView beginUpdates];
[tableView deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES];
[tableView insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES];
[tableView endUpdates];
Also, the "withRowAnimation" is not exactly a boolean, but an animation style:
UITableViewRowAnimationFade,
UITableViewRowAnimationRight,
UITableViewRowAnimationLeft,
UITableViewRowAnimationTop,
UITableViewRowAnimationBottom,
UITableViewRowAnimationNone,
UITableViewRowAnimationMiddle
I took a similar approach as Sean3z but instead I have the connection closed everytime i make a query.
His way works if it's only executed on the entry point of your app, but let's say you have controllers that you want to do a var db = require('./db')
. You can't because otherwise everytime you access that controller you will be creating a new connection.
To avoid that, i think it's safer, in my opinion, to open and close the connection everytime.
here is a snippet of my code.
mysq_query.js
// Dependencies
var mysql = require('mysql'),
config = require("../config");
/*
* @sqlConnection
* Creates the connection, makes the query and close it to avoid concurrency conflicts.
*/
var sqlConnection = function sqlConnection(sql, values, next) {
// It means that the values hasnt been passed
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection(config.db);
connection.connect(function(err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
}
});
connection.query(sql, values, function(err) {
connection.end(); // close the connection
if (err) {
throw err;
}
// Execute the callback
next.apply(this, arguments);
});
}
module.exports = sqlConnection;
Than you can use it anywhere just doing like
var mysql_query = require('path/to/your/mysql_query');
mysql_query('SELECT * from your_table where ?', {id: '1'}, function(err, rows) {
console.log(rows);
});
UPDATED: config.json looks like
{
"db": {
"user" : "USERNAME",
"password" : "PASSWORD",
"database" : "DATABASE_NAME",
"socketPath": "/tmp/mysql.sock"
}
}
Hope this helps.
If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.
Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: How to open a local disk file with Javascript?
I will include a slightly modified version for using it in React:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
this.handleFileSelect = this.handleFileSelect.bind(this);
}
displayData(content) {
this.setState({data: content});
}
handleFileSelect(evt) {
let files = evt.target.files;
if (!files.length) {
alert('No file select');
return;
}
let file = files[0];
let that = this;
let reader = new FileReader();
reader.onload = function(e) {
that.displayData(e.target.result);
};
reader.readAsText(file);
}
render() {
const data = this.state.data;
return (
<div>
<input type="file" onChange={this.handleFileSelect}/>
{ data && <p> {data} </p> }
</div>
);
}
}
Well, as most of the answers pointed out, you can include the jQuery file locally as well as use Google's CDN/Microsoft CDN servers. On choosing Google vs. Microsoft CDN go Google_CDN vs. Microsoft_CDN depending on your requirement.
Generally for intranet applications include jQuery file locally and never use the CDN method since for intranet, the LAN is 10x times faster than Internet. For Internet and public facing applications use a hybrid approach as suggested by cowgod elsewhere. Also don't forget to use the nice tool JS_Compressor to compress the extra JavaScript code you add to your jQuery library. It makes JavaScript really fast.
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
This jsPerf test suggests that find() is faster. I created a more thorough test, and it still looks as though find() outperforms children().
Update: As per tvanfosson's comment, I created another test case with 16 levels of nesting. find() is only slower when finding all possible divs, but find() still outperforms children() when selecting the first level of divs.
children() begins to outperform find() when there are over 100 levels of nesting and around 4000+ divs for find() to traverse. It's a rudimentary test case, but I still think that find() is faster than children() in most cases.
I stepped through the jQuery code in Chrome Developer Tools and noticed that children() internally makes calls to sibling(), filter(), and goes through a few more regexes than find() does.
find() and children() fulfill different needs, but in the cases where find() and children() would output the same result, I would recommend using find().
Trying to "transfer an amount larger than my bitcoin balance" is not an unexpected error. You could use Popen.communicate()
directly instead of check_output()
to avoid raising an exception unnecessarily:
from subprocess import Popen, PIPE
p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE)
output = p.communicate()[0]
if p.returncode != 0:
print("bitcoin failed %d %s" % (p.returncode, output))
=====> COMPILATION PROCESS <======
|
|----> Input is Source file(.c)
|
V
+=================+
| |
| C Preprocessor |
| |
+=================+
|
| ---> Pure C file ( comd:cc -E <file.name> )
|
V
+=================+
| |
| Lexical Analyzer|
| |
+-----------------+
| |
| Syntax Analyzer |
| |
+-----------------+
| |
| Semantic Analyze|
| |
+-----------------+
| |
| Pre Optimization|
| |
+-----------------+
| |
| Code generation |
| |
+-----------------+
| |
| Post Optimize |
| |
+=================+
|
|---> Assembly code (comd: cc -S <file.name> )
|
V
+=================+
| |
| Assembler |
| |
+=================+
|
|---> Object file (.obj) (comd: cc -c <file.name>)
|
V
+=================+
| Linker |
| and |
| loader |
+=================+
|
|---> Executable (.Exe/a.out) (com:cc <file.name> )
|
V
Executable file(a.out)
C preprocessing is the first step in the compilation. It handles:
#define
statements.#include
statements.The purpose of the unit is to convert the C source file into Pure C code file.
There are Six steps in the unit :
It combines characters in the source file, to form a "TOKEN". A token is a set of characters that does not have 'space', 'tab' and 'new line'. Therefore this unit of compilation is also called "TOKENIZER". It also removes the comments, generates symbol table and relocation table entries.
This unit check for the syntax in the code. For ex:
{
int a;
int b;
int c;
int d;
d = a + b - c * ;
}
The above code will generate the parse error because the equation is not balanced. This unit checks this internally by generating the parser tree as follows:
=
/ \
d -
/ \
+ *
/ \ / \
a b c ?
Therefore this unit is also called PARSER.
This unit checks the meaning in the statements. For ex:
{
int i;
int *p;
p = i;
-----
-----
-----
}
The above code generates the error "Assignment of incompatible type".
This unit is independent of the CPU, i.e., there are two types of optimization
This unit optimizes the code in following forms:
For ex:
{
int a = 10;
if ( a > 5 ) {
/*
...
*/
} else {
/*
...
*/
}
}
Here, the compiler knows the value of 'a' at compile time, therefore it also knows that the if condition is always true. Hence it eliminates the else part in the code.
For ex:
{
int a, b, c;
int x, y;
/*
...
*/
x = a + b;
y = a + b + c;
/*
...
*/
}
can be optimized as follows:
{
int a, b, c;
int x, y;
/*
...
*/
x = a + b;
y = x + c; // a + b is replaced by x
/*
...
*/
}
For ex:
{
int a;
for (i = 0; i < 1000; i++ ) {
/*
...
*/
a = 10;
/*
...
*/
}
}
In the above code, if 'a' is local and not used in the loop, then it can be optimized as follows:
{
int a;
a = 10;
for (i = 0; i < 1000; i++ ) {
/*
...
*/
}
}
Here, the compiler generates the assembly code so that the more frequently used variables are stored in the registers.
Here the optimization is CPU dependent. Suppose if there are more than one jumps in the code then they are converted to one as:
-----
jmp:<addr1>
<addr1> jmp:<addr2>
-----
-----
The control jumps to the directly.
Then the last phase is Linking (which creates executable or library). When the executable is run, the libraries it requires are Loaded.
If You Need to Replace Strings in Multiple Files:
It should be noted that the different methods posted here can be wildly different with regard to the time it takes to complete. For me, I regularly have large numbers of small files. To test what is most performant, I extracted 5.52 GB (5,933,604,999 bytes) of XML in 40,693 separate files and ran through three of the answers I found here:
## 5.52 GB (5,933,604,999 bytes) of XML files (40,693 files)
#### Test 1 - Plain Replace
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
(Get-Content $xml).replace("'", " ") | Set-Content $xml
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 103.725113128333
#>
#### Test 2 - Replace with -Raw
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
(Get-Content $xml -Raw).replace("'", " ") | Set-Content $xml
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 10.1600227983333
#>
#### Test 3 - .NET, System.IO
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
$txt = [System.IO.File]::ReadAllText("$xml").Replace("'"," ")
[System.IO.File]::WriteAllText("$xml", $txt)
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 5.83619516833333
#>
First, let's clear up some terminology: "asynchronous" (async
) means that it may yield control back to the calling thread before it starts. In an async
method, those "yield" points are await
expressions.
This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".
To futher confuse the issue, async
is very different than "awaitable"; there are some async
methods whose return types are not awaitable, and many methods returning awaitable types that are not async
.
Enough about what they aren't; here's what they are:
async
keyword allows an asynchronous method (that is, it allows await
expressions). async
methods may return Task
, Task<T>
, or (if you must) void
.Task
and Task<T>
.So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run
:
private Task<int> DoWorkAsync() // No async because the method does not need await
{
return Task.Run(() =>
{
return 1 + 2;
});
}
(But this pattern is a poor approach; see below).
But if your question is "how do I create an async
method that can yield back to its caller instead of blocking", the answer is to declare the method async
and use await
for its "yielding" points:
private async Task<int> GetWebPageHtmlSizeAsync()
{
var client = new HttpClient();
var html = await client.GetAsync("http://www.example.com/");
return html.Length;
}
So, the basic pattern of things is to have async
code depend on "awaitables" in its await
expressions. These "awaitables" can be other async
methods or just regular methods returning awaitables. Regular methods returning Task
/Task<T>
can use Task.Run
to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T>
or one of its shortcuts (TaskFactory.FromAsync
, Task.FromResult
, etc). I don't recommend wrapping an entire method in Task.Run
; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run
:
private int DoWork()
{
return 1 + 2;
}
private void MoreSynchronousProcessing()
{
// Execute it directly (synchronously), since we are also a synchronous method.
var result = DoWork();
...
}
private async Task DoVariousThingsFromTheUIThreadAsync()
{
// I have a bunch of async work to do, and I am executed on the UI thread.
var result = await Task.Run(() => DoWork());
...
}
I have an async
/await
intro on my blog; at the end are some good followup resources. The MSDN docs for async
are unusually good, too.
ES6 setTimeout
setTimeout(() => {
console.log("we waited 204586560000 ms to run this code, oh boy wowwoowee!");
}, 204586560000);
Edit: 204586560000 ms is the approximate time between the original question and this answer... assuming I calculated correctly.
I am using MySQL 5.6 on AWS RDS. I updated following in parameter group.
innodb_file_per_table=1
innodb_file_format = Barracuda
I had to reboot DB instance for parameter group changes to be in effect.
Also, ROW_FORMAT=COMPRESSED was not supported. I used DYNAMIC as below and it worked fine.
ALTER TABLE nombre_tabla ENGINE=InnoDB ROW_FORMAT=DYNAMIC KEY_BLOCK_SIZE=8
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
If you are talking about an RCP app, then what you need is the SWT link
widget.
Here is the official link event handler snippet.
Update
Here is minimalist android application to connect to either superuser or stackoverflow with 2 buttons.
package ap.android;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class LinkButtons extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void goToSo (View view) {
goToUrl ( "http://stackoverflow.com/");
}
public void goToSu (View view) {
goToUrl ( "http://superuser.com/");
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
}
And here is the layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/select" />
<Button android:layout_height="wrap_content" android:clickable="true" android:autoLink="web" android:cursorVisible="true" android:layout_width="match_parent" android:id="@+id/button_so" android:text="StackOverflow" android:linksClickable="true" android:onClick="goToSo"></Button>
<Button android:layout_height="wrap_content" android:layout_width="match_parent" android:text="SuperUser" android:autoLink="web" android:clickable="true" android:id="@+id/button_su" android:onClick="goToSu"></Button>
</LinearLayout>
"Does this mean that I should use a custom XML file to save configuration settings?" No, not necessarily. We use SharpConfig for such operations.
For instance, if a configuration file is like that
[General]
# a comment
SomeString = Hello World!
SomeInteger = 10 # an inline comment
We can retrieve values like this
var config = Configuration.LoadFromFile("sample.cfg");
var section = config["General"];
string someString = section["SomeString"].StringValue;
int someInteger = section["SomeInteger"].IntValue;
It is compatible with .NET 2.0 and higher. We can create configuration files on the fly and we can save it later.
Source: http://sharpconfig.net/
GitHub: https://github.com/cemdervis/SharpConfig
Using AddDays(-1)
worked for me until I tried to cross months. When I tried to subtract 2 days from 2017-01-01 the result was 2016-00-30. It could not handle the month change correctly (though the year seemed to be fine).
I used date = Convert.ToDateTime(date).Subtract(TimeSpan.FromDays(2)).ToString("yyyy-mm-dd");
and have no issues.
A good book on MVVM with WPF
Building Enterprise Applications with Windows® Presentation Foundation and the Model View ViewModel
Is your type really arbitrary? If you know it is just going to be a int float or string you could just do
if val.dtype == float and np.isnan(val):
assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN
Try this,
Using foreach
Loop:
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Use it in OnRowCommand
event and get checked CheckBox value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
CREATE Procedure IF NOT EXISTS 'Your proc-name' () BEGIN ... END
They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.
Deleting the .git
folder is probably the easiest path since you don't want/need the history (as Stephan said).
So you can create a new repo from your latest commit: (How to clone seed/kick-start project without the whole history?)
git clone <git_url>
then delete .git
, and afterwards run
git init
Or if you want to reuse your current repo: Make the current commit the only (initial) commit in a Git repository?
Follow the above steps then:
git add .
git commit -m "Initial commit"
Push to your repo.
git remote add origin <github-uri>
git push -u --force origin master
After using git for a long time without problems, I encountered this problem today. After some reflection, I realized I changed my umask
earlier today from 022
to something else.
All the answers by other people are helpful, i.e., do chmod
for the offending directories. But the root cause is my new umask
which will always cause a new problem down the road whenever a new directory is created under .git/object/
. So, the long term solution for me is to change umask
back to 022
.
if you are using RestTemplate than you should use following code to implement timeouts
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(2000);
factory.setConnectTimeout(2000);
return factory;
}}
The xml configuration
<bean class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"
p:readTimeout="2000"
p:connectTimeout="2000" />
</constructor-arg>
Define a module ( call it "globalbaz" ) and have the variables defined inside it. All the modules using this "pseudoglobal" should import the "globalbaz" module, and refer to it using "globalbaz.var_name"
This works regardless of the place of the change, you can change the variable before or after the import. The imported module will use the latest value. (I tested this in a toy example)
For clarification, globalbaz.py looks just like this:
var_name = "my_useful_string"
In my case it works for me after adding this below version dependency(10.2.0.4). After adding this version 10.2.0.3.0 it doesn't work due to .jar file not avail in repository path.
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4</version>
You can try this as well:
from time import perf_counter
t0 = perf_counter()
...
t1 = perf_counter()
time_taken = t1 - t0
I would have thought this would have been answered already - but surely what you want is this: box-shadow: 0 0 3px #CC0000;
Example: http://jsfiddle.net/vmzLW/
here is java O(nlogn) implementation
import java.util.Scanner;
public class LongestIncreasingSeq {
private static int binarySearch(int table[],int a,int len){
int end = len-1;
int beg = 0;
int mid = 0;
int result = -1;
while(beg <= end){
mid = (end + beg) / 2;
if(table[mid] < a){
beg=mid+1;
result = mid;
}else if(table[mid] == a){
return len-1;
}else{
end = mid-1;
}
}
return result;
}
public static void main(String[] args) {
// int[] t = {1, 2, 5,9,16};
// System.out.println(binarySearch(t , 9, 5));
Scanner in = new Scanner(System.in);
int size = in.nextInt();//4;
int A[] = new int[size];
int table[] = new int[A.length];
int k = 0;
while(k<size){
A[k++] = in.nextInt();
if(k<size-1)
in.nextLine();
}
table[0] = A[0];
int len = 1;
for (int i = 1; i < A.length; i++) {
if(table[0] > A[i]){
table[0] = A[i];
}else if(table[len-1]<A[i]){
table[len++]=A[i];
}else{
table[binarySearch(table, A[i],len)+1] = A[i];
}
}
System.out.println(len);
}
}
//TreeSet can be used
Here is simple code snippet working for AES Encryption and Decryption.
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryptionClass {
private static String INIT_VECTOR_PARAM = "#####";
private static String PASSWORD = "#####";
private static String SALT_KEY = "#####";
private static SecretKeySpec generateAESKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
// Prepare password and salt key.
char[] password = new String(Base64.decode(PASSWORD, Base64.DEFAULT)).toCharArray();
byte[] salt = new String(Base64.decode(SALT_KEY, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);
// Create object of [Password Based Encryption Key Specification] with required iteration count and key length.
KeySpec spec = new PBEKeySpec(password, salt, 64, 256);
// Now create AES Key using required hashing algorithm.
SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
// Get encoded bytes of secret key.
byte[] bytesSecretKey = key.getEncoded();
// Create specification for AES Key.
SecretKeySpec secretKeySpec = new SecretKeySpec(bytesSecretKey, "AES");
return secretKeySpec;
}
/**
* Call this method to encrypt the readable plain text and get Base64 of encrypted bytes.
*/
public static String encryptMessage(String message) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {
byte[] initVectorParamBytes = new String(Base64.decode(INIT_VECTOR_PARAM, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);
Cipher encryptionCipherBlock = Cipher.getInstance("AES/CBC/PKCS5Padding");
encryptionCipherBlock.init(Cipher.ENCRYPT_MODE, generateAESKey(), new IvParameterSpec(initVectorParamBytes));
byte[] messageBytes = message.getBytes();
byte[] cipherTextBytes = encryptionCipherBlock.doFinal(messageBytes);
String encryptedText = Base64.encodeToString(cipherTextBytes, Base64.DEFAULT);
return encryptedText;
}
/**
* Call this method to decrypt the Base64 of encrypted message and get readable plain text.
*/
public static String decryptMessage(String base64Cipher) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {
byte[] initVectorParamBytes = new String(Base64.decode(INIT_VECTOR_PARAM, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);
Cipher decryptionCipherBlock = Cipher.getInstance("AES/CBC/PKCS5Padding");
decryptionCipherBlock.init(Cipher.DECRYPT_MODE, generateAESKey(), new IvParameterSpec(initVectorParamBytes));
byte[] cipherBytes = Base64.decode(base64Cipher, Base64.DEFAULT);
byte[] messageBytes = decryptionCipherBlock.doFinal(cipherBytes);
String plainText = new String(messageBytes);
return plainText;
}
}
Now, call
encryptMessage()
ordecryptMessage()
for desiredAES
Operation with required parameters.Also, handle the exceptions during
AES
operations.
Hope it helped...
In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:
I had to restart the browser after changing the ip address (laptop wireless DHCP) which was my "cross-host" I was referring to in my web app, which resolved the issue.
Also make sure all the cors headers being added by your browser/host are accepted/allowed by including then in the cors.allowed.headers
You can use the pattern
attribute. The required
attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.
<input pattern=".{3,}" required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">
If you want to create the option to use the pattern for "empty, or minimum length", you could do the following:
<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}" required title="Either 0 OR (8 chars minimum)">
Have you noticed that you don't get the error if you run
python ./script.py
instead of
python script.py
This is because sys.argv[0]
will read ./script.py
in the former case, which gives os.path.dirname
something to work with. When you don't specify a path, sys.argv[0]
reads simply script.py
, and os.path.dirname
cannot determine a path.
In order to show the icon, use getSupportActionBar().setIcon(R.xxx.xxx)
In my case the code is:-
getSupportActionBar().setIcon (R.mipmap.ic_launcher);
Piping to another process (Although this WON'T accomplish what you said you are trying to do):
command1 | command2
This will send the output of command1 as the input of command2
-exec
on a find
(this will do what you are wanting to do -- but is specific to find
)
find . -name '*.foo' -exec cat {} \;
(Everything between find
and -exec
are the find predicates you were already using. {}
will substitute the particular file you found into the command (cat {}
in this case); the \;
is to end the -exec
command.)
send output of one process as command line arguments to another process
command2 `command1`
for example:
cat `find . -name '*.foo' -print`
(Note these are BACK-QUOTES not regular quotes (under the tilde ~ on my keyboard).)
This will send the output of command1
into command2
as command line arguments. Note that file names containing spaces (newlines, etc) will be broken into separate arguments, though.
Enter the date as a native value 'yyyymmdd'
to avoid regional issues:
select cast('17530101' as datetime)
Yes, it would be great if TSQL had MinDate() = '00010101'
, but no such luck.
Object doesn't support this property or method.
Think of it like if anything after the dot is called on an object. It's like a chain.
An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot .
you get intelli-sense (that white dropdown) trying to help you pick the correct action.
(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)
Type this much anywhere in your code area
Dim a As Worksheets
a.
you get help from VBE, it's a little dropdown called Intelli-sense
It lists all available actions that particular object exposes to any user. You can't see the .Selection
member of the Worksheets()
class. That's what the error tells you exactly.
Object doesn't support this property or method.
If you look at the example on MSDN
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
It activates
the sheet first then calls the Selection...
it's not connected together because Selection
is not a member of Worksheets()
class. Simply, you can't prefix the Selection
What about
Sub DisplayColumnCount()
Dim iAreaCount As Integer
Dim i As Integer
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
If iAreaCount <= 1 Then
MsgBox "The selection contains " & Selection.Columns.Count & " columns."
Else
For i = 1 To iAreaCount
MsgBox "Area " & i & " of the selection contains " & _
Selection.Areas(i).Columns.Count & " columns."
Next i
End If
End Sub
from HERE
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
Be aware that a lot of the really killer features are only in Enterprise Edition. Data compression and backup compression are among two of my top favorites - they give you free performance improvements right off the bat. Data compression lessens the amount of I/O you have to do, so a lot of queries speed up 20-40%. CPU use goes up, but in today's multi-core environments, we often have more CPU power but not more IO. Anyway, those are only in Enterprise.
If you're only going to use Standard Edition, then most of the improvements require changes to your application code and T-SQL code, so it's not quite as easy of a sell.
I don't think you need/want the timeout.
onhover (hover) would be defined as the time period while "over" something. IMHO
onmouseover = start...
onmouseout = ...end
For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.
There is a way by saying what is is not. Just make the not something it never will be. A good css selector reference: https://www.w3schools.com/cssref/css_selectors.asp which shows the :not selector as follows:
:not(selector) :not(p) Selects every element that is not a <p> element
Here is an example: a div followed by something (anything but a z tag)
div > :not(z){
border:1px solid pink;
}
I think this is enough to get you on a nice path:
Sub a()
Dim btn As Button
Application.ScreenUpdating = False
ActiveSheet.Buttons.Delete
Dim t As Range
For i = 2 To 6 Step 2
Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "btnS"
.Caption = "Btn " & i
.Name = "Btn" & i
End With
Next i
Application.ScreenUpdating = True
End Sub
Sub btnS()
MsgBox Application.Caller
End Sub
It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.
For me it was solved instantly by the following
find the following lines by cont+f:
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
AllowOverride AuthConfig
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
only change local ----> all granted, so it becomes like this
Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
<Directory "C:/xampp/phpMyAdmin">
AllowOverride AuthConfig
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
After this the localhost will stop showing the error and will show admin panel. I found this solution in a video here: https://www.youtube.com/watch?v=MvYyEPaNNhE
If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src
attribute.
$("#myiframe").attr("src", "newwebpage.html");
Maybe you have to try getActivity().getSupportActionBar().setTitle()
if you are using support_v7.
You did not mention what the command was that you were trying to run that produced the error message. However, the bottom line problem is that you are trying to run and/or install 32-bit (i686) packages on a 64-bit (x86_64) system which is not a good idea. For example, if you were trying to run the 32-bit version of Perl on a 64-bit system, the result would be something like
perl: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory
If you still want to use the rpm command to install the 32-bit versions of glibc and glibc-common on your system, then you need to know that you must install both of the packages at the same time and as a single command because they are dependencies of each other. The command to run in your case would be:
rpm -Uvh glibc-2.12-1.80.el6.i686.rpm glibc-common-2.12-1.80.el6.i686.rpm
I'm think this has been answered before...but anyway, if you want to encrypt/decrypt data, you can't use SHA256
//Key
$key = 'SuperSecretKey';
//To Encrypt:
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, 'I want to encrypt this', MCRYPT_MODE_ECB);
//To Decrypt:
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB);
In chrome lastest. Add following css it auto hide address bar (URL bar) when scroll!
html { height: 100vh; }
body { height: 100%; }
And this is why: https://developers.google.com/web/updates/2016/12/url-bar-resizing
Hope to helpful!
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
Note that the NIB file doesn't wire up all the IBOutlets until the view has been added to the scene. If you're wiring things up manually (which you might be doing if things are in separate NIBs) this is important to keep in mind.
So if my test view controller has an "imageView" wired by a nib, this probably won't work:
testCardViewController.imageView.image = [UIImage imageNamed:@"EmptyCard.png"];
[self.view addSubview:testCardViewController.view];
But this will:
[self.view addSubview:testCardViewController.view];
testCardViewController.imageView.image = [UIImage imageNamed:@"EmptyCard.png"];
As best coding practices suggests, use setTimeout
instead of setInterval
.
function foo() {
// your function code here
setTimeout(foo, 5000);
}
foo();
Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout
function that will be later call the same function again.
Try this
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custom_actionbar, menu);
menu.setGroupVisible(...);
}
If you have an embedded navigation controller created via Interface Builder, be sure to set the following in a class that manages your navigation controller:
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
That should be all you need.
If I understand your question correctly, you are looking for innerHTML
:
alert(col.firstChild.innerHTML);
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<h4 align="center">
<a href="Demo2.html">Center</a>
</h4>
</body>
</html>
You could try using a casting operator to convert it to an integer:
$page = (int) $_GET['p'];
if($page == "")
{
$page = 1;
}
if(empty($page) || !$page)
{
setcookie("error", "Invalid page.", time()+3600);
header("location:somethingwentwrong.php");
die();
}
//else continue with code
Here is how you push a register. I assume we are talking about x86.
push ebx
push eax
It is pushed on stack. The value of ESP
register is decremented to size of pushed value as stack grows downwards in x86 systems.
It is needed to preserve the values. The general usage is
push eax ; preserve the value of eax
call some_method ; some method is called which will put return value in eax
mov edx, eax ; move the return value to edx
pop eax ; restore original eax
A push
is a single instruction in x86, which does two things internally.
ESP
register by the size of pushed value.ESP
register.Please follow the steps below to install sshpass
in mac.
curl -O -L https://fossies.org/linux/privat/sshpass-1.06.tar.gz && tar xvzf sshpass-1.06.tar.gz
cd sshpass-1.06
./configure
sudo make install
Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:
var http = require('http')
var fs = require('fs')
fs.readFile('image.jpg', function(err, data) {
if (err) throw err // Fail if the file can't be read.
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.end(data) // Send the file data to the browser.
}).listen(8124)
console.log('Server running at http://localhost:8124/')
})
Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg
.
[Edit] You could even embed the image in an HTML page directly by using an <img>
with a data URI source. For example:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body><img src="data:image/jpeg;base64,')
res.write(Buffer.from(data).toString('base64'));
res.end('"/></body></html>');
Maybe I am missing something, but it seems like most of these solutions overcomplicate things and do away with secure practices.
This method does not violate the MVVM pattern and maintains complete security. Yes, technically it is code behind, but it is nothing more than a "special case" binding. The ViewModel still has no knowledge of the View implementation, which in my mind it does if you are trying to pass the PasswordBox in to the ViewModel.
Code Behind != Automatic MVVM violation. It all depends on what you do with it. In this case, we are just manually coding a binding, so its all considered part of the UI implementation and therefore is ok.
In the ViewModel, just a simple property. I made it "write only" since there shouldn't be a need to retrieve it from outside the ViewModel for any reason, but it doesn't have to be. Note that it is a SecureString, not just a string.
public SecureString SecurePassword { private get; set; }
In the xaml, you set up a PasswordChanged event handler.
<PasswordBox PasswordChanged="PasswordBox_PasswordChanged"/>
In the code behind:
private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
if (this.DataContext != null)
{ ((dynamic)this.DataContext).SecurePassword = ((PasswordBox)sender).SecurePassword; }
}
With this method, your password remains in a SecureString at all times and therefore provides maximum security. If you really don't care about security or you need the clear text password for a downstream method that requires it (note: most .NET methods that require a password also support a SecureString option, so you may not really need a clear text password even if you think you do), you can just use the Password property instead. Like this:
(ViewModel property)
public string Password { private get; set; }
(Code behind)
private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
if (this.DataContext != null)
{ ((dynamic)this.DataContext).Password = ((PasswordBox)sender).Password; }
}
If you wanted to keep things strongly typed, you could substitute the (dynamic) cast with the interface of your ViewModel. But really, "normal" data bindings aren't strongly typed either, so its not that big a deal.
private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
if (this.DataContext != null)
{ ((IMyViewModel)this.DataContext).Password = ((PasswordBox)sender).Password; }
}
So best of all worlds - your password is secure, your ViewModel just has a property like any other property, and your View is self contained with no external references required.
Check the ExcelPackage project, it uses the Office Open XML file format of Excel 2007, it's lightweight and open source...
You can use IN operator as below
select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)
I had similar requirement of running a LAMP stack, Mongo DB and my own services
Docker is OS based virtualisation, which is why it isolates its container around a running process, hence it requires least one process running in FOREGROUND.
So you provide your own startup script as the entry point, thus your startup script becomes an extended Docker image script, in which you can stack any number of the services as far as AT LEAST ONE FOREGROUND SERVICE IS STARTED, WHICH TOO TOWARDS THE END
So my Docker image file has two line below in the very end:
COPY myStartupScript.sh /usr/local/myscripts/myStartupScript.sh
CMD ["/bin/bash", "/usr/local/myscripts/myStartupScript.sh"]
In my script I run all MySQL, MongoDB, Tomcat etc. In the end I run my Apache as a foreground thread.
source /etc/apache2/envvars
/usr/sbin/apache2 -DFOREGROUND
This enables me to start all my services and keep the container alive with the last service started being in the foreground
Hope it helps
UPDATE: Since I last answered this question, new things have come up like Docker compose, which can help you run each service on its own container, yet bind all of them together as dependencies among those services, try knowing more about docker-compose and use it, it is more elegant way unless your need does not match with it.
>>> a=range(1,10)
>>> for i in [2,3,7]: a.remove(i)
...
>>> a
[1, 4, 5, 6, 8, 9]
>>> a=range(1,10)
>>> b=map(a.remove,[2,3,7])
>>> a
[1, 4, 5, 6, 8, 9]
Here's a snippet of the HTML escape characters taken from a cached page on archive.org:
< | < less than sign
@ | @ at sign
] | ] right bracket
{ | { left curly brace
} | } right curly brace
… | … ellipsis
‡ | ‡ double dagger
’ | ’ right single quote
” | ” right double quote
– | – short dash
™ | ™ trademark
¢ | ¢ cent sign
¥ | ¥ yen sign
© | © copyright sign
¬ | ¬ logical not sign
° | ° degree sign
² | ² superscript 2
¹ | ¹ superscript 1
¼ | ¼ fraction 1/4
¾ | ¾ fraction 3/4
÷ | ÷ division sign
” | ” right double quote
> | > greater than sign
[ | [ left bracket
` | ` back apostrophe
| | | vertical bar
~ | ~ tilde
† | † dagger
‘ | ‘ left single quote
“ | “ left double quote
• | • bullet
— | — longer dash
¡ | ¡ inverted exclamation point
£ | £ pound sign
¦ | ¦ broken vertical bar
« | « double left than sign
® | ® registered trademark sign
± | ± plus or minus sign
³ | ³ superscript 3
» | » double greater-than sign
½ | ½ fraction 1/2
¿ | ¿ inverted question mark
“ | “ left double quote
— | — dash
Another way to use OVER is to have a result column in your select operate on another "partition", so to say.
This:
SELECT
name,
ssn,
case
when ( count(*) over (partition by ssn) ) > 1
then 1
else 0
end AS hasDuplicateSsn
FROM table;
returns 1 in hasDuplicateSsn for each row whose ssn is shared by another row. Great for making "tags" for data for different error reports and such.
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
This worked for me better:
$('.resiText').on('keyup input', function() { _x000D_
$(this).css('height', 'auto').css('height', this.scrollHeight + (this.offsetHeight - this.clientHeight));_x000D_
});
_x000D_
.resiText {_x000D_
box-sizing: border-box;_x000D_
resize: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="resiText"></textarea>
_x000D_
You can do that using the thenAnswer
method (when chaining with when
):
when(someMock.someMethod()).thenAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
});
Or using the equivalent, static doAnswer
method:
doAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
}).when(someMock).someMethod();
'M' (Capital) represent month & 'm' (Simple) represent minutes
Some example for months
'M' -> 7 (without prefix 0 if it is single digit)
'M' -> 12
'MM' -> 07 (with prefix 0 if it is single digit)
'MM' -> 12
'MMM' -> Jul (display with 3 character)
'MMMM' -> December (display with full name)
Some example for minutes
'm' -> 3 (without prefix 0 if it is single digit)
'm' -> 19
'mm' -> 03 (with prefix 0 if it is single digit)
'mm' -> 19
The problem is the OS can’t find Pip. Pip helps you install packages MODIFIED SOME GREAT ANSWERS TO BE BETTER
cd C:\Users\Username\AppData\Local\Programs\Python\Python37-32
In this directory, search pip with python -m pip then install package
python -m pip install ipywidgets
-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.
GO TO scripts from CMD. This is where Pip stays :)
cd C:\Users\User name\AppData\Local\Programs\Python\Python37-32\Scripts>
Then
pip install anypackage
One option could be converting DateTime to ToUniversalTime() before converting to string using "o" format. For example,
var dt = DateTime.Now.ToUniversalTime();
Console.WriteLine(dt.ToString("o"));
It will output:
2016-01-31T20:16:01.9092348Z
This error is currently being fixed: https://chromium-review.googlesource.com/c/chromium/src/+/2001234
But it helped me, changing nginx settings:
In my case, Nginx acts as a reverse proxy for Node.js application.
I was having this problem when running from c#, on Windows 7, the "Interactive Services Detection" service was popping up when running a hidden powershell window as the SYSTEM account.
Using the "CreateNoWindow" parameter prevented the ISD service popping up it's warning.
process.StartInfo = new ProcessStartInfo("powershell.exe",
String.Format(@" -NoProfile -ExecutionPolicy unrestricted -encodedCommand ""{0}""",encodedCommand))
{
WorkingDirectory = executablePath,
UseShellExecute = false,
CreateNoWindow = true
};
Since this setting is not an attribute
It is an attribute.
Some attributes are defined as boolean, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled", you include only the bold part. In HTML 4, you should include only the bold part as the full version is marked as a feature with limited support (although that is less true now then when the spec was written).
As of HTML 5, the rules have changed and now you include only the name and not the value. This makes no practical difference because the name and the value are the same.
The DOM property is also called disabled
and is a boolean that takes true
or false
.
foo.disabled = true;
In theory you can also foo.setAttribute('disabled', 'disabled');
and foo.removeAttribute("disabled")
, but I wouldn't trust this with older versions of Internet Explorer (which are notoriously buggy when it comes to setAttribute
).
You could try using something like:
sed -n 's/$/:80/' ips.txt > new-ips.txt
Provided that your file format is just as you have described in your question.
The s///
substitution command matches (finds) the end of each line in your file (using the $
character) and then appends (replaces) the :80
to the end of each line. The ips.txt
file is your input file... and new-ips.txt
is your newly-created file (the final result of your changes.)
Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:
sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt
So, for example, if your input file looked something like this (note the :80
):
127.0.0.1
128.0.0.0:80
121.121.33.111
The final result would look something like this:
127.0.0.1:80
128.0.0.0:80
121.121.33.111:80
Use jquery cookie https://github.com/carhartl/jquery-cookie and then you can be sure the class will stay on page refresh.
Stores the id of the clicked element in the cookie and then uses that to add the class on refresh.
//Get cookie value and set active
var tab = $.cookie('active');
$('#' + tab).addClass('active');
//Set cookie active tab value on click
//Done this way to preserve after page refresh
$('.topTab').click(function (event) {
var clickedTab = event.target.id;
$.removeCookie('active', { path: '/' });
$( '.active' ).removeClass( 'active' );
$.cookie('active', clickedTab, { path: '/' });
});
You probably aborted a clearcache halfway and now you already have an app/cache/dev_old.
Try this (in the root of your project, assuming you're on a Unixy environment like OS X or Linux):
rm -rf app/cache/dev*
Get rid of the semicolon after WordGame
.
You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.
res.json
forces the argument to JSON. res.send
will take an non-json object or non-json array and send another type. For example:
This will return a JSON number.
res.json(100)
This will return a status code and issue a warning to use sendStatus.
res.send(100)
If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json
.
Java 1.6.0_24:
public static File[] getPackageContent(String packageName) throws IOException{
ArrayList<File> list = new ArrayList<File>();
Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
.getResources(packageName);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
File dir = new File(url.getFile());
for (File f : dir.listFiles()) {
list.add(f);
}
}
return list.toArray(new File[]{});
}
This solution was tested within the EJB environment.
ALTER TABLE old_table_name RENAME new_table_name;
or
RENAME TABLE old_table_name TO new_table_name;
For all the pythonian zealots out there I'm sure Johan Cleeze would approve of your dogmatism ;). I'm leaving this answer keep demeriting it It actually makes me more confidant. Leave a comment you chickens!
For python 3.6
class SomeClass:
def attr_list1(self, should_print=False):
for k in self.__dict__.keys():
v = self.__dict__.__getitem__(k)
if should_print:
print(f"attr: {k} value: {v}")
def attr_list(self, should_print=False):
b = [(k, v) for k, v in self.__dict__.items()]
if should_print:
[print(f"attr: {a[0]} value: {a[1]}") for a in b]
return b
In my case, the 'page.dt' event did not do the trick.
I used 'draw.dt' event instead, and it works!, some code:
$(document).on('draw.dt', function () {
//Do something
});
'Draw.dt' event is fired everytime the datatable page change by searching, ordering or page changing.
/***** Aditional Info *****/
There are some diferences in the way we can declare the event listener. You can asign it to the 'document' or to a 'html object'. The 'document' listeners will always exist in the page and the 'html object' listener will exist only if the object exist in the DOM in the moment of the declaration. Some code:
//Document event listener
$(document).on('draw.dt', function () {
//This will also work with objects loaded by ajax calls
});
//HTML object event listener
$("#some-id").on('draw.dt', function () {
//This will work with existing objects only
});
If you do not want variables to be replaced, you need to surround EOL with single quotes.
cat >/tmp/myconfig.conf <<'EOL'
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
EOL
Previous example:
$ cat /tmp/myconfig.conf
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
if you are on Windows
sqlplus / as sysdba
Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.
Thanks, I didn't have the idea of an UPDATE with INNER JOIN.
In the original query, the mistake was to name the subquery, which must return a value and can't therefore be aliased.
UPDATE Competition
SET Competition.NumberOfTeams =
(SELECT count(*) -- no column alias
FROM PicksPoints
WHERE UserCompetitionID is not NULL
-- put the join condition INSIDE the subquery :
AND CompetitionID = Competition.CompetitionID
group by CompetitionID
) -- no table alias
should do the trick for every record of Competition.
To be noticed :
The effect is NOT EXACTLY the same as the query proposed by mellamokb, which won't update Competition records with no corresponding PickPoints.
Since SELECT id, COUNT(*) GROUP BY id
will only count for existing values of ids,
whereas a SELECT COUNT(*)
will always return a value, being 0 if no records are selected.
This may, or may not, be a problem for you.
0-aware version of mellamokb query would be :
Update Competition as C
LEFT join (
select CompetitionId, count(*) as NumberOfTeams
from PicksPoints as p
where UserCompetitionID is not NULL
group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = IFNULL(A.NumberOfTeams, 0)
In other words, if no corresponding PickPoints are found, set Competition.NumberOfTeams to zero.
The clearest way in my view is to use TimeSpan.FromTicks and then convert that to minutes:
TimeSpan ts = TimeSpan.FromTicks(ticks);
double minutes = ts.TotalMinutes;
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
This works for me.
if(code ==112) {
alert("F1 was pressed!!");
return false;
}
F2 - 113, F3 - 114, F4 - 115, and so fort.
To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do n / i
, and this will cover the whole problem space.
As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.
Python code:
import math
def divisorGenerator(n):
large_divisors = []
for i in xrange(1, int(math.sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n:
large_divisors.append(n / i)
for divisor in reversed(large_divisors):
yield divisor
print list(divisorGenerator(100))
Which should output a list like:
[1, 2, 4, 5, 10, 20, 25, 50, 100]
A possibly simpler alternative to editing the ssh config file (as suggested in all other answers), is to configure an individual repository to use a different (e.g. non-default) ssh key.
Inside the repository for which you want to use a different key, run:
git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_anotheraccount'
If your key is passhprase-protected and you don't want to type your password every time, you have to add it to the ssh-agent. Here's how to do it for ubuntu and here for macOS.
It should also be possible to scale this approach to multiple repositories using global git config and conditional includes (see example).
EDIT ouch, too late... I know read your comment stating that you want to keep the feature-x changeset around, so the cloning approach here doesn't work.
I'll still let the answer here for it may help others.
If you want to completely get rid of "feature X", because, for example, it didn't work, you can clone. This is one of the method explained in the article and it does work, and it talks specifically about heads.
As far as I understand you have this and want to get rid of the "feature-x" head once and for all:
@ changeset: 7:00a7f69c8335
|\ tag: tip
| | parent: 4:31b6f976956b
| | parent: 2:0a834fa43688
| | summary: merge
| |
| | o changeset: 5:013a3e954cfd
| |/ summary: Closed branch feature-x
| |
| o changeset: 4:31b6f976956b
| | summary: Changeset2
| |
| o changeset: 3:5cb34be9e777
| | parent: 1:1cc843e7f4b5
| | summary: Changeset 1
| |
o | changeset: 2:0a834fa43688
|/ summary: Changeset C
|
o changeset: 1:1cc843e7f4b5
| summary: Changeset B
|
o changeset: 0:a9afb25eaede
summary: Changeset A
So you do this:
hg clone . ../cleanedrepo --rev 7
And you'll have the following, and you'll see that feature-x is indeed gone:
@ changeset: 5:00a7f69c8335
|\ tag: tip
| | parent: 4:31b6f976956b
| | parent: 2:0a834fa43688
| | summary: merge
| |
| o changeset: 4:31b6f976956b
| | summary: Changeset2
| |
| o changeset: 3:5cb34be9e777
| | parent: 1:1cc843e7f4b5
| | summary: Changeset 1
| |
o | changeset: 2:0a834fa43688
|/ summary: Changeset C
|
o changeset: 1:1cc843e7f4b5
| summary: Changeset B
|
o changeset: 0:a9afb25eaede
summary: Changeset A
I may have misunderstood what you wanted but please don't mod down, I took time reproducing your use case : )
// This is for first date
first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((first.getTime())/1000); // get the actual epoch values
second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((second.getTime())/1000); // get the actual epoch values
diff= second - first ;
one_day_epoch = 24*60*60 ; // calculating one epoch
if ( diff/ one_day_epoch > 365 ) // check , is it exceei
{
alert( 'date is exceeding one year');
}
All you need is to Stop the ASP.NET Development Server and run the project again
What about normal encoded white-space character?
 
% draw simple vector from pt a to pt b
% wtr : with respect to
scale=0;%for drawin vectors with true scale
a = [10 20 30];% wrt origine O(0,0,0)
b = [10 10 20];% wrt origine O(0,0,0)
starts=a;% a now is the origine of my vector to draw (from a to b) so we made a translation from point O to point a = to vector a
c = b-a;% c is the new coordinates of b wrt origine a
ends=c;%
plot3(a(1),a(2),a(3),'*b')
hold on
plot3(b(1),b(2),b(3),'*g')
quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3),scale);% Use scale = 0 to plot the vectors without the automatic scaling.
% axis equal
hold off
I prefer this Amazon AWS endpoint:
import requests
ip = requests.get('https://checkip.amazonaws.com').text.strip()
I used to work with Klassmaster in my previous company and it works really well and can integrate pretty good with build systems (maven support is excellent). But it's not free though.
On Windows 7 64-bit, I added the registry entry using the following script:
@echo off
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Description" /t REG_SZ /d "Oracle Next Generation Java Plug-In"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "GeckoVersion" /t REG_SZ /d "1.9"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Path" /t REG_SZ /d "C:\Oracle\jdev11123\jdk160_24\jre\bin\new_plugin\npjp2.dll"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "ProductName" /t REG_SZ /d "Oracle Java Plug-In"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Vendor" /t REG_SZ /d "Oracle Corp."
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Version" /t REG_SZ /d "10.3.1"
Note that you will have to change the Path
.
You can also use &
, |
(and/or) for more flexibility:
values between 5 and 10: A[(A>5)&(A<10)]
values greater than 10 or smaller than 5: A[(A<5)|(A>10)]
I use
function windowHasScroll()
{
return document.body.clientHeight > document.documentElement.clientHeight;
}
The string is basically bounded from the place where it is pointed to (char *ptrChar;
), to the null character (\0
).
The char *ptrChar;
actually points to the beginning of the string (char array), and thus that is the pointer to that string,
so when you do like ptrChar[x]
for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).
Just go to start > type search box uac
press enter > you will see 'Change user account control settings' > down the you will see never notify. Click on OK. And you are done.
Reset: "\x1b[0m"
Bright: "\x1b[1m"
Dim: "\x1b[2m"
Underscore: "\x1b[4m"
Blink: "\x1b[5m"
Reverse: "\x1b[7m"
Hidden: "\x1b[8m"
FgBlack: "\x1b[30m"
FgRed: "\x1b[31m"
FgGreen: "\x1b[32m"
FgYellow: "\x1b[33m"
FgBlue: "\x1b[34m"
FgMagenta: "\x1b[35m"
FgCyan: "\x1b[36m"
FgWhite: "\x1b[37m"
BgBlack: "\x1b[40m"
BgRed: "\x1b[41m"
BgGreen: "\x1b[42m"
BgYellow: "\x1b[43m"
BgBlue: "\x1b[44m"
BgMagenta: "\x1b[45m"
BgCyan: "\x1b[46m"
BgWhite: "\x1b[47m"
For example if you want to have a Dim, Red text with Blue background you can do it in Javascript like this:
console.log("\x1b[2m", "\x1b[31m", "\x1b[44m", "Sample Text", "\x1b[0m");
The order of the colors and effects seems to not be that important but always remember to reset the colors and effects at the end.
The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.
plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) ) )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
}
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
My solution: remove some init options (ex. show), because constructor doesnt yield if something is not working (ex slide effect). My function without dynamic html insertion:
function ySearch(){ console.log('ysearch');
$( "#aaa" ).dialog({autoOpen: true,closeOnEscape: true, dialogClass: "ysearch-dialog",modal: false,height: 510, width:860
});
$('#aaa').dialog("open");
console.log($('#aaa').dialog("isOpen"));
return false;
}
The exception probably comes from the parseDouble() calls. Check that the values given to that function really reflect a double.
phpMyAdmin can handle CSV import. Here are the steps:
Prepare the CSV file to have the fields in the same order as the MySQL table fields.
Remove the header row from the CSV (if any), so that only the data is in the file.
Go to the phpMyAdmin interface.
Select the table in the left menu.
Click the import button at the top.
Browse to the CSV file.
Select the option "CSV using LOAD DATA".
Enter "," in the "fields terminated by".
Enter the column names in the same order as they are in the database table.
Click the go button and you are done.
This is a note that I prepared for my future use, and sharing here if someone else can benefit.
For what it is worth I came to this page because I had the same problem. I never got anywhere except some IMAP stuff that I don't understand. Then I remembered I had uninstalled privoxy on my ubuntu (because of some weird runtime error that mentioned 127.0.0.1:8118 when I used Daniel Kehoe's Rails template, https://github.com/RailsApps/rails3-application-templates [never discovered what it was]) and I hadn't changed my terminal to the state of no system wide proxy, under network proxy.
I know this may not be on-point but if I wound up here maybe other privoxy users can benefit too.
Essentially it means you don't have the index you are trying to reference. For example:
df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)
will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:
df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)
Hope that answers your question!
Option 1 and 2 involves using inner class that will make the code kind of clutter. Option 2 is sort of messy because there will be one listener for every button. If you have small number of button, this is okay. For option 4 I think this will be harder to debug as you will have to go back and fourth the xml and java code. I personally use option 3 when I have to handle multiple button clicks.
The main()
method is the entry point for a Java application. run()
is typically used for new threads or tasks.
Where have you been writing a run()
method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
Solved..! September 5, 2020.
It is working very well. In this way, you do not need to have permission from user. You can open directly phone calling part.
Trick point, use ACTION_DIAL instead of ACTION_CALL.
private void callPhoneNumber() {
String phone = "03131693169";
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + phone));
startActivity(callIntent);
}
For more question, ask me on Instagram: @canerkaseler
From Sort an array of associative arrays by value of given key in php:
by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order. Example :
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);
Output:
Array
(
[0] => Array
(
[price] => 200.0
[product] => test3
)
[1] => Array
(
[price] => 1000.50
[product] => test1
)
[2] => Array
(
[price] => 8800.50
[product] => test2
)
)
Here are the outputs of isset()
and empty()
for the 4 possibilities: undeclared, null, false and true.
$a=null;
$b=false;
$c=true;
var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared
//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) }
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) }
You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false
. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset
and false when tested by 'empty'.
So use isset()
when you're concerned about the existence of a variable. And use empty
when you're testing for true or false. If the actual type of emptiness matters, use is_null
and ===0
, ===false
, ===''
.
What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.
If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.
EDIT
I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.
It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc()
call, etc.) so those warnings would not be very useful due to the false positive frequency.
for x in reversed(whatever):
do_something()
This works on basically everything that has a defined order, including xrange
objects and lists.
Read and remember each line
Identify the one you want to get rid of
Forget that one
Write the rest back over the top of the file
import os
zip_file_path = "C:\AA\BB"
file_list = os.listdir(path)
abs_path = []
for a in file_list:
x = zip_file_path+'\\'+a
print x
abs_path.append(x)
for f in abs_path:
zip=zipfile.ZipFile(f)
zip.extractall(zip_file_path)
This does not contain validation for the file if its not zip. If the folder contains non .zip file it will fail.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "EmpExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdByExcel.DataSource = dss.Tables[0].DefaultView;
grdByExcel.DataBind();
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdByExcel.DataSource = null;
grdByExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
Graphviz is evidently included in Anaconda so as to be used with pydot or pydot-ng (both of which are included in Anaconda). You may want to consider using one of those instead of the 'graphviz' Python module.
If you use spring-boot, you don't need to create a DataSource class, just specify the data url/username/password/driver in application.properties
, then you can simply @Autowired
it.
@Repository
public class JdbcRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public DynamicRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void insert() {
jdbcTemplate.update("INSERT INTO BOOK (name, description) VALUES ('book name', 'book description')");
}
}
Example of application.properties
:
#Basic Spring Boot Config for Oracle
spring.datasource.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourHostIP)(PORT=YourPort))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=YourServiceName)))
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
Then add the driver and connection pool dependencies in pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.1</version>
</dependency>
<!-- HikariCP connection pool -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.0</version>
</dependency>
See the official doc for more details.
This being a very old question but worth adding that I have just had a similar issue where a background colour on a footer
element in my case didn't show. I added a position: relative
which worked.
You could construct a dataframe from the series and then merge with the dataframe. So you specify the data as the values but multiply them by the length, set the columns to the index and set params for left_index and right_index to True:
In [27]:
df.merge(pd.DataFrame(data = [s.values] * len(s), columns = s.index), left_index=True, right_index=True)
Out[27]:
a b s1 s2
0 1 3 5 6
1 2 4 5 6
EDIT for the situation where you want the index of your constructed df from the series to use the index of the df then you can do the following:
df.merge(pd.DataFrame(data = [s.values] * len(df), columns = s.index, index=df.index), left_index=True, right_index=True)
This assumes that the indices match the length.
You could do something like this
dict = [{
"id": 1,
"name": "Doom Hammer"
},
{
"id": 2,
"name": "Rings ov Saturn"
}
]
for x in dict:
if x["id"] == 2:
print(x["name"])
Thats what i use to find the objects in a long array of objects.
I was able to set up github actions to automatically commit the results of a node build command (yarn build
in my case but it should work with npm too) to the gh-pages
branch whenever a new commit is pushed to master.
While not completely ideal as i'd like to avoid committing the built files, it seems like this is currently the only way to publish to github pages.
I based my workflow off of this guide for a different react library, and had to make the following changes to get it to work for me:
yarn export
because that command does not exist and it doesn't seem to add anything helpful (you may also want to change the build line above it to suit your needs)env
directive to the yarn build
step so that I can include the SHA hash of the commit that generated the build inside my app, but this is optionalHere is my full github action:
name: github pages
on:
push:
branches:
- master
jobs:
deploy:
runs-on: ubuntu-18.04
steps:
- uses: actions/checkout@v2
- name: Setup Node
uses: actions/setup-node@v2-beta
with:
node-version: '12'
- name: Get yarn cache
id: yarn-cache
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Cache dependencies
uses: actions/cache@v2
with:
path: ${{ steps.yarn-cache.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- run: yarn install --frozen-lockfile
- run: yarn build
env:
REACT_APP_GIT_SHA: ${{ github.SHA }}
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build
The docs for next.js also provides instructions for setting up with Vercel which appears to be a hosting service for node.js apps similar to github pages. I have not tried this though and so cannot speak to how well it works.
Use a iterator to loop through list and then delete the required object.
Iterator itr = a.iterator();
while(itr.hasNext()){
if(itr.next().equals("acbd"))
itr.remove();
}
Update : As @amram99 mentioned, the issue has been fixed as of the release of Android Studio v1.3.
Tested and verified with below specifications
What works now
Now you can import a local aar file via the File>New>New Module>Import .JAR/.AAR Package option in Android Studio v1.3
However the below answer holds true and effective irrespective of the Android Studio changes as this is based of gradle scripting.
Old Answer : In a recent update the people at android broke the inclusion of local aar files via the Android Studio's add new module menu option. Check the Issue listed here. Irrespective of anything that goes in and out of IDE's feature list , the below method works when it comes to working with local aar files.(Tested it today):
Put the aar file in the libs directory (create it if needed), then, add the following code in your build.gradle :
dependencies {
compile(name:'nameOfYourAARFileWithoutExtension', ext:'aar')
}
repositories{
flatDir{
dirs 'libs'
}
}
EDIT: Okay, now we know it's Java...
Section 4.2.2 of the Java Language Specification states:
The Java programming language provides a number of operators that act on integral values:
[...]
The numerical operators, which result in a value of type int or long: [...] The additive operators + and - (§15.18)
In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int
or long
, which is why you need to cast to assign to a short
variable.
Original answer (C#)
In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:
int operator +(int x, int y);
uint operator +(uint x, uint y);
long operator +(long x, long y);
ulong operator +(ulong x, ulong y);
float operator +(float x, float y);
double operator +(double x, double y);
These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:
decimal operator +(decimal x, decimal y);
(Enumeration addition, string concatenation and delegate combination are also defined there.)
As you can see, there's no short operator +(short x, short y)
operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.
An int*
is a pointer to an int
, so int*&
must be a reference to a pointer to an int
. Similarly, int**
is a pointer to a pointer to an int
, so int**&
must be a reference to a pointer to a pointer to an int
.
Use sqlalchemy's text function to remove the interpretation of special characters:
Note the use of the function text("your_insert_statement")
below. What it does is communicate to sqlalchemy that all of the questionmarks and percent signs in the passed in string should be considered as literals.
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re
engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
% ("your_username", "your_password", "your_hostname_mysql_server:3306",
"your_database"),
pool_size=3, pool_recycle=3600)
conn = engine.connect()
myfile = open('access2.log', 'r')
lines = myfile.readlines()
penguins = []
for line in lines:
elements = re.split('\s+', line)
print "item: " + elements[0]
linedate = datetime.fromtimestamp(float(elements[0]))
mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")
penguins.append(text(
"insert into your_table (foobar) values('%%%????')"))
for penguin in penguins:
print penguin
conn.execute(penguin)
conn.close()
Try this:
$('#divID').css({"background":"none"});// remove existing
$('#divID').css({"background":"#bada55"});// add new color here.
Thanks
You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);
i also suppose you want to center the image, so the code would be :
function drawImageScaled(img, ctx) {
var canvas = ctx.canvas ;
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
var centerShift_y = ( canvas.height - img.height*ratio ) / 2;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(img, 0,0, img.width, img.height,
centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);
}
you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output
The important part is this:
Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];
due to:
nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
According to this log, Spring could not find your MemberPointSummaryDAOImpl
class.
I have faced similar problem, 'int' object has no attribute 'DataFrame',
This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.
I realized this, and changed my variable to something else, and fixed the error.
I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.
However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.
For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:
perl Makefile.PL INSTALL_BASE=/mydir/perl
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
create a new file with string image path
String imagePath;
File test = new File(imagePath);
test.getName();
test.getPath();
getExtension(test.getName());
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
First, the error you're getting is due to where you're using the COUNT
function -- you can't use an aggregate (or group) function in the WHERE
clause.
Second, instead of using a subquery, simply join the table to itself:
SELECT a.pid
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid
Which I believe should return only rows where at least two rows exist with the same pid
but there is are at least 2 sid
s. To make sure you get back only one row per pid
I've applied a grouping clause.
$python 2.7.8
from timeit import timeit
import numpy
timeit("list(0 for i in xrange(0, 100000))", number=1000)
> 8.173301935195923
timeit("[0 for i in xrange(0, 100000)]", number=1000)
> 4.881675958633423
timeit("[0] * 100000", number=1000)
> 0.6624710559844971
timeit('list(itertools.repeat(0, 100000))', 'import itertools', number=1000)
> 1.0820629596710205
You should use [0] * n
to generate a list with n
zeros.
See why [] is faster than list()
There is a gotcha though, both itertools.repeat
and [0] * n
will create lists whose elements refer to same id
. This is not a problem with immutable objects like integers or strings but if you try to create list of mutable objects like a list of lists ([[]] * n
) then all the elements will refer to the same object.
a = [[]] * 10
a[0].append(1)
a
> [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
[0] * n
will create the list immediately while repeat
can be used to create the list lazily when it is first accessed.
If you're dealing with really large amount of data and your problem doesn't need variable length of list or multiple data types within the list it is better to use numpy
arrays.
timeit('numpy.zeros(100000, numpy.int)', 'import numpy', number=1000)
> 0.057849884033203125
numpy
arrays will also consume less memory.
One option is you can wrap it into another array:
Foo(new object[]{ new object[]{ (object)"1", (object)"2" } });
Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:
Foo((object) new object[]{ (object)"1", (object)"2" });
Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:
void Foo(object[] item)
{
// Somehow don't duplicate Foo(object[]) and
// Foo(params object[]) without making an infinite
// recursive call... maybe something like
// FooImpl(params object[] items) and then this
// could invoke it via:
// FooImpl(new object[] { item });
}
!important
word is prior to first two rules.for example:
.divclass .spanclass
is more specific than .spanclass
.divclass.divclass
is more specific than .divclass
#divId .spanclass
has ID that's why it is more specific than .divClass .spanClass
<div id="someDiv" style="color:red;">
has attribute and beats #someDiv{color:blue}
#someDiv{color:blue!important}
will be applied over attribute style="color:red"
When creating a PWA, a service worker used on an non https server also generates this error.
You have to set the property of StoreGeneratedPattern
to identity and then try your own code.
Or else you can also use this.
using (var context = new MyContext())
{
context.MyEntities.AddObject(myNewObject);
context.SaveChanges();
int id = myNewObject.Id; // Your Identity column ID
}
Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.
This functionality can also be added using JavaScript. Carto.net has an example:
http://old.carto.net/papers/svg/textFlow/
Something else that also might be useful to are you are editable text areas:
BufferedReader
can't wrap an InputStream
directly. It wraps another Reader
. In this case you'd want to do something like:
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
In dashboard you can see running word press version at "At a Glance"
Paste my contains
example here:
//table[contains(@class, "EC_result")]/tbody
As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub
. The simplest way is to change location
to str(location)
when using re.sub
. It wouldn't hurt to do it anyways even if it's already a str
.
letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
" ", # Replace all non-letters with spaces
str(location))
This is what helped me. My navigation bar is in the body tag. Entire code for navigation bar is in nav.html
file (without any html or body tag, only the code for navigation bar). In the target page, this goes in the head
tag:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Then in the body tag, a container is made with an unique id and a javascript block to load the nav.html
into the container, as follows:
<!--Navigation bar-->
<div id="nav-placeholder">
</div>
<script>
$(function(){
$("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->
ALTER SCHEMA dbo TRANSFER jonathan.MovieData;
See ALTER SCHEMA.
Generalized Syntax:
ALTER SCHEMA TargetSchema TRANSFER SourceSchema.TableName;
I prefer the following, which is cleaner:
x = [1, 2, 3];
g=sprintf('%d ', x);
fprintf('Answer: %s\n', g)
which outputs
Answer: 1 2 3
li:nth-child(1n) { color:green; }_x000D_
li:nth-child(2n) { color:red; }
_x000D_
<ul>_x000D_
<li>list element 1</li>_x000D_
<li>list element 2</li>_x000D_
<li>list element 3</li>_x000D_
<li>list element 4</li>_x000D_
</ul>
_x000D_
See browser support here : CSS3 :nth-child() Selector
Any use of any of the methods suggested is considered a code smell which is based in a bad OO design.
If your design is good, you should not find yourself needing to use getClass()
or instanceof
.
Any of the suggested methods will do, but just something to keep in mind, design-wise.
Just use:
mail
d 1-15
quit
Which will delete all messages between number 1 and 15. to delete all, use the d *
.
I just used this myself on ubuntu 12.04.4, and it worked like a charm.
For example:
eric@dev ~ $ mail
Heirloom Mail version 12.4 7/29/08. Type ? for help.
"/var/spool/mail/eric": 2 messages 2 new
>N 1 Cron Daemon Tue Jul 29 17:43 23/1016 "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
N 2 Cron Daemon Tue Jul 29 17:44 23/1016 "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
& d *
& quit
Then check your mail again:
eric@dev ~ $ mail
No mail for eric
eric@dev ~ $
What is tripping you up is you are using x
or exit
to quit which rolls back the changes during that session.
The answer that you got there is correct. One minor thing in the code above, you need to init(key) before you can call doFinal()
final Charset charSet = Charset.forName("US-ASCII");
final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(charSet.encode("key").array(), "HmacSHA256");
try {
sha256_HMAC.init(secret_key);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
...
Open the httpd.conf file and search for
"rewrite"
, then remove
"#"
at the starting of the line,so the line looks like.
LoadModule rewrite_module modules/mod_rewrite.so
then restart the wamp.
Basically below code line is only useful in data binding scenarios
datagridview.DataSource = null;
otherwise below is the used when no data binding and datagridview is populated manually
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
So, check first what you are doing.
I'd wrap the dictionary in another class:
public class MyListDictionary
{
private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();
public void Add(string key, string value)
{
if (this.internalDictionary.ContainsKey(key))
{
List<string> list = this.internalDictionary[key];
if (list.Contains(value) == false)
{
list.Add(value);
}
}
else
{
List<string> list = new List<string>();
list.Add(value);
this.internalDictionary.Add(key, list);
}
}
}
process.stdin.pipe(process.stdout);
in short the difference between recursion memoization and Dynamic programming
Dynamic programming as name suggest is using the previous calculated value to dynamically construct the next new solution
Where to apply dynamic programming : If you solution is based on optimal substructure and overlapping sub problem then in that case using the earlier calculated value will be useful so you do not have to recompute it. It is bottom up approach. Suppose you need to calculate fib(n) in that case all you need to do is add the previous calculated value of fib(n-1) and fib(n-2)
Recursion : Basically subdividing you problem into smaller part to solve it with ease but keep it in mind it does not avoid re computation if we have same value calculated previously in other recursion call.
Memoization : Basically storing the old calculated recursion value in table is known as memoization which will avoid re-computation if its already been calculated by some previous call so any value will be calculated once. So before calculating we check whether this value has already been calculated or not if already calculated then we return the same from table instead of recomputing. It is also top down approach
Running Windows Server 2008 R2 64bit and .net framework 4.5, ran this command from this location, and was successful:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis -i
output:
Microsoft (R) ASP.NET RegIIS version 4.0.30319.0
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.0).
.....
Finished installing ASP.NET (4.0.30319.0).
For split string by space like in Python lang, can be used:
var w = "hello my brothers ;";
w.split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );
output:
["hello", "my", "brothers", ";"]
or similar:
w.split(/(\s+)/).filter( e => e.trim().length > 0)
(output some)
You should cast your numbers as floats, which will do this for you.
$string = "42.422005000000000000000000000000";
echo (float)$string;
Output of this will be what you are looking for.
42.422005
Same with something more complex...getting the ec2 instance region from within the instance.
INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")
echo $INSTANCE_REGION
Here is another helpful solution for manually adding custom HTTP Headers to your client WCF request using the ChannelFactory
as a proxy. This would have to be done for each request, but suffices as a simple demo if you just need to unit test your proxy in preparation for non-.NET platforms.
// create channel factory / proxy ...
using (OperationContextScope scope = new OperationContextScope(proxy))
{
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = new HttpRequestMessageProperty()
{
Headers =
{
{ "MyCustomHeader", Environment.UserName },
{ HttpRequestHeader.UserAgent, "My Custom Agent"}
}
};
// perform proxy operations...
}
Because you set visibility either true or false.
try that
setVisible(0)
to visible true .
and setVisible(4)
to visible false.
There are a few ways to do this it seems.
Angular provides an $anchorScroll
service, but the documentation is severely lacking and I've not been able to get it to work.
Check out http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html for some insight into $anchorScroll
.
Another way I tested out was creating a custom directive and using el.scrollIntoView()
.
This works pretty decently by basically doing the following in your directive link function:
var el = document.getElementById(attrs.href);
el.scrollIntoView();
However, it seems a bit overblown to do both of these when the browser natively supports this, right?
If you take a look at http://docs.angularjs.org/guide/dev_guide.services.$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:
Links that contain target element
Example:
<a href="/ext/link?a=b" target="_self">link</a>
So, all you have to do is add the target
attribute to your links, like so:
<a href="#anchorLinkID" target="_self">Go to inpage section</a>
Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.
I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.
Gotta note that after a successful scroll and hash change, Angular does follow up and rewrite the hash to its custom style. However, the browser has already completed its business and you are good to go.
What's perplexing to me is that the visual studio designer only allows you to use BackgroundWorkers and Timers that don't actually work with the service project.
It gives you neat drag and drop controls onto your service but... don't even try deploying it. Won't work.
Services: Only use System.Timers.Timer System.Windows.Forms.Timer won't work even though it's available in the toolbox
Services: BackgroundWorkers will not work when it's running as a service Use System.Threading.ThreadPools instead or Async calls
In 2010 it is ctrl +k +d for indentation
In my case, it's because I accidentally removed (not deleted) the stdafx.h
and targetver.h
files in the Header Files section.
Add these files back to Header Files and the problem is solved.
I had these:
#pragma comment( linker, "/entry:\"mainCRTStartup\"" ) // set the entry point to be main()
I just need to comment that (by prepending //
) and it's good.