For PHP's PHPSESSID variable, this function works:
function getPHPSessId() {
var phpSessionId = document.cookie.match(/PHPSESSID=[A-Za-z0-9]+\;/i);
if(phpSessionId == null)
return '';
if(typeof(phpSessionId) == 'undefined')
return '';
if(phpSessionId.length <= 0)
return '';
phpSessionId = phpSessionId[0];
var end = phpSessionId.lastIndexOf(';');
if(end == -1) end = phpSessionId.length;
return phpSessionId.substring(10, end);
}
Yes there is. The preferred syntax is to favor str.format
over the deprecated %
operator.
print "First number is {} and second number is {}".format(first, second)
from collections import OrderedDict
def remove_duplicates(value):
m=list(OrderedDict.fromkeys(value))
s=''
for i in m:
s+=i
return s
print(remove_duplicates("11223445566666ababzzz@@@123#*#*"))
This is a one line solution.
It will run taskkill only if the process is really running otherwise it will just info that it is not running.
tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.
This is the output in case the process was running:
notepad.exe 1960 Console 0 112,260 K
SUCCESS: The process "notepad.exe" with PID 1960 has been terminated.
This is the output in case not running:
process "notepad.exe" not running.
Use the DATEPART function to extract the month from the date.
So you would do something like this:
SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)
At macOS Catalina, I followed this steps to set secure_file_priv
1.Stop MySQL service
sudo /usr/local/mysql/support-files/mysql.server stop
2.Restart MYSQL assigning --secure_file_priv system variables
sudo /usr/local/mysql/support-files/mysql.server start --secure-file-priv=YOUR_FILE_DIRECTORY
Note: Adding empty value fix the issue for me, and MYSQL will export data to directory /usr/local/mysql/data/YOUR_DB_TABLE/EXPORT_FILE
sudo /usr/local/mysql/support-files/mysql.server start --secure-file-priv=
Thanks
add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=
above answer didnt help me as my string value was "700.00"
with Swift 2.2 this works for me
let myString = "700.00"
let myInt = (myString as NSString).integerValue
I passed myInt to NSFormatterClass
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0
let priceValue = formatter.stringFromNumber(myInt!)!
//Now priceValue is ? 700
Thanks to this blog post.
Th part of an URI after the #
is called "fragment" and is by definition only available/processed on client side (see https://en.wikipedia.org/wiki/Fragment_identifier).
On the client side, this can be accessed using javaScript with window.location.hash
.
Parse to your string to a decimal first.
Add System.ServiceModel
in references
Using SyndicationFeed
:
string url = "http://fooblog.com/feed";
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
foreach (SyndicationItem item in feed.Items)
{
String subject = item.Title.Text;
String summary = item.Summary.Text;
...
}
Mapped to CoffeeScript if anyones interested. **edit -> sorry using backbone too, but you get the idea.
Modified slightly to accept a beacon with attribs
{latitude: item.lat,longitude: item.lng,date: new Date(item.effective_at),accuracy: item.gps_accuracy}
MIN_ACCURACY = 1
# mapped from http://stackoverflow.com/questions/1134579/smooth-gps-data
class v.Map.BeaconFilter
constructor: ->
_.extend(this, Backbone.Events)
process: (decay,beacon) ->
accuracy = Math.max beacon.accuracy, MIN_ACCURACY
unless @variance?
# if variance nil, inititalise some values
@variance = accuracy * accuracy
@timestamp_ms = beacon.date.getTime();
@lat = beacon.latitude
@lng = beacon.longitude
else
@timestamp_ms = beacon.date.getTime() - @timestamp_ms
if @timestamp_ms > 0
# time has moved on, so the uncertainty in the current position increases
@variance += @timestamp_ms * decay * decay / 1000;
@timestamp_ms = beacon.date.getTime();
# Kalman gain matrix K = Covarariance * Inverse(Covariance + MeasurementVariance)
# NB: because K is dimensionless, it doesn't matter that variance has different units to lat and lng
_k = @variance / (@variance + accuracy * accuracy)
@lat = _k * (beacon.latitude - @lat)
@lng = _k * (beacon.longitude - @lng)
@variance = (1 - _k) * @variance
[@lat,@lng]
I tried:
rm -rf .git
and also
Git keeps all of its files in the .git directory. Just remove that one and init again.
Neither worked for me. Here's what did:
.git
Then create / restore the project from backup:
For beginners: To create your .bash_profile
file in your home directory on MacOS, run:
nano ~/.bash_profile
Then you can paste in the following:
https://gist.github.com/mocon/0baf15e62163a07cb957888559d1b054
As you can see, it includes some example aliases and an environment variable at the bottom.
One you're done making your changes, follow the instructions at the bottom of the Nano editor window to WriteOut (Ctrl-O
) and Exit (Ctrl-X
). Then quit your Terminal and reopen it, and you will be able to use your newly defined aliases and environment variables.
The error seems clear: model objects do not support item assignment.
MyModel.objects.latest('id')['foo'] = 'bar'
will throw this same error.
It's a little confusing that your model instance is called projectForm
...
To reproduce your first block of code in a loop, you need to use setattr
for k,v in session_results.iteritems():
setattr(projectForm, k, v)
You should be able to match it with: /<primaryAddress>(.+?)<\/primaryAddress>/
The content between the tags will be in the matched group.
This is my preferred version using a class based view. Simply subclass the basic View and override the get()-method.
import json
class MyJsonView(View):
def get(self, *args, **kwargs):
resp = {'my_key': 'my value',}
return HttpResponse(json.dumps(resp), mimetype="application/json" )
This might sound strange but you can remove next line by copying the whole text and pasting it in firefox search bar, and then re-pasting it in notepad++
To print both key and value, use the following:
for (Object objectName : example.keySet()) {
System.out.println(objectName);
System.out.println(example.get(objectName));
}
This is what I tried for a right outer join [as per my requirement]:
m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink,
by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"),
by.y=c("company_permalink"), all.y=TRUE)
This worked.
I came up with a similar example. Again, the rotation keyword is.. well, it's key.
from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.bar( [0,1,2], [1,3,5] )
ax.set_xticks( [ 0.5, 1.5, 2.5 ] )
ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ;
Below works for me if your exe depend on some dll or certain dependency then you need to set directory path. As mention below exePath mean folder where exe placed along with it's references files.
Exe application creating any temporaray file so it will create in folder mention in processBuilder.directory(...)
**
ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.directory(new File(exePath));
process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
if (waitFlag == 0) {
...
int returnVal = process.exitValue();
}
**
Let us assume:
then you really want to chop the files into parts, count parts in parallel on multiple nodes and sum up the results from there (this is basically @Chris White's idea).
Here is how you do that with GNU Parallel (version > 20161222). You need to list the nodes in ~/.parallel/my_cluster_hosts
and you must have ssh
access to all of them:
parwc() {
# Usage:
# parwc -l file
# Give one chunck per host
chunks=$(cat ~/.parallel/my_cluster_hosts|wc -l)
# Build commands that take a chunk each and do 'wc' on that
# ("map")
parallel -j $chunks --block -1 --pipepart -a "$2" -vv --dryrun wc "$1" |
# For each command
# log into a cluster host
# cd to current working dir
# execute the command
parallel -j0 --slf my_cluster_hosts --wd . |
# Sum up the number of lines
# ("reduce")
perl -ne '$sum += $_; END { print $sum,"\n" }'
}
Use as:
parwc -l myfile
parwc -w myfile
parwc -c myfile
Let's explorer how the go get repository_remote_url
command manages the project structure under $GOPATH
. If we do a go get github.com/gohugoio/hugo
It will clone the repository under
$GOPATH/src/repository_remote/user_name/project_name
$GOPATH/src/github.com/gohugoio/hugo
This is a nice way to create your initial project path. Now let's explorer what are the project types out there and how their inner structures are organized. All golang projects in the community can be categorized under
Libraries
(no executable binaries)Single Project
(contains only 1 executable binary)Tooling Projects
(contains multiple executable binaries)Generally golang project files can be packaged under any design principles such as DDD, POD
Most of the available go projects follows this Package Oriented Design
Package Oriented Design encourage the developer to keeps the implementation only inside it's own packages, other than the /internal
package those packages can't can communicate with each other
/internal
package is mainly used to hide the implementation from other projects. ~/$GOPATH/
bin/
pkg/
src/
repository_remote/
user_name/
project_name/
internal/
other_pkg/
cmd/
package manages the number of binaries (tools) that we want to build ~/$GOPATH/
bin/
pkg/
src/
repository_remote/
user_name/
project_name/
cmd/
binary_one/
main.go
binary_two/
main.go
binary_three/
main.go
other_pkg/
Before Mysql version 5.0.3 Varchar datatype can store 255 character, but from 5.0.3 it can be store 65,535 characters.
BUT it has a limitation of maximum row size of 65,535 bytes. It means including all columns it must not be more than 65,535 bytes.
In your case it may possible that when you are trying to set more than 10000 it is exceeding more than 65,535 and mysql will gives the error.
For more information: https://dev.mysql.com/doc/refman/5.0/en/column-count-limit.html
blog with example: http://goo.gl/Hli6G3
May be the file name or path you are used may be incorrect
In my system i created file abcd.sql at c:\
and used command mysql> source c:\abcd.sql
Then i got result
Align the text area box to the label, not the label to the text area,
label {
width: 180px;
display: inline-block;
}
textarea{
vertical-align: middle;
}
<label for="myfield">Label text</label><textarea id="myfield" rows="5" cols="30"></textarea>
Beyond @Jaime excellent answer, another way to collapse a row is to uses a.strides[0]
(assuming a
is C-contiguous) which is equal to a.dtype.itemsize*a.shape[0]
. Furthermore void(n)
is a shortcut for dtype((void,n))
. we arrive finally to this shortest version :
a[unique(a.view(void(a.strides[0])),1)[1]]
For
[[0 1 1 1 0 0]
[1 1 1 0 0 0]
[1 1 1 1 1 0]]
I've had success with using white-space: nowrap; on the outer container, display: inline-block; on the inner containers, and then (in my case since I wanted the second one to word-wrap) white-space: normal; on the inner ones.
after that change in git-ignore file run this command , This command will remove all file cache not the files or changes
git rm -r --cached .
after execution of this command commit the files
for removing single file or folder from cache use this command
git rm --cached filepath/foldername
var arr = []
while(arr.length < 8){
var randomnumber=Math.ceil(Math.random()*100)
if(arr.indexOf(randomnumber) === -1){arr.push(randomnumber)}
}
document.write(arr);
shorter than other answers I've seen
You can try this also-
if( !$('#EventStartTimeMin').val() ) {
// do something
}
in these cases you can try ssh if https is stuck.
Also you can try increasing the buffer size to an astronomical figure so that you dont have to worry about the buffer size any more git config http.postBuffer 100000000
The way you have added a row into the table layout you can add multiple TableRow
instances into your tableLayout
object
tl.addView(row1);
tl.addView(row2);
etc...
(For those coming to this question from a search engine), check that your stored procedures declare a custom delimiter, as this is the error that you might see when the engine can't figure out how to terminate a statement:
ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line…
If you have a database dump and see:
DROP PROCEDURE IF EXISTS prc_test;
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE', test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
SELECT @sqlstr;
PREPARE stmt FROM @sqlstr;
EXECUTE stmt;
END;
Try wrapping with a custom DELIMITER
:
DROP PROCEDURE IF EXISTS prc_test;
DELIMITER $$
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE', test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
SELECT @sqlstr;
PREPARE stmt FROM @sqlstr;
EXECUTE stmt;
END;
$$
DELIMITER ;
So if you just have a string and not a window.location you could use...
String.prototype.toUrl = function(){
if(!this && 0 < this.length)
{
return undefined;
}
var original = this.toString();
var s = original;
if(!original.toLowerCase().startsWith('http'))
{
s = 'http://' + original;
}
s = this.split('/');
var protocol = s[0];
var host = s[2];
var relativePath = '';
if(s.length > 3){
for(var i=3;i< s.length;i++)
{
relativePath += '/' + s[i];
}
}
s = host.split('.');
var domain = s[s.length-2] + '.' + s[s.length-1];
return {
original: original,
protocol: protocol,
domain: domain,
host: host,
relativePath: relativePath,
getParameter: function(param)
{
return this.getParameters()[param];
},
getParameters: function(){
var vars = [], hash;
var hashes = this.original.slice(this.original.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
};};
How to use.
var str = "http://en.wikipedia.org/wiki/Knopf?q=1&t=2";
var url = str.toUrl;
var host = url.host;
var domain = url.domain;
var original = url.original;
var relativePath = url.relativePath;
var paramQ = url.getParameter('q');
var paramT = url.getParamter('t');
Always use latest SDK version to build:
compileSdkVersion 23
It does not affect runtime behavior, but give you latest programming features.
Just add <br>
where you would like to make the new line.
$S$: a set of shops
<br>
$I$: a set of items M wants to get
Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html
Note that newlines using <br>
does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br>
as a space.
As everyone aware about the process of cloning, I would like to add few more things here. Don't worry about special character or writing "@" as "%40" see character encoding
$ git clone https://username:[email protected]/user/repo
This line can do the job
To solve this issue I encourage to use GitHub Developer option to generate Access token. I believe Access token is secure and you wont find any special character.
creating-a-personal-access-token
Now I will write the below code to access my repository.
$ git clone https://username:[email protected]/user/repo
I am just replacing my original password with Access-token, Now I am not worried if some one see my access credential , I can regenerate the token when ever I feel.
Make sure you have checked repo Full control of private repositories
In case of float values with characters 'e' '+' it errors out if we try to convert in decimal. ('2.81104e+006'). It still pass ISNUMERIC test.
SELECT ISNUMERIC('2.81104e+006')
returns 1
.
SELECT convert(decimal(15,2), '2.81104e+006')
returns
error: Error converting data type varchar to numeric.
And
SELECT try_convert(decimal(15,2), '2.81104e+006')
returns NULL
.
SELECT convert(float, '2.81104e+006')
returns the correct value 2811040
.
Try this one, if you want to truncate based on Words instead of characters while also allowing an option to see the complete text.
Came here searching for a Read More solution based on words, sharing the custom Pipe
i ended up writing.
Pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'readMore'
})
export class ReadMorePipe implements PipeTransform {
transform(text: any, length: number = 20, showAll: boolean = false, suffix: string = '...'): any {
if (showAll) {
return text;
}
if ( text.split(" ").length > length ) {
return text.split(" ").splice(0, length).join(" ") + suffix;
}
return text;
}
}
In Template:
<p [innerHTML]="description | readMore:30:showAll"></p>
<button (click)="triggerReadMore()" *ngIf="!showAll">Read More<button>
Component:
export class ExamplePage implements OnInit {
public showAll: any = false;
triggerReadMore() {
this.showAll = true;
}
}
In Module:
import { ReadMorePipe } from '../_helpers/read-more.pipe';
@NgModule({
declarations: [ReadMorePipe]
})
export class ExamplePageModule {}
goto
doesn't do anything in Java.
As Get-Date
returns a DateTime object you are able to compare them directly. An example:
(get-date 2010-01-02) -lt (get-date 2010-01-01)
will return false.
use reverse for loop to print in descending order,
for (int i = ar.length - 1; i >= 0; i--) {
Arrays.sort(ar);
System.out.println(ar[i]);
}
Be careful in comparing the find result with the the end like for map 'm' as all answer have done above map::iterator i = m.find("f");
if (i == m.end())
{
}
else
{
}
you should not try and perform any operation such as printing the key or value with iterator i if its equal to m.end() else it will lead to segmentation fault.
Tell the correlation to ignore the NAs with use
argument, e.g.:
cor(data$price, data$exprice, use = "complete.obs")
You can use below function for relative path as absolute path is not a good idea to add in script
Import
import sys, os
Use code as below :
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'Screenshots'+ os.sep)
driver.get_screenshot_as_file(screenshotpath+"testPngFunction.png")
make sure you create the folder where the .py file is present.
os.path.join
also prevent you to run your script in cross-platform like: UNIX and windows. It will generate path separator as per OS at runtime. os.sep
is similar like File.separtor
in java
I'm very late to the party but this answer pulls up top in Google search results.
Bootstrap 3 has an answer for this built in, set your container div in your navbar to container-fluid
and it'll fall to screen width.
Like so:
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">More Stuff</a></li>
</ul>
</div>
</div>
</div>
I have a cool one, facebook created a automated tool for rewriting PHP code. They parse the source into an abstract syntax tree, do some transformations:
if ($f == false) -> if (false == $f)
I don't know why, but that seems to be their particular style and then they pretty print it.
https://github.com/facebook/lex-pass
We use haskell for making small domain specific languages. Huge amounts of data processing. Web development. Web spiders. Testing applications. Writing system administration scripts. Backend scripts, which communicate with other parties. Monitoring scripts (we have a DSL which works nicely together with munin, makes it much easier to write correct monitor code for your applications.)
All kind of stuff actually. It is just a everyday general purpose language with some very powerful and useful features, if you are somewhat mathematically inclined.
Since other solutions are old and either poorly-working or not working at all, I've modified NestedScrollView
, which is stable, modern and it has all you expect from a scroll view. Except for horizontal scrolling.
Here's the repo: https://github.com/ultimate-deej/TwoWayNestedScrollView
I've made no changes, no "improvements" to the original NestedScrollView
expect for what was absolutely necessary.
The code is based on androidx.core:core:1.3.0
, which is the latest stable version at the time of writing.
All of the following works:
NestedScrollView
)Update September 26, 2016:
As @Taytay's answer says, instead of the 'typings' installations that we used a few months ago, we can now use:
npm install --save @types/lodash
Here are some additional references supporting that answer:
If still using the typings installation, see the comments below (by others) regarding '''--ambient''' and '''--global'''.
Also, in the new Quick Start, config is no longer in index.html; it's now in systemjs.config.ts (if using SystemJS).
Original Answer:
This worked on my mac (after installing Angular 2 as per Quick Start):
sudo npm install typings --global
npm install lodash --save
typings install lodash --ambient --save
You will find various files affected, e.g.
Angular 2 Quickstart uses System.js, so I added 'map' to the config in index.html as follows:
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
},
map: {
lodash: 'node_modules/lodash/lodash.js'
}
});
Then in my .ts code I was able to do:
import _ from 'lodash';
console.log('lodash version:', _.VERSION);
Edits from mid-2016:
As @tibbus mentions, in some contexts, you need:
import * as _ from 'lodash';
If starting from angular2-seed, and if you don't want to import every time, you can skip the map and import steps and just uncomment the lodash line in tools/config/project.config.ts.
To get my tests working with lodash, I also had to add a line to the files array in karma.conf.js:
'node_modules/lodash/lodash.js',
if you want to split the plot into two columns (2 plots next to each other), you can do it like this:
par(mfrow=c(1,2))
plot(x)
plot(y)
I had similar issue. Earlier I was using Maven 3 to build the project. After switching to maven 2 , I had the above error.
Solved it by switching to Maven 3.
If the first cell returned is a null
, the result in .NET will be DBNull.Value
If no cells are returned, the result in .NET will be null
; you cannot call ToString()
on a null
. You can of course capture what ExecuteScalar
returns and process the null
/ DBNull
/ other cases separately.
Since you are grouping etc, you presumably could potentially have more than one group. Frankly I'm not sure ExecuteScalar
is your best option here...
Additional: the sql in the question is bad in many ways:
I strongly suggest you parameterize; perhaps with something like "dapper" to make it easy:
int count = conn.Query<int>(
@"select COUNT(idemp_atd) absentDayNo from td_atd
where absentdate_atd between @sdate and @edate
and idemp_atd=@idemp group by idemp_atd",
new {sdate, edate, idemp}).FirstOrDefault();
all problems solved, including the "no rows" scenario. The dates are passed as dates (not strings); the injection hole is closed by use of a parameter. You get query-plan re-use as an added bonus, too. The group by
here is redundant, BTW - if there is only one group (via the equality condition) you might as well just select COUNT(1)
.
Using a plain object, you can pair up strings that represent property names with their corresponding values. Changing the background color, and making text bolder, for instance would look like this:
$("#message").css({
"background-color": "#0F0",
"font-weight" : "bolder"
});
Alternatively, you can use the JavaScript property names too:
$("#message").css({
backgroundColor: "rgb(128, 115, 94)",
fontWeight : "700"
});
More information can be found in jQuery's documentation.
A while
loop can be simulated in cmd.exe
with:
:still_more_files
if %countfiles% leq 21 (
rem change countfile here
goto :still_more_files
)
For example, the following script:
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 0"
:more_to_process
if %x% leq 5 (
echo %x%
set /a "x = x + 1"
goto :more_to_process
)
endlocal
outputs:
0
1
2
3
4
5
For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:
@echo off
set backupdir=c:\test
:more_files_to_process
for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
if %num% gtr 20 (
cscript /nologo c:\deletefile.vbs %backupdir%
goto :more_files_to_process
)
Here are the steps:
To verify if Path is set successfully open terminal again and type adb if adb version and other details are displayed that means path is set properly.
Use this:
SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM
(SELECT DISTINCT id FROM table WHERE fid = 64) Base
and put the "output" of a query as the "input" of another.
Using CTE:
; WITH Base AS (
SELECT DISTINCT id FROM table WHERE fid = 64
)
SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM Base
The two queries should be equivalent.
Technically you could
SELECT DISTINCT id, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) AS RowNum
FROM table
WHERE fid = 64
but if you increase the number of DISTINCT fields, you have to put all these fields in the PARTITION BY
, so for example
SELECT DISTINCT id, description,
ROW_NUMBER() OVER (PARTITION BY id, description ORDER BY id) AS RowNum
FROM table
WHERE fid = 64
I even hope you comprehend that you are going against standard naming conventions here, id
should probably be a primary key, so unique by definition, so a DISTINCT
would be useless on it, unless you coupled the query with some JOIN
s/UNION ALL
...
I believe a watermark as mentioned in this post would work well in this case
There's a bit of code needed but you can reuse it for any combobox or textbox (and even passwordboxes) so I prefer this way
The Jackson-databind library also has ISO8601DateFormat class that does that (actual implementation in ISO8601Utils.
ISO8601DateFormat df = new ISO8601DateFormat();
Date d = df.parse("2010-07-28T22:25:51Z");
A convenient solution in your case would be to include the configs in a yaml file named
**your_config_name.yml**
which would look like this:
path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"
In your python code you can then load the config params into a dictionary by doing this:
import yaml
with open('your_config_name.yml') as stream:
config = yaml.safe_load(stream)
You then access e.g. path1 like this from your dictionary config:
config['path1']
To import yaml you first have to install the package as such: pip install pyyaml
into your chosen virtual environment.
The best solution is a minimal use of java directly in the visualstudio GUI
here it is: On a button go to the "OnClientClick" property (its not into events*) overthere type:
return confirm('are you sure?')
it will put a dialog with cancel ok buttons transparent over current page if cancel is pressed no postback will ocure. However if you want only ok button type:
alert ('i told you so')
The events like onclick work server side they execute your code, while OnClientClick runs in the browser side. the come most close to a basic dialog
The command bellow wont work always. If you do just:
$ git checkout thebranch
Already on 'thebranch'
Your branch and 'origin/thebranch' have diverged,
and have 23 and 7 different commits each, respectively.
$ git reset --hard
HEAD is now at b05f611 Here the commit message bla, bla
$ git pull
Auto-merging thefile1.c
CONFLICT (content): Merge conflict in thefile1.c
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.
and so on...
To really start over, downloading thebranch and overwriting all your local changes, just do:
$ git checkout thebranch
$ git reset --hard origin/thebranch
This will work just fine.
$ git checkout thebranch
Already on 'thebranch'
Your branch and 'origin/thebranch' have diverged,
and have 23 and 7 different commits each, respectively.
$ git reset --hard origin/thebranch
HEAD is now at 7639058 Here commit message again...
$ git status
# On branch thebranch
nothing to commit (working directory clean)
$ git checkout thebranch
Already on 'thebranch'
There are differences and constraints in options offered by @Steve C and @ashosborne1. They must be specified, I believe.
When can we can use: File resourcesDirectory = new File("src/test/resources");
?
IntelliJ IDEA
only, but I think all IDEs work like this. And this configuration that must be done manually, is not good at all. Working with several tests existing in different maven projects, but imported into one big “IDE” project, force us to remember this and don’t allow to relax and get pleasure from your work.Solution offered by @ashosborne1 (personally I prefer this one) requires 2 additional requirements that must be done before you run tests. Here is a list of steps to use this solution:
Create a test folder (“teva”) and file (“readme”) inside of “src/test/resources/”:
src/test/resources/teva/readme
File must be created in the test folder, otherwise, it will not work. Maven ignores empty folders.
At least once build project via mvn clean install
. It will run tests also. It may be enough to run only your test class/method via maven without building a whole project. As a result your test resources will be copied into test-classes, here is a path: target/test-classes/teva/readme
After that, you can access the folder using code, already offered by @ashosborne1 (I'm sorry, that I could not edit this code inside of this list of items correctly):
public static final String TEVA_FOLDER = "teva"; ... URL tevaUrl = YourTest.class.getClassLoader().getResource(TEVA_FOLDER); String tevaTestFolder = new File(tevaUrl.toURI()).getAbsolutePath();
Now you can run your test via IDE as many times as you want. Until you run mvn clean. It will drop the target folder.
Creating file inside a test folder and running maven first time, before you run tests via IDE are needed steps. Without these steps, if you just in your IDE create test resources, then write test and run it via IDE only, you'll get an error. Running tests via mvn copies test resources into target/test-classes/teva/readme and they become accessible for a classloader.
You may ask, why do I need import more than one maven project in IDE and why so many complicated things? For me, one of the main motivation: keeping IDA-related files far from code. I first create a new project in my IDE. It is a fake project, that is just a holder of IDE-related files. Then, I import already existing maven projects. I force these imported projects to keep IDEA files in my original fake project only. As a result I don't see IDE-related files among the code. SVN should not see them (don't offer to configure svn/git to ignore such files, please). Also it is just very convenient.
The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).
The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.
On the server-side:
Alternative solution: the select element is in your case (only guessing) a single-choice form control and you could use a group of radio buttons instead. These you could then style with better control. If you have a select[@multiple] you could do the same with a group of checkboxes instead as they can both be seen as a multiple-choice form control.
4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:
Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:
Hope that helps.
In my case, the issue was unrelated to CORS since I was issuing a jQuery POST to the same web server. The data was JSON but I had omitted the dataType: 'json' parameter.
I did not have (nor did I add) a contentType parameter as shown in David Lopes' answer above.
In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray[] = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
You don't need a FK, you can join arbitrary columns.
But having a foreign key ensures that the join will actually succeed in finding something.
Foreign key give you certain guarantees that would be extremely difficult and error prone to implement otherwise.
For example, if you don't have a foreign key, you might insert a detail record in the system and just after you checked that the matching master record is present somebody else deletes it. So in order to prevent this you need to lock the master table, when ever you modify the detail table (and vice versa). If you don't need/want that guarantee, screw the FKs.
Depending on your RDBMS a foreign key also might improve performance of select (but also degrades performance of updates, inserts and deletes)
If the requested commit is in the pull requests of the remote repo, you can get it by its ID:
# Add the remote repo path, let's call it 'upstream':
git remote add upstream https://github.com/repo/project.git
# checkout the pull ID, for example ID '60':
git fetch upstream pull/60/head && git checkout FETCH_HEAD
None of the answers above works for me. The only (let's say) solution has been to change the first TextView in a disabled EditText that receives focus and then add
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
in the onCreate callback to prevent keyboard to be shown. Now my first EditText looks like a TextView but can get the initial focus, finally.
I also wanted to load any iframe inside modal window. What I did was, Created an iframe inside Modal and passing the source of target iframe to the iframe inside the modal.
function closeModal() {_x000D_
$('#modalwindow').hide();_x000D_
var modalWindow = document.getElementById('iframeModalWindow');_x000D_
modalWindow.src = "";_x000D_
}
_x000D_
.modal {_x000D_
z-index: 3;_x000D_
display: none;_x000D_
padding-top: 5%;_x000D_
padding-left: 5%;_x000D_
position: fixed;_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow: auto;_x000D_
background-color: rgb(51, 34, 34);_x000D_
background-color: rgba(0, 0, 0, 0.4)_x000D_
}
_x000D_
<!-- Modal Window -->_x000D_
<div id="modalwindow" class="modal">_x000D_
<div class="modal-header">_x000D_
<button type="button" style="margin-left:80%" class="close" onclick=closeModal()>×</button>_x000D_
</div>_x000D_
<iframe id="iframeModalWindow" height="80%" width="80%" src="" name="iframe_modal"></iframe>_x000D_
</div>
_x000D_
Still no print no native print function, but outside the installing the suggested package, you can go the autohotkey way, as the that app can actually help you run macros for other stuff as well. So you can do something like create a macro that with one click does:
No the most glamorous of options but could also work if the receiving app has can accept code-formatting.
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
console.log(arrayBuffer);_x000D_
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
You used Fruits.shift() method to first element remove . Fruits.pop() method used for last element remove one by one if you used button click. Fruits.slice( start position, delete element)You also used slice method for remove element in middle start.
const obj = { id: 1, name: 'Neel' };_x000D_
let str = '';_x000D_
str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');_x000D_
console.log(str);
_x000D_
Similar to OP without streams and libs, but conciser:
public <T> List<List<T>> getBatches(List<T> collection, int batchSize) {
List<List<T>> batches = new ArrayList<>();
for (int i = 0; i < collection.size(); i += batchSize) {
batches.add(collection.subList(i, Math.min(i + batchSize, collection.size())));
}
return batches;
}
The Magic
field of the IMAGE_OPTIONAL_HEADER
(though there is nothing optional about the header in Windows executable images (DLL/EXE files)) will tell you the architecture of the PE.
Here's an example of grabbing the architecture from a file.
public static ushort GetImageArchitecture(string filepath) {
using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
using (var reader = new System.IO.BinaryReader(stream)) {
//check the MZ signature to ensure it's a valid Portable Executable image
if (reader.ReadUInt16() != 23117)
throw new BadImageFormatException("Not a valid Portable Executable image", filepath);
// seek to, and read, e_lfanew then advance the stream to there (start of NT header)
stream.Seek(0x3A, System.IO.SeekOrigin.Current);
stream.Seek(reader.ReadUInt32(), System.IO.SeekOrigin.Begin);
// Ensure the NT header is valid by checking the "PE\0\0" signature
if (reader.ReadUInt32() != 17744)
throw new BadImageFormatException("Not a valid Portable Executable image", filepath);
// seek past the file header, then read the magic number from the optional header
stream.Seek(20, System.IO.SeekOrigin.Current);
return reader.ReadUInt16();
}
}
The only two architecture constants at the moment are:
0x10b - PE32
0x20b - PE32+
Cheers
UPDATE
It's been a while since I posted this answer, yet I still see that it gets a few upvotes now and again so I figured it was worth updating. I wrote a way to get the architecture of a Portable Executable
image, which also checks to see if it was compiled as AnyCPU
. Unfortunately the answer is in C++, but it shouldn't be too hard to port to C# if you have a few minutes to look up the structures in WinNT.h
. If people are interested I'll write a port in C#, but unless people actually want it I wont spend much time stressing about it.
#include <Windows.h>
#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))
typedef enum _pe_architecture {
PE_ARCHITECTURE_UNKNOWN = 0x0000,
PE_ARCHITECTURE_ANYCPU = 0x0001,
PE_ARCHITECTURE_X86 = 0x010B,
PE_ARCHITECTURE_x64 = 0x020B
} PE_ARCHITECTURE;
LPVOID GetOffsetFromRva(IMAGE_DOS_HEADER *pDos, IMAGE_NT_HEADERS *pNt, DWORD rva) {
IMAGE_SECTION_HEADER *pSecHd = IMAGE_FIRST_SECTION(pNt);
for(unsigned long i = 0; i < pNt->FileHeader.NumberOfSections; ++i, ++pSecHd) {
// Lookup which section contains this RVA so we can translate the VA to a file offset
if (rva >= pSecHd->VirtualAddress && rva < (pSecHd->VirtualAddress + pSecHd->Misc.VirtualSize)) {
DWORD delta = pSecHd->VirtualAddress - pSecHd->PointerToRawData;
return (LPVOID)MKPTR(pDos, rva - delta);
}
}
return NULL;
}
PE_ARCHITECTURE GetImageArchitecture(void *pImageBase) {
// Parse and validate the DOS header
IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)pImageBase;
if (IsBadReadPtr(pDosHd, sizeof(pDosHd->e_magic)) || pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
return PE_ARCHITECTURE_UNKNOWN;
// Parse and validate the NT header
IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
if (IsBadReadPtr(pNtHd, sizeof(pNtHd->Signature)) || pNtHd->Signature != IMAGE_NT_SIGNATURE)
return PE_ARCHITECTURE_UNKNOWN;
// First, naive, check based on the 'Magic' number in the Optional Header.
PE_ARCHITECTURE architecture = (PE_ARCHITECTURE)pNtHd->OptionalHeader.Magic;
// If the architecture is x86, there is still a possibility that the image is 'AnyCPU'
if (architecture == PE_ARCHITECTURE_X86) {
IMAGE_DATA_DIRECTORY comDirectory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
if (comDirectory.Size) {
IMAGE_COR20_HEADER *pClrHd = (IMAGE_COR20_HEADER*)GetOffsetFromRva(pDosHd, pNtHd, comDirectory.VirtualAddress);
// Check to see if the CLR header contains the 32BITONLY flag, if not then the image is actually AnyCpu
if ((pClrHd->Flags & COMIMAGE_FLAGS_32BITREQUIRED) == 0)
architecture = PE_ARCHITECTURE_ANYCPU;
}
}
return architecture;
}
The function accepts a pointer to an in-memory PE image (so you can choose your poison on how to get it their; memory-mapping or reading the whole thing into memory...whatever).
sometimes this can be a bogus error message, tried opening the file with the same account that it is running the process. I had the same issue in my environment and when I did open the file (with the same credentials running the process), it said that it must be associated with a known program, after I did that I was able to open it and run the process without any errors.
If you need getting the value from a select, you can use:
$form->get('nameSelect')->getClientData();
No there is not. Wikipedia has a nice article about this and provides an alternative using JavaScript and CSS: http://en.wikipedia.org/wiki/Blink_element
If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.
// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");
// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();
// Since it is private, make it accessible.
cons.setAccessible(true);
// Create new object.
Object obj = cons.newInstance();
This only works for classes that implement singleton pattern using a private constructor.
If you're using 0
and an empty string ''
and null
to designate undefined you've got a data problem. Just update the columns and fix your schema.
UPDATE pt.incentive_channel
SET pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';
This will make joining and selecting substantially easier moving forward.
jQuery.fn.doSomething = function() {
//return something with 'this'
};
$('selector:empty').doSomething();
Shortest path is to use scipy
, like this:
from scipy.misc import toimage
toimage(data).show()
This requires PIL or Pillow to be installed as well.
A similar approach also requiring PIL or Pillow but which may invoke a different viewer is:
from scipy.misc import imshow
imshow(data)
What you should do is to serialize your form data and send it to the controller action. ASP.NET MVC will bind the form data to the EditPostViewModel
object( your action method parameter), using MVC model binding feature.
You can validate your form at client side and if everything is fine, send the data to server. The valid()
method will come in handy.
$(function () {
$("#yourSubmitButtonID").click(function (e) {
e.preventDefault();
var _this = $(this);
var _form = _this.closest("form");
var isvalid = _form .valid(); // Tells whether the form is valid
if (isvalid)
{
$.post(_form.attr("action"), _form.serialize(), function (data) {
//check the result and do whatever you want
})
}
});
});
Laravel 5 and later
Controller
return redirect()->back()->with('success', 'your message,here');
Blade:
@if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
@endif
I did something like this:
from math import trunc
def truncate(number, decimals=0):
if decimals < 0:
raise ValueError('truncate received an invalid value of decimals ({})'.format(decimals))
elif decimals == 0:
return trunc(number)
else:
factor = float(10**decimals)
return trunc(number*factor)/factor
The ===
is not for checking string equalit , to do so you can use the Regxp functions for example
if (x.match(y) === null) {
// x and y are not equal
}
there is also the test
function
Wrap it in <pre>
tags to preserve formatting.
I am also still figuring out the internals of git, and have figured out this so far:
% cat .git/HEAD
ref: refs/heads/master
% cat .git/refs/heads/master
cbf01a8e629e8d884888f19ac203fa037acd901f
% cat .git/HEAD
8e2c815f83231f85f067f19ed49723fd1dc023b7
This is called a detached HEAD. The remote master is ahead of your local master. When you do git submodule --remote myrepo to get the latest commit of your submodule, it will by default do a checkout, which will update HEAD. Since your current branch master is behind, HEAD becomes 'detached' from your current branch, so to speak.
According to Cormen et al. Introduction to Algorithms (Appendix B.5.3), the depth of a node X in a tree T is defined as the length of the simple path (number of edges) from the root node of T to X. The height of a node Y is the number of edges on the longest downward simple path from Y to a leaf. The height of a tree is defined as the height of its root node.
Note that a simple path is a path without repeat vertices.
The height of a tree is equal to the max depth of a tree. The depth of a node and the height of a node are not necessarily equal. See Figure B.6 of the 3rd Edition of Cormen et al. for an illustration of these concepts.
I have sometimes seen problems asking one to count nodes (vertices) instead of edges, so ask for clarification if you're not sure you should count nodes or edges during an exam or a job interview.
this is the updated answer for WAMP v3.0.6
UPDATE mysql.user
SET authentication_string=PASSWORD('MyNewPass')
WHERE user='root';
FLUSH PRIVILEGES;
Access the database as the administrator user (root maybe).
Check current SQL_mode
mysql> SELECT @@sql_mode;
To set a new sql_mode, exit the database, create a file
nano /etc/mysql/conf.d/<filename>.cnf
with your sql_mode content
[mysqld]
sql_mode=NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Restart Mysql
mysql> sudo service mysql stop
mysql> sudo service mysql start
We create a file in the folder /etc/mysql/conf.d/ because in the main config file /etc/mysql/my.cnf the command is written to include all the settings files from the folder /etc/mysql/conf.d/
What? From 2010 and nobody mentioned Ruby has a fine for /in loop (it's just nobody uses it):
ar = [1,2,3,4,5,6]
for item in ar
puts item
end
I had a similar problem just now!
You can use the filter_input()
function with FILTER_VALIDATE_INT
and FILTER_NULL_ON_FAILURE
to filter only integer values out of the $_GET
variable. Works pretty accurately! :)
Check out my question here: How to check whether a variable in $_GET Array is an integer?
You call tarfile.open with mode='w:gz'
, meaning "Open for gzip compressed writing."
You'll probably want to end the filename (the name
argument to open
) with .tar.gz
, but that doesn't affect compression abilities.
BTW, you usually get better compression with a mode of 'w:bz2'
, just like tar
can usually compress even better with bzip2
than it can compress with gzip
.
The closest you can get is typeof
, but it only returns "object" for any sort of custom type. For those, see Jason Bunting.
Edit, Jason's deleted his post for some reason, so just use Object's constructor
property.
Filezilla just released a Pro version of their FTP client. It connects to S3 buckets in a streamlined FTP like experience. I use it myself (no affiliation whatsoever) and it works great.
One Short Answere is:
For a number, it is tricky because if a numeric cell is empty
VBA will assign a default value of 0 to it, so it is hard for your VBA code to tell the difference between an entered zero and a blank numeric cell.
The following check worked for me to see if there was an actual 0 entered into the cell:
If CStr(rng.value) = "0" then
'your code here'
End If
Update for the new 64bit arch
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -9223372036854775808
LONG_MAX: 9223372036854775807
ULONG_MAX: 18446744073709551615
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
Update:
I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.
I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.
There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com
The best which i have got: Include in your js file and for including views you can add in this way
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">_x000D_
<meta http-equiv="x-ua-compatible" content="ie=edge">_x000D_
<title>Bootstrap</title>_x000D_
<!-- Your custom styles (optional) -->_x000D_
<link href="css/style_different.css" rel="stylesheet">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<script src="https://www.w3schools.com/lib/w3data.js"></script>_x000D_
<div class="">_x000D_
<div w3-include-html="templates/header.html"></div>_x000D_
<div w3-include-html="templates/dashboard.html"></div>_x000D_
<div w3-include-html="templates/footer.html"></div>_x000D_
</div>_x000D_
</body>_x000D_
<script type="text/javascript">_x000D_
w3IncludeHTML();_x000D_
</script>_x000D_
</html>
_x000D_
If your data is already in your database you can do:
INSERT INTO MyTable(ID, Name)
SELECT ID, NAME FROM OtherTable
If you need to hard code the data then SQL 2008 and later versions let you do the following...
INSERT INTO MyTable (Name, ID)
VALUES ('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)
Execute
is sql*plus syntax .. try wrapping your call in begin .. end like this:
begin
temp_proc;
end;
(Although Jeffrey says this doesn't work in APEX .. but you're trying to get this to run in SQLDeveloper .. try the 'Run' menu there.)
To handle this use case, you can use the <ImageBackground>
component, which has the same props as <Image>
, and add whatever children to it you would like to layer on top of it.
Example:
return (
<ImageBackground source={...} style={{width: '100%', height: '100%'}}>
<Text>Inside</Text>
</ImageBackground>
);
For more: ImageBackground | React Native
Note that you must specify some width and height style attributes.
A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.
Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.
def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...
If GUID collisions are a concern, I would recommend using the ScottGuID instead.
ArrayList
LinkedList:-
Now coming to your questions:-
1) ArrayList saves data according to indexes and it implements RandomAccess interface which is a marker interface that provides the capability of a Random retrieval to ArrayList but LinkedList doesn't implements RandomAccess Interface that's why ArrayList is faster than LinkedList.
2) The underlying data structure for LinkedList is doubly linked list so insertion and deletion in the middle is very easy in LinkedList as it doesn't have to shift each and every element for each and every deletion and insertion operations just like ArrayList(which is not recommended if our operation is insertion and deletion in the middle because internally several shift operations are performed).
Source
If you design query using the Query editor in SQL Server 2012 for example you would get this:
SELECT e.EmployeeID, s.CompanyName, o.ShipName
FROM Employees AS e INNER JOIN
Orders AS o ON e.EmployeeID = o.EmployeeID INNER JOIN
Shippers AS s ON o.ShipVia = s.ShipperID
WHERE (s.CompanyName = 'Federal Shipping')
However removing the AS does not make any difference as in the following:
SELECT e.EmployeeID, s.CompanyName, o.ShipName
FROM Employees e INNER JOIN
Orders o ON e.EmployeeID = o.EmployeeID INNER JOIN
Shippers s ON o.ShipVia = s.ShipperID
WHERE (s.CompanyName = 'Federal Shipping')
In this case use of AS is superfluous but in many other places it is needed.
Command line:
npm init
will create package.json file
To install , update and uninstall packages under dependencies into package.json file:
Command line :
npm install <pkg>@* --save
will automatically add the latest version for the package under dependencies into package.json file
EX:
npm install node-markdown@* --save
Command line:
npm install <pkg> --save
also will automatically add the latest version for the package under dependencies into package.json file
if you need specific version for a package use this Command line:
npm install <pkg>@<version> --save
will automatically add specific version of package under dependencies into package.json file
EX:
npm install [email protected] --save
if you need specific range of version for a package use this Command line:
npm install <pkg>@<version range>
will automatically add the latest version for the package between range of version under dependencies into package.json file
EX:
npm install koa-views@">1.0.0 <1.2.0" --save
For more details about how to write version for package npm Doc
Command line:
npm update --save
will update packages into package.json file and will automatically add updated version for all packages under dependencies into package.json file
Command line:
npm uninstall <pkg> --save
will automatically remove package from dependencies into package.json file and remove package from node_module folder
public List<Requirement> listInquiryLogged()
{
using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
var result = from Q in dt.Requirements
where inq.Contains(Q.ID)
orderby Q.Description
select Q;
return result.ToList<Requirement>();
}
}
"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.
GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html
If you want to add a default value for the already created column, this works for me:
ALTER TABLE Persons
ALTER credit SET DEFAULT 0.0;
I had the same error. I checked the error logs: C:\ProgramData\MySQL\MySQL Server 5.5\data\inf3rno-PC.err
. According to them
170208 1:06:25 [Note] C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld: Shutdown complete
170208 1:10:44 [Note] Plugin 'FEDERATED' is disabled.
170208 1:10:44 InnoDB: The InnoDB memory heap is disabled
170208 1:10:44 InnoDB: Mutexes and rw_locks use Windows interlocked functions
170208 1:10:44 InnoDB: Compressed tables use zlib 1.2.3
170208 1:10:44 InnoDB: Error: unable to create temporary file; errno: 2
170208 1:10:44 [ERROR] Plugin 'InnoDB' init function returned error.
170208 1:10:44 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
170208 1:10:44 [ERROR] Unknown/unsupported storage engine: INNODB
170208 1:10:44 [ERROR] Aborting
I think the important part here
170208 1:10:44 InnoDB: Error: unable to create temporary file; errno: 2
I changed the TMP
and TEMP
env variables from C:\Windows\Temp
to %USERPROFILE%\AppData\Local\Temp
yesterday, because I was unable to compress a directory and according to many post the solution is that. Now compression works, but mysql and apparently nod32 complains that they cannot create temporary files...
I added tmpdir=c:/server/mytmp
to C:\Program Files\MySQL\MySQL Server 5.5\my.ini
. And after that started the service again with services.msc. It is okay now.
So this can be a possible cause as well. I strongly suggest to everybody encountering this problem to check the error logs.
import java.util.List;
import java.util.ArrayList;
import static java.lang.System.out;
import lombok.Setter;
import lombok.Getter;
import java.awt.Color;
public class Deck {
private static @Getter List<Card> deck = null;
final int SUIT_COUNT = 4;
final int VALUE_COUNT = 13;
public Deck() {
deck = new ArrayList<>();
Card card = null;
int suitIndex = 0, valueIndex = 0;
while (suitIndex < SUIT_COUNT) {
while (valueIndex < VALUE_COUNT) {
card = new Card(Suit.values()[suitIndex], FaceValue.values()[valueIndex]);
valueIndex++;
deck.add(card);
}
valueIndex = 0;
suitIndex++;
}
}
private enum Suit{CLUBS("Clubs", Color.BLACK), DIAMONDS("Diamonds", Color.RED),HEARTS("Hearts", Color.RED), SPADES("Spades", Color.BLACK);
private @Getter String name = null;
private @Getter Color color = null;
Suit(String name) {
this.name = name;
}
Suit(String name, Color color) {
this.name = name;
this.color = color;
}
}
private enum FaceValue{ACE(1), TWO(2), THREE(3),
FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT (8), NINE(9), TEN(10),
JACK(11), QUEEN(12), KING(13);
private @Getter int cardValue = 0;
FaceValue(int value) {
this.cardValue = value;
}
}
private class Card {
private @Getter @Setter Suit suit = null;
private @Getter @Setter FaceValue faceValue = null;
Card(Suit suit, FaceValue value) {
this.suit = suit;
this.faceValue = value;
}
public String toString() {
return getSuit() + " " + getFaceValue();
}
public String properties() {
return getSuit().getName() + " " + getFaceValue().getCardValue();
}
}
public static void main(String...inputs) {
Deck deck = new Deck();
List<Card> cards = deck.getDeck();
cards.stream().filter(card -> card.getSuit().getColor() != Color.RED && card.getFaceValue().getCardValue() > 4).map(card -> card.toString() + " " + card.properties()).forEach(out::println);
}
}
In my case the solution was stupid: I just had incorrect dependency versions.
The other answers provided will not include files or directories that start with a . the following worked for me:
#/bin/sh
getAll()
{
local fl1="$1"/*;
local fl2="$1"/.[!.]*;
local fl3="$1"/..?*;
for inpath in "$1"/* "$1"/.[!.]* "$1"/..?*; do
if [ "$inpath" != "$fl1" -a "$inpath" != "$fl2" -a "$inpath" != "$fl3" ]; then
stat --printf="%F\0%n\0\n" -- "$inpath";
if [ -d "$inpath" ]; then
getAll "$inpath"
#elif [ -f $inpath ]; then
fi;
fi;
done;
}
There are several tools for converting Matlab to Python code.
The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).
Other options include:
Also, for those interested in an interface between the two languages and not conversion:
pymatlab
: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.pymat2
: continuation of the seemingly abandoned PyMat.mlabwrap
, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).oct2py
: run GNU Octave commands from within Python.pymex
: Embeds the Python Interpreter in Matlab, also on File Exchange.matpy
: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).Btw might be helpful to look here for other migration tips:
On a different note, though I'm not a fortran
fan at all, for people who might find it useful there is:
If you don't want to add a new column, and you can guarantee that your current int column is unique, you could select all of the data out into a temporary table, drop the table and recreate with the IDENTITY column specified. Then using SET IDENTITY INSERT ON
you can insert all of your data in the temporary table into the new table.
Make sure that the all tables can support foreign key - InnoDB engine
Above are great answers. Here is an easy way to remember this:
a is a pointer
*a is the value
Now if you say "const a" then the pointer is const. (i.e. char * const a;)
If you say "const *a" then the value is const. (i.e. const char * a;)
Take a look here,
html file
<div class='progress' id="progress_div">
<div class='bar' id='bar1'></div>
<div class='percent' id='percent1'></div>
</div>
<div id="wrapper">
<div id="content">
<h1>Display Progress Bar While Page Loads Using jQuery<p>TalkersCode.com</p></h1>
</div>
</div>
js file
document.onreadystatechange = function(e) {
if (document.readyState == "interactive") {
var all = document.getElementsByTagName("*");
for (var i = 0, max = all.length; i < max; i++) {
set_ele(all[i]);
}
}
}
function check_element(ele) {
var all = document.getElementsByTagName("*");
var totalele = all.length;
var per_inc = 100 / all.length;
if ($(ele).on()) {
var prog_width = per_inc + Number(document.getElementById("progress_width").value);
document.getElementById("progress_width").value = prog_width;
$("#bar1").animate({
width: prog_width + "%"
}, 10, function() {
if (document.getElementById("bar1").style.width == "100%") {
$(".progress").fadeOut("slow");
}
});
} else {
set_ele(ele);
}
}
function set_ele(set_element) {
check_element(set_element);
}
it definitely solve your problem for complete tutorial here is the link http://talkerscode.com/webtricks/display-progress-bar-while-page-loads-using-jquery.php
Checkout this working Plunker
<select (change)="onItemChange($event.target.value)">
<option *ngFor="#value of values" [value]="value.key">{{value.value}}</option>
</select>
The DatePicker class has methods for getting the month, year, day of month. Or you can use an OnDateChangedListener.
by_type_year_tag_filtered <- by_type_year_tag %>%
dplyr:: filter(tag_name %in% c("dplyr", "ggplot2"))
So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".
Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row
SELECT t.chargeId, t.chargeType, t.serviceMonth FROM(
SELECT chargeId,MAX(serviceMonth) AS serviceMonth
FROM invoice
GROUP BY chargeId) x
JOIN invoice t ON x.chargeId =t.chargeId
AND x.serviceMonth = t.serviceMonth
The code could be cleaner, but this seems to do the trick for different locales.
import java.math.BigDecimal;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class Main
{
public static void main(String[] args)
{
final BigDecimal numberA;
final BigDecimal numberB;
numberA = stringToBigDecimal("1,000,000,000.999999999999999", Locale.CANADA);
numberB = stringToBigDecimal("1.000.000.000,999999999999999", Locale.GERMANY);
System.out.println(numberA);
System.out.println(numberB);
}
private static BigDecimal stringToBigDecimal(final String formattedString,
final Locale locale)
{
final DecimalFormatSymbols symbols;
final char groupSeparatorChar;
final String groupSeparator;
final char decimalSeparatorChar;
final String decimalSeparator;
String fixedString;
final BigDecimal number;
symbols = new DecimalFormatSymbols(locale);
groupSeparatorChar = symbols.getGroupingSeparator();
decimalSeparatorChar = symbols.getDecimalSeparator();
if(groupSeparatorChar == '.')
{
groupSeparator = "\\" + groupSeparatorChar;
}
else
{
groupSeparator = Character.toString(groupSeparatorChar);
}
if(decimalSeparatorChar == '.')
{
decimalSeparator = "\\" + decimalSeparatorChar;
}
else
{
decimalSeparator = Character.toString(decimalSeparatorChar);
}
fixedString = formattedString.replaceAll(groupSeparator , "");
fixedString = fixedString.replaceAll(decimalSeparator , ".");
number = new BigDecimal(fixedString);
return (number);
}
}
The parseInt
function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:
var digit = parseInt(binary, 2);
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users
is a PDOStatement
object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach
is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch
will return false
, since you have already exhausted the result set (see above), so you get an error trying to loop over false
.
In the last example you are simply fetching the first result row and are looping over it.
Just change the directory to another one and come back. Probably that one has been deleted or moved.
You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct()
you'll get an error).
Therefore you'd have to create an initialize()
function and call it in each method:
<?php
class Hello
{
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
I think this solves
using System.Linq;
(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))
if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";
$status = file_put_contents($path,base64_decode($image));
if($status){
echo "Successfully Uploaded";
}else{
echo "Upload failed";
}
}
This may not apply to many of you, but I'm usually operating my computers under Linux, so by default I save my matplotlib plots as PNG and SVG. This works fine under Linux but is unbearably slow on my Windows 7 installations [MiKTeX under Python(x,y) or Anaconda], so I've taken to adding this code, and things work fine over there again:
import platform # Don't save as SVG if running under Windows.
#
# Plot code goes here.
#
fig.savefig('figure_name.png', dpi = 200)
if platform.system() != 'Windows':
# In my installations of Windows 7, it takes an inordinate amount of time to save
# graphs as .svg files, so on that platform I've disabled the call that does so.
# The first run of a script is still a little slow while everything is loaded in,
# but execution times of subsequent runs are improved immensely.
fig.savefig('figure_name.svg')
Sometimes you get the error because the destination location in phone are not exist. For example, some android phone external storage location is /storage/emulated/legacy
instead of /storage/emulated/0
.
On WebStorm 2016.3
Press ALT+F12 (open terminal)
Run this command:
npm install require.js
Usage
char str[50] = {0};
strcpy(str, (char*)"My name is Khan");
reverseWords(str);
Method
void reverseWords(char* pString){
if(NULL ==pString){
return;
}
int nLen = strlen(pString);
reverseString(pString,nLen);
char* start = pString;
char* end = pString;
nLen = 0;
while (*end) {
if(*end == ' ' ){
reverseString(start,nLen);
end++;
start = end;
nLen = 0;
continue;
}
nLen++;
end++;
}
reverseString(start,nLen);
printf("\n Reversed: %s",pString);
}
void reverseString(char* start,int nLen){
char* end = start+ nLen-1;
while(nLen > 0){
char temp = *start;
*start = *end;
*end = temp;
end--;
start++;
nLen-=2;
}
}
select CONVERT(date,DATEADD(dd,-(DATEPART(dd,getdate())-1),getdate()),120)
This function will provide you date part of start date of the month
Time for an update! Create an inline (.inl, or probably any other) file and simply copy all your definitions in it. Be sure to add the template above each function (template <typename T, ...>
). Now instead of including the header file in the inline file you do the opposite. Include the inline file after the declaration of your class (#include "file.inl"
).
I don't really know why no one has mentioned this. I see no immediate drawbacks.
You have at least these 3 issues:
display
yet in your javascript you attempt to get element myDiv
which is not even defined in your markup.You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.
You can use assign
(doc) to change the value of perf.a1:
> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5
Update:
This feature is now part of the proplot matplotlib package that I recently released on pypi. By default, when you make figures, the labels are "shared" between axes.
Original answer:
I discovered a more robust method:
If you know the bottom
and top
kwargs that went into a GridSpec
initialization, or you otherwise know the edges positions of your axes in Figure
coordinates, you can also specify the ylabel position in Figure
coordinates with some fancy "transform" magic. For example:
import matplotlib.transforms as mtransforms
bottom, top = .1, .9
f, a = plt.subplots(nrows=2, ncols=1, bottom=bottom, top=top)
avepos = (bottom+top)/2
a[0].yaxis.label.set_transform(mtransforms.blended_transform_factory(
mtransforms.IdentityTransform(), f.transFigure # specify x, y transform
)) # changed from default blend (IdentityTransform(), a[0].transAxes)
a[0].yaxis.label.set_position((0, avepos))
a[0].set_ylabel('Hello, world!')
...and you should see that the label still appropriately adjusts left-right to keep from overlapping with ticklabels, just like normal -- but now it will adjust to be always exactly between the desired subplots.
Furthermore, if you don't even use set_position
, the ylabel will show up by default exactly halfway up the figure. I'm guessing this is because when the label is finally drawn, matplotlib
uses 0.5 for the y
-coordinate without checking whether the underlying coordinate transform has changed.
First, you're using the modifiers under an incorrect assumption.
Pattern.MULTILINE
or (?m)
tells Java to accept the anchors ^
and $
to match at the start and end of each line (otherwise they only match at the start/end of the entire string).
Pattern.DOTALL
or (?s)
tells Java to allow the dot to match newline characters, too.
Second, in your case, the regex fails because you're using the matches()
method which expects the regex to match the entire string - which of course doesn't work since there are some characters left after (\\W)*(\\S)*
have matched.
So if you're simply looking for a string that starts with User Comments:
, use the regex
^\s*User Comments:\s*(.*)
with the Pattern.DOTALL
option:
Pattern regex = Pattern.compile("^\\s*User Comments:\\s+(.*)", Pattern.DOTALL);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group(1);
}
ResultString
will then contain the text after User Comments:
The best choice is to alter the column and remove the auto_increment attribute. Then issue another alter statement and put auto_increment back onto the column. This will reset the count to the max+1 of the current rows and thus preserve foreign key references back to this table, from other tables in your database, or any other key usage for that column.
I recently discovered a project called OniVim, which is an electron-based front-end for NeoVim that comes with very nice autocomplete for several languages out of the box, and since it's basically just a wrapper around NeoVim, you have the full power of vim at your disposal if the GUI doesn't meet your needs. It's still in early development, but it is rapidly improving and there is a really active community around it. I have been using vim for over 10 years and started giving Oni a test drive a few weeks ago, and while it does have some bugs here and there it hasn't gotten in my way. I would strongly recommend it to new vim users who are still getting their vim-fingers!
OniVim: https://www.onivim.io/
I would recommend creating a TNSNAMES.ORA file. From your Oracle Client install directory, navigate to NETWORK\ADMIN. You may already have a file called TNSNAMES.ORA, if so edit it, else create it using your favorite text editor.
Next, simply add an entry like this:
MYDB =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521))
(CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED))
)
You can change MYDB to whatever you like, this is the identifier that applications will will use to find the database using the info from TNSNAMES.
Finally, login with MYDB as your database in PL/SQL Developer. It should automatically find the connection string in the TNSNAMES.ORA.
If that does not work, hit Help->About then click the icon with an "i" in it in the upper-lefthand corner. The fourth tab is the "TNS Names" tab, check it to confirm that it is loading the proper TNSNAMES.ORA file. If it is not, you may have multiple Oracle installations on your computer, and you will need to find the one that is in use.
Easier way to do it in one line of code
this.setState({ object: { ...this.state.object, objectVarToChange: newData } })
After I change the password for my "root" in phpMyAdmin page, I had a same problem and also looking for the solutions from the internet but fail to get the answer I needed, so I check the documentation inside the phpMyAdmin directory.
Go to and edit the file
\modules\phpmyadmin414x140123114237\config.sample.inc.php
look for line
$cfg['Servers'][$i]['auth_type'] = 'config'
and change the 'config' to 'http' and that will allow you to type the user name and password when you go to your phpMyAdmin page using your browser.
OR
see the documentation file under the same phpMyAdmin directory (phpmyadmin414x140123114237\doc\html
) for help and search for $cfg['Servers'][$i]['auth_type']
and you will see 4 options to choose from as to how to login to your phpMyAdmin page.
I use a generic class to store the enum/description pairs and a nested helper class to get the description.
The enum:
enum Status { Success, Fail, Pending }
The generic class:
Note: Since a generic class cannot be constrained by an enum I am constraining by struct instead and checking for enum in the constructor.
public class EnumX<T> where T : struct
{
public T Code { get; set; }
public string Description { get; set; }
public EnumX(T code, string desc)
{
if (!typeof(T).IsEnum) throw new NotImplementedException();
Code = code;
Description = desc;
}
public class Helper
{
private List<EnumX<T>> codes;
public Helper(List<EnumX<T>> codes)
{
this.codes = codes;
}
public string GetDescription(T code)
{
EnumX<T> e = codes.Where(c => c.Code.Equals(code)).FirstOrDefault();
return e is null ? "Undefined" : e.Description;
}
}
}
Usage:
EnumX<Status>.Helper StatusCodes = new EnumX<Status>.Helper(new List<EnumX<Status>>()
{
new EnumX<Status>(Status.Success,"Operation was successful"),
new EnumX<Status>(Status.Fail,"Operation failed"),
new EnumX<Status>(Status.Pending,"Operation not complete. Please wait...")
});
Console.WriteLine(StatusCodes.GetDescription(Status.Pending));
You should look at the documentation for the Action method; it's explained well. For your case, this should work:
@Html.Action("GetOptions", new { pk="00", rk="00" });
The controllerName
parameter will default to the controller from which Html.Action
is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:
@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });
I got this exception too. MY error code is below
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
connection.setRequestProperty("Content-type", "JSON");
I found "Content-type" should not be "JSON",is wrong! I solved this exception by update this line to below
connection.setRequestProperty("Content-type", "application/json");
you can check up your "Content-type"
Or, if you want a more general approach - i.e. for nesting up to "levelN":
void Main()
{
XElement rootElement = XElement.Load(@"c:\events\test.xml");
Console.WriteLine(GetOutline(0, rootElement));
}
private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
Similar with Bozho above. You can do some workaround here (although i myself don't like it) through this method :
public <T> List<T> convert(List list, T t){
return list;
}
Yes. It will cast your list into your demanded generic type.
In the given case above, you can do some code like this :
List<Object> list = getList();
return convert(list, new Customer());
MDN suggests that there's a much cleaner way of doing this in modern browsers:
// Assuming we're listening for e.g. a 'change' event on `element`
// Create a new 'change' event
var event = new Event('change');
// Dispatch it.
element.dispatchEvent(event);
import os
source = ['test_sound.flac','ts.mp3']
for files in source:
fileName,fileExtension = os.path.splitext(files)
print fileExtension # Print File Extensions
print fileName # It print file name
Thanks to great Mark Amery's answer I devised function to account for all possible ISO formats of datetime:
class FixedOffset(tzinfo):
"""Fixed offset in minutes: `time = utc_time + utc_offset`."""
def __init__(self, offset):
self.__offset = timedelta(minutes=offset)
hours, minutes = divmod(offset, 60)
#NOTE: the last part is to remind about deprecated POSIX GMT+h timezones
# that have the opposite sign in the name;
# the corresponding numeric value is not used e.g., no minutes
self.__name = '<%+03d%02d>%+d' % (hours, minutes, -hours)
def utcoffset(self, dt=None):
return self.__offset
def tzname(self, dt=None):
return self.__name
def dst(self, dt=None):
return timedelta(0)
def __repr__(self):
return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)
def __getinitargs__(self):
return (self.__offset.total_seconds()/60,)
def parse_isoformat_datetime(isodatetime):
try:
return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S.%f')
except ValueError:
pass
try:
return datetime.strptime(isodatetime, '%Y-%m-%dT%H:%M:%S')
except ValueError:
pass
pat = r'(.*?[+-]\d{2}):(\d{2})'
temp = re.sub(pat, r'\1\2', isodatetime)
naive_date_str = temp[:-5]
offset_str = temp[-5:]
naive_dt = datetime.strptime(naive_date_str, '%Y-%m-%dT%H:%M:%S.%f')
offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:])
if offset_str[0] == "-":
offset = -offset
return naive_dt.replace(tzinfo=FixedOffset(offset))
Actually got the same problem. For me worked this easy way:
Adding the data to a Datatable
and sort it:
dt.DefaultView.Sort = "columnname";
dt = dt.DefaultView.ToTable();
If you use .NET as your middle tier, check the route attribute clearly, for example,
I had issue when it was like this,
[Route("something/{somethingLong: long}")] //Space.
Fixed it by this,
[Route("something/{somethingLong:long}")] //No space
Below code will only print files within directory and exclude directories within given directory while traversing.
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
DIR *d;
struct dirent *dir;
char path[1000]="/home/joy/Downloads";
d = opendir(path);
char full_path[1000];
if (d)
{
while ((dir = readdir(d)) != NULL)
{
//Condition to check regular file.
if(dir->d_type==DT_REG){
full_path[0]='\0';
strcat(full_path,path);
strcat(full_path,"/");
strcat(full_path,dir->d_name);
printf("%s\n",full_path);
}
}
closedir(d);
}
return(0);
}
I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.
The code below was simplyfied.
List<SelectListItem> items = new List<SelectListItem>();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("Texto", "1");
dictionary.Add("Foto", "2");
dictionary.Add("Vídeo", "3");
foreach (KeyValuePair<string, string> pair in objBLL.GetTiposPost())
{
items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });
}
ViewBag.TiposPost = new SelectList(items, "Value", "Text");
In the View, I used a foreach to build a radiobutton.
<div class="form-group">
<div class="col-sm-10">
@foreach (var item in (SelectList)ViewBag.TiposPost)
{
@Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false)
<label class="control-label">@item.Text</label>
}
</div>
</div>
Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.
Hope it's useful!
Here is a Perl script that will:
The script:
my $svn_repo = "/var/svn";
my $bkup_dir = "/home/backup_user/backups";
my $bkup_file = "my_backup-";
my $tmp_dir = "/home/backup_user/tmp";
my $bkup_svr = "my.backup.com";
my $bkup_svr_login = "backup";
$bkup_file = $bkup_file . `date +%Y%m%d-%H%M`;
chomp $bkup_file;
my $youngest = `svnlook youngest $svn_repo`;
chomp $youngest;
my $dump_command = "svnadmin -q dump $svn_repo > $bkup_dir/$bkup_file ";
print "\nDumping Subversion repo $svn_repo to $bkup_file...\n";
print `$dump_command`;
print "Backing up through revision $youngest... \n";
print "\nCompressing dump file...\n";
print `gzip -9 $bkup_dir/$bkup_file\n`;
chomp $bkup_file;
my $zipped_file = $bkup_dir . "/" . $bkup_file . ".gz";
print "\nCreated $zipped_file\n";
print `scp $zipped_file $bkup_svr_login\@$bkup_svr:/home/backup/`;
print "\n$bkup_file.gz transfered to $bkup_svr\n";
#Test Backup
print "\n---------------------------------------\n";
print "Testing Backup";
print "\n---------------------------------------\n";
print "Downloading $bkup_file.gz from $bkup_svr\n";
print `scp $bkup_svr_login\@$bkup_svr:/home/backup/$bkup_file.gz $tmp_dir/`;
print "Unzipping $bkup_file.gz\n";
print `gunzip $tmp_dir/$bkup_file.gz`;
print "Creating test repository\n";
print `svnadmin create $tmp_dir/test_repo`;
print "Loading repository\n";
print `svnadmin -q load $tmp_dir/test_repo < $tmp_dir/$bkup_file`;
print "Checking out repository\n";
print `svn -q co file://$tmp_dir/test_repo $tmp_dir/test_checkout`;
print "Cleaning up\n";
print `rm -f $tmp_dir/$bkup_file`;
print `rm -rf $tmp_dir/test_checkout`;
print `rm -rf $tmp_dir/test_repo`;
Script source and more details about the rational for this type of backup.
if (typeof console != "undefined") {
...
}
Or better
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
Works in all browsers
Sort by picture and then by activity:
SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;
I know this is an older question, but I thought I would also post my solution:
Here is an example of one method of including a custom filter in a Spring Boot MVC application. Be sure to include the package in a component scan:
package com.dearheart.gtsc.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
public class XClacksOverhead implements Filter {
public static final String X_CLACKS_OVERHEAD = "X-Clacks-Overhead";
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader(X_CLACKS_OVERHEAD, "GNU Terry Pratchett");
chain.doFilter(req, res);
}
@Override
public void destroy() {}
@Override
public void init(FilterConfig arg0) throws ServletException {}
}
Add something like this to lib/__init__.py
from .helperclass import Helper
now you can import it directly:
from lib import Helper
One of alternatives is MSYS2 , in another words "MinGW-w64"/Git Bash. You can simply ssh to Unix machines and run most of linux commands from it. Also install tmux!
To install tmux in MSYS2:
run command pacman -S tmux
To run tmux on Git Bash:
install MSYS2 and copy tmux.exe
and msys-event-2-1-6.dll
from MSYS2 folder C:\msys64\usr\bin
to your Git Bash directory C:\Program Files\Git\usr\bin
.
This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.
I was looking for a general way of adding a column of numpy.nan
s to a dataframe without getting the dumb SettingWithCopyWarning
.
From the following:
numpy
array of NaNs in-lineI came up with this:
col = 'column_name'
df = df.assign(**{col:numpy.full(len(df), numpy.nan)})
For me.
Edit .gitattributes file.
add
*.dll binary
Then everything goes well.
Depends on the language and most likely its compiler, but they should be equivalent in most languages.
something like:
p
{
display:inline;
}
in your stylesheet would do it for all p tags.
Why not just target the ones you want (demo)?
$('form').find('input[type=text],textarea,select').filter(':visible:first');
Edit
Or use jQuery :input selector to filter form descendants.
$('form').find('*').filter(':input:visible:first');
I took Kashif's answer and union'd all of them together. Strangely, sometimes, I found results in one of the selects but not the other. So to be safe, I run all 3 when I'm looking for something. Hope this helps:
DECLARE @SearchText varchar(1000) = 'mytext';
SELECT DISTINCT SPName
FROM (
(SELECT ROUTINE_NAME SPName
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%' + @SearchText + '%'
AND ROUTINE_TYPE='PROCEDURE')
UNION ALL
(SELECT OBJECT_NAME(id) SPName
FROM SYSCOMMENTS
WHERE [text] LIKE '%' + @SearchText + '%'
AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id))
UNION ALL
(SELECT OBJECT_NAME(object_id) SPName
FROM sys.sql_modules
WHERE OBJECTPROPERTY(object_id, 'IsProcedure') = 1
AND definition LIKE '%' + @SearchText + '%')
) AS T
ORDER BY T.SPName
In software engineering, multi-tier architecture (often referred to as n-tier architecture) is a client-server architecture in which, the presentation, the application processing and the data management are logically separate processes. For example, an application that uses middleware to service data requests between a user and a database employs multi-tier architecture. The most widespread use of "multi-tier architecture" refers to three-tier architecture.
It's debatable what counts as "tiers," but in my opinion it needs to at least cross the process boundary. Or else it's called layers. But, it does not need to be in physically different machines. Although I don't recommend it, you can host logical tier and database on the same box.
Edit: One implication is that presentation tier and the logic tier (sometimes called Business Logic Layer) needs to cross machine boundaries "across the wire" sometimes over unreliable, slow, and/or insecure network. This is very different from simple Desktop application where the data lives on the same machine as files or Web Application where you can hit the database directly.
For n-tier programming, you need to package up the data in some sort of transportable form called "dataset" and fly them over the wire. .NET's DataSet class or Web Services protocol like SOAP are few of such attempts to fly objects over the wire.
In newer versions of matplotlib
, if you do not set the tick labels with a bunch of str
values, they are ''
by default (and when the plot is draw the labels are simply the ticks values). Knowing that, to get your desired output would require something like this:
>>> from pylab import *
>>> axes = figure().add_subplot(111)
>>> a=axes.get_xticks().tolist()
>>> a[1]='change'
>>> axes.set_xticklabels(a)
[<matplotlib.text.Text object at 0x539aa50>, <matplotlib.text.Text object at 0x53a0c90>,
<matplotlib.text.Text object at 0x53a73d0>, <matplotlib.text.Text object at 0x53a7a50>,
<matplotlib.text.Text object at 0x53aa110>, <matplotlib.text.Text object at 0x53aa790>]
>>> plt.show()
and the result:
and now if you check the _xticklabels
, they are no longer a bunch of ''
.
>>> [item.get_text() for item in axes.get_xticklabels()]
['0.0', 'change', '1.0', '1.5', '2.0']
It works in the versions from 1.1.1rc1
to the current version 2.0
.
Wrap the xml in another element
<wrapper>
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</wrapper>
->It is located in $MAVEN_HOME/conf/settings.xml... where $MAVEN_HOME is your environmental variable of Maven that you have downloaded. Else you can do like this also.. ->Path to Maven can also be found from /etc/bashrc file in mac. Get Path to Maven from that file and in that Maven directory you can find conf/ directory inside that directory you can find settings.xml of maven
For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.
The extern
declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern
in a header file like:
extern struct a myAValue;
Then, in one source file, define the actual variable:
struct a myAValue;
If you forget to do this or accidentally define it in two source files, the linker will let you know about this.
Another issue that you might run into if you're running RHEL (I ran into it) is that there is a default welcome page configured with the httpd package that will override your settings, even if you put Options Indexes. The file is in /etc/httpd/conf.d/welcome.conf. See the following link for more info: http://wpapi.com/solved-issue-directory-index-forbidden-by-options-directive/
Sadly, I experienced a case of multiple dots on file name that splittext does not worked well... my work around:
file = r'C:\Docs\file.2020.1.1.xls'
ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
filefinal = file.replace(ext,'.zip')
os.rename(file ,filefinal)
A small update to what @control freak and @skatun wrote previously (sorry I don't have enough reputation to just make a comment). I used skatun's code and it worked well for me except that it was creating a larger array than what I needed. Therefore, I changed:
ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)
to:
ReDim aPreservedArray(LBound(aArrayToPreserve, 1) To nNewFirstUBound, LBound(aArrayToPreserve, 2) To nNewLastUBound)
This will maintain whatever the original array's lower bounds were (either 0, 1, or whatever; the original code assumes 0) for both dimensions.
Bind you Datagrid to an ObservableCollection, and update your collection instead.
try this code, it will work for all version of URLs like
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.website.com$ [NC]
RewriteRule ^(.*)$ https://www.website.com/$1 [L,R=301]
Try writting the lambda with the same conditions as the delegate. like this:
List<AnalysisObject> analysisObjects =
analysisObjectRepository.FindAll().Where(
(x =>
(x.ID == packageId)
|| (x.Parent != null && x.Parent.ID == packageId)
|| (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
).ToList();
Function overloading or method overloading is the ability to create multiple functions of the same name with different implementations (Wikipedia)
This feature is not possible in JS - the last defined function is taken in case of multiple declarations:
function foo(a1, a2) { return `${a1}, ${a2}` }
function foo(a1) { return `${a1}` } // replaces above `foo` declaration
foo(42, "foo") // "42"
Overloads are a compile-time construct with no impact on the JS runtime:
function foo(s: string): string // overload #1 of foo
function foo(s: string, n: number): number // overload #2 of foo
function foo(s: string, n?: number): string | number {/* ... */} // foo implementation
A duplicate implementation error is triggered, if you use above code (safer than JS). TS chooses the first fitting overload in top-down order, so overloads are sorted from most specific to most broad.
Overloaded class method types can be used in a similar way to function overloading:
class LayerFactory {
createFeatureLayer(a1: string, a2: number): string
createFeatureLayer(a1: number, a2: boolean, a3: string): number
createFeatureLayer(a1: string | number, a2: number | boolean, a3?: string)
: number | string { /*... your implementation*/ }
}
const fact = new LayerFactory()
fact.createFeatureLayer("foo", 42) // string
fact.createFeatureLayer(3, true, "bar") // number
The vastly different overloads are possible, as the function implementation is compatible to all overload signatures - enforced by the compiler.
More infos:
The OP didn't mention view controllers but so many of the answers do, that I wanted to chime in with what some of the new features of the LLVM allow to make this easier when wanting to pass data from one view controller to another and then getting some results back.
Storyboard segues, ARC and LLVM blocks make this easier than ever for me. Some answers above mentioned storyboards and segues already but still relied on delegation. Defining delegates certainly works but some people may find it easier to pass pointers or code blocks.
With UINavigators and segues, there are easy ways of passing information to the subservient controller and getting the information back. ARC makes passing pointers to things derived from NSObjects simple so if you want the subservient controller to add/change/modify some data for you, pass it a pointer to a mutable instance. Blocks make passing actions easy so if you want the subservient controller to invoke an action on your higher level controller, pass it a block. You define the block to accept any number of arguments that makes sense to you. You can also design the API to use multiple blocks if that suits things better.
Here are two trivial examples of the segue glue. The first is straightforward showing one parameter passed for input, the second for output.
// Prepare the destination view controller by passing it the input we want it to work on
// and the results we will look at when the user has navigated back to this controller's view.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
[[segue destinationViewController]
// This parameter gives the next controller the data it works on.
segueHandoffWithInput:self.dataForNextController
// This parameter allows the next controller to pass back results
// by virtue of both controllers having a pointer to the same object.
andResults:self.resultsFromNextController];
}
This second example shows passing a callback block for the second argument. I like using blocks because it keeps the relevant details close together in the source - the higher level source.
// Prepare the destination view controller by passing it the input we want it to work on
// and the callback when it has done its work.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
[[segue destinationViewController]
// This parameter gives the next controller the data it works on.
segueHandoffWithInput:self.dataForNextController
// This parameter allows the next controller to pass back results.
resultsBlock:^(id results) {
// This callback could be as involved as you like.
// It can use Grand Central Dispatch to have work done on another thread for example.
[self setResultsFromNextController:results];
}];
}
Check your Entity class. Use String instead of Long and float instead of double .
INSERT INTO table ( column1, column2, column3 )
SELECT $column1, $column2, $column3
EXCEPT SELECT column1, column2, column3
FROM table
Here is where I found it on a Windows 2008R2 server. Elevated Task Scheduler Click on "Task Scheduler Library" It appears as an option on the right hand "Actions" panel.
You can export a pfx from IIS on another server, if you have a server with the cert successfully installed.
Update:
Working on another round of certificate updates (a renewal) I ran into this problem again, on every server I tried. @Geir's answer didn't work, but it did give me an idea. I identified the server where I had generated the Certificate Request and successfully installed the new cert there. From that server I was able to export a pfx and then import the pfx version on the rest of the servers. No need to redo the Cert Request.
Tray to add text with html value to textarea but it wil not works
value :
$(document).on('click', '.edit_targets_btn', function() {
$('#add_edit_targets').modal('show');
$('#add_edit_targets_form')[0].reset();
$('#targets_modal_title').text('Doel bijwerken');
$('#action').val('targets_update');
$('#targets_submit_btn').val('Opslaan');
$('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
$('#targets_title').val($(this).attr("title"));
$("#targets_content").append($(this).attr("content"));
tinymce.init({
selector: '#targets_content',
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
},
browser_spellcheck : true,
plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
relative_urls : false,
remove_script_host : false,
image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
min_height: 250,
branding: false
});
});