According to official documentation, the following command worked for me.
Link is here
I was trying to run by "react-native run-android" command. make sure to have react-native cli installed globally!
I found this question while trying to split multiple contacts in a single vCard VCF file to separate files. Here's what I did based on Lee's code. I had to look up how to create a new StreamReader object and changed null to $null.
$reader = new-object System.IO.StreamReader("C:\Contacts.vcf")
$count = 1
$filename = "C:\Contacts\{0}.vcf" -f ($count)
while(($line = $reader.ReadLine()) -ne $null)
{
Add-Content -path $fileName -value $line
if($line -eq "END:VCARD")
{
++$count
$filename = "C:\Contacts\{0}.vcf" -f ($count)
}
}
$reader.Close()
Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
Here an example with 100000 rows (occupations are set here from A to Z):
> a = data.frame(sex=sample(c("M", "F"), 100000, replace=T), occupation=sample(LETTERS, 100000, replace=T))
> sum(a$sex == "M" & a$occupation=="A")
[1] 1882
returns the number of males with occupation "A".
EDIT
As I understand from your comment, you want the counts of all possible combinations of sex and occupation. So first create a dataframe with all combinations:
combns = expand.grid(c("M", "F"), LETTERS)
and loop with apply
to sum for your criteria and append the results to combns
:
combns = cbind (combns, apply(combns, 1, function(x)sum(a$sex==x[1] & a$occupation==x[2])))
colnames(combns) = c("sex", "occupation", "count")
The first rows of your result look as follows:
sex occupation count
1 M A 1882
2 F A 1869
3 M B 1866
4 F B 1904
5 M C 1979
6 F C 1910
Does this solve your problem?
OR:
Much easier solution suggested by thelatemai:
table(a$sex, a$occupation)
A B C D E F G H I J K L M N O
F 1869 1904 1910 1907 1894 1940 1964 1907 1918 1892 1962 1933 1886 1960 1972
M 1882 1866 1979 1904 1895 1845 1946 1905 1999 1994 1933 1950 1876 1856 1911
P Q R S T U V W X Y Z
F 1908 1907 1883 1888 1943 1922 2016 1962 1885 1898 1889
M 1928 1938 1916 1927 1972 1965 1946 1903 1965 1974 1906
Add this to css
of your div: word-wrap: break-word;
You can use 9 patch in Android Studio to make borders!
I was looking for a solution but I did not find any so I skipped that part.
Then I went to the Google images of Firebase assets and I accidentally discovered that they use 9patch.
Here's the link: https://developer.android.com/studio/write/draw9patch
You just need to drag where the edges are.
It's just like border edge in Unity.
To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example
SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));
Table created.
SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column
SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)
SQL> insert into test values(111,'Darshan');
1 row created.
SQL>
And to answer your next one:
The difference between varchar2
and varchar
:
VARCHAR
can store up to 2000 bytes
of characters while VARCHAR2
can store up to 4000 bytes
of characters.VARCHAR
then it will occupy space for NULL values
, In case of VARCHAR2
datatype it will not
occupy any space.From within less (in Linux):
g and the line number to go forward
G and the line number to go backwards
Used alone, g and G will take you to the first and last line in a file respectively; used with a number they are both equivalent.
An example; you want to go to line 320123 of a file,
press 'g' and after the colon type in the number 320123
Additionally you can type '-N' inside less to activate / deactivate the line numbers. You can as a matter of fact pass any command line switches from inside the program, such as -j or -N.
NOTE: You can provide the line number in the command line to start less (less +number -N) which will be much faster than doing it from inside the program:
less +12345 -N /var/log/hugelogfile
This will open a file displaying the line numbers and starting at line 12345
Source: man 1 less and built-in help in less (less 418)
change_column
is a method of ActiveRecord::Migration
, so you can't call it like that in the console.
If you want to add a default value for this column, create a new migration:
rails g migration add_default_value_to_show_attribute
Then in the migration created:
# That's the more generic way to change a column
def up
change_column :profiles, :show_attribute, :boolean, default: true
end
def down
change_column :profiles, :show_attribute, :boolean, default: nil
end
OR a more specific option:
def up
change_column_default :profiles, :show_attribute, true
end
def down
change_column_default :profiles, :show_attribute, nil
end
Then run rake db:migrate
.
It won't change anything to the already created records. To do that you would have to create a rake task
or just go in the rails console
and update all the records (which I would not recommend in production).
When you added t.boolean :show_attribute, :default => true
to the create_profiles
migration, it's expected that it didn't do anything. Only migrations that have not already been ran are executed. If you started with a fresh database, then it would set the default to true.
For me the code:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
throws error, but I added name attribute to input:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
and it started to work.
Inline code takes higher precedence than the other ones. To call your other function func () call it from the f1 ().
Inside your function, add a line,
function fun () {
// Your code here
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
fun ();
}
Rewriting your whole code,
<!DOCTYPE html>
<html>
<head>
<script>
function fun()
{
alert("hello");
//validation code to see State field is mandatory.
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
fun ();
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1()">click</td></tr></table>
</body>
</html>
Adding my way to do it in React-Native using react-native-config package.
Create a .env file:
RELEASE_STORE_PASSWORD=[YOUR_PASSWORD]
RELEASE_KEY_PASSWORD=[YOUR_PASSWORD]
note this should not be part of the version control.
in your build.gradle
:
signingConfigs {
debug {
...
}
release {
storeFile file(RELEASE_STORE_FILE)
storePassword project.env.get('RELEASE_STORE_PASSWORD')
keyAlias RELEASE_KEY_ALIAS
keyPassword project.env.get('RELEASE_KEY_PASSWORD')
}
}
save the file on your disk and then use the following as URL:
file://your_path/your_file.wsdl
You can also do the same thing in another way,
If you are using PHP 5.5 or latest one then you can do it as follow,
return view(index, compact('data1','data2')); //as many as you want to pass
<div>
You can access {{$data1}}. [if it is variable]
</div>
@foreach($data1 as $d1)
<div>
You can access {{$d1}}. [if it is array]
</div>
@endforeach
Same way you can access all variable that you have passed in compact function.
Hope it helps :)
If you have mixed content list. And want to stringify it. Here is one way:
Consider this list:
>>> aa
[None, 10, 'hello']
Convert it to string:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
If required, convert back to list:
>>> ast.literal_eval(st)
[None, 10, 'hello']
I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.
With localView1 as (
select c1,
c2,
c3,
c4,
((c2-c4)*(3))+c1 as "complex"
from realTable1)
, localView2 as (
select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
complex * complex as formula2
from localView1)
select *
from localView2
You may have to enable the HTTPS part:
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 2);
And if you need to verify (authenticate yourself) you may need this too:
curl_setopt($c, CURLOPT_USERPWD, 'username:password');
use below code:
model = forest.fit(train_fold, train_y.ravel())
if you are still getting slap by error as identical as below ?
Unknown label type: %r" % y
use this code:
y = train_y.ravel()
train_y = np.array(y).astype(int)
model = forest.fit(train_fold, train_y)
import json
json_data = json.dumps({
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find": "true"
}
]
})
item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])
Convert it in dict.
In the API manager menu, you should be able to click overview, select the relevant API under the Google Maps APIs heading and map icon.
Your page might be using some other API's , like Places. Enable them all and see if it helps.
Google Places API Web Service Google Maps Geocoding API
I did a workaround by creating a new css class in my custom stylesheet as follows:
.selectwidthauto
{
width:auto !important;
}
And then applied this class to all my select elements either manually like:
<select id="State" class="selectwidthauto">
...
</select>
Or using jQuery:
$('select').addClass('selectwidthauto');
You want a config.site file. Try:
$ mkdir -p ~/local/share $ cat << EOF > ~/local/share/config.site CPPFLAGS=-I$HOME/local/include LDFLAGS=-L$HOME/local/lib ... EOF
Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum
If you want to make exceptions, you can apply the following "hack". It requires a user with DELETE
and INSERT
privilege for mysql.plugin
system table.
uninstall plugin validate_password;
SET PASSWORD FOR 'app' = PASSWORD('abcd');
INSTALL PLUGIN validate_password SONAME 'validate_password.so';
Bland security disclaimer: Consider, why you are making your password shorter or easier and perhaps consider replacing it with one that is more complex. However, I understand the "it's 3AM and just needs to work" moments, just make sure you don't build a system of hacks, lest you yourself be hacked
The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:
underscores_in_headers on;
This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997
I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.
Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.
So if you are manipulating DOM directly and inserting content it, you need to sanitize it otherwise Angular will through errors.
I have created the pipe SanitizeUrlPipe for this
import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) { }
transform(v: string): SafeHtml {
return this._sanitizer.bypassSecurityTrustResourceUrl(v);
}
}
and this is how you can use
<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>
If you want to add HTML, then SanitizeHtmlPipe can help
import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) { }
transform(v: string): SafeHtml {
return this._sanitizer.bypassSecurityTrustHtml(v);
}
}
Read more about angular security here.
Since C90, you can simply use:
dest_struct = source_struct;
as long as the string is memorized inside an array:
struct xxx {
char theString[100];
};
Otherwise, if it's a pointer, you'll need to copy it by hand.
struct xxx {
char* theString;
};
dest_struct = source_struct;
dest_struct.theString = malloc(strlen(source_struct.theString) + 1);
strcpy(dest_struct.theString, source_struct.theString);
And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:
IJulia.clear_output(true)
so for a kind of animated plot of multiple runs
if nrun==1
display(plot(x,y)) # first plot
else
IJulia.clear_output(true) # clear the window (as above)
display(plot!(x,y)) # plot! overlays the plot
end
Without the clear_output call, all plots appear separately.
function _formatDatetime(date: Date, format: string) {
const _padStart = (value: number): string => value.toString().padStart(2, '0');
return format
.replace(/yyyy/g, _padStart(date.getFullYear()))
.replace(/dd/g, _padStart(date.getDate()))
.replace(/mm/g, _padStart(date.getMonth() + 1))
.replace(/hh/g, _padStart(date.getHours()))
.replace(/ii/g, _padStart(date.getMinutes()))
.replace(/ss/g, _padStart(date.getSeconds()));
}
function isValidDate(d: Date): boolean {
return !isNaN(d.getTime());
}
export function formatDate(date: any): string {
var datetime = new Date(date);
return isValidDate(datetime) ? _formatDatetime(datetime, 'yyyy-mm-dd hh:ii:ss') : '';
}
SQL-92 standard defines INFORMATION_SCHEMA which conforming rdbms's like MS SQL Server support. The following works for MS SQL Server 2000/2005/2008 and MySql 5 and above
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'myTable'
MS SQl Server Specific:
exec sp_help 'myTable'
This solution returns several result sets within which is the information you desire, where as the former gives you exactly what you want.
Also just for completeness you can query the sys tables directly. This is not recommended as the schema can change between versions of SQL Server and INFORMATION_SCHEMA is a layer of abstraction above these tables. But here it is anyway for SQL Server 2000
select [name] from dbo.syscolumns where id = object_id(N'[dbo].[myTable]')
Properties prop = new Properties();
String fileName = "./src/test/resources/predefined.properties";
FileInputStream inputStream = new FileInputStream(fileName);
InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.company.package"
android:versionCode="1"
android:versionName="0.1">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<!-- ... -->
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
You should always check for availability first. A snippet from the official android documentation on external storage.
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
At last but not least forget about the FileOutputStream
and use a FileWriter
instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.
// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory());
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
Here's a Python 3 solution using the built in wave module [1], that works for n channels, and 8,16,24... bits.
import sys
import wave
def read_wav(path):
with wave.open(path, "rb") as wav:
nchannels, sampwidth, framerate, nframes, _, _ = wav.getparams()
print(wav.getparams(), "\nBits per sample =", sampwidth * 8)
signed = sampwidth > 1 # 8 bit wavs are unsigned
byteorder = sys.byteorder # wave module uses sys.byteorder for bytes
values = [] # e.g. for stereo, values[i] = [left_val, right_val]
for _ in range(nframes):
frame = wav.readframes(1) # read next frame
channel_vals = [] # mono has 1 channel, stereo 2, etc.
for channel in range(nchannels):
as_bytes = frame[channel * sampwidth: (channel + 1) * sampwidth]
as_int = int.from_bytes(as_bytes, byteorder, signed=signed)
channel_vals.append(as_int)
values.append(channel_vals)
return values, framerate
You can turn the result into a NumPy array.
import numpy as np
data, rate = read_wav(path)
data = np.array(data)
Note, I've tried to make it readable rather than fast. I found reading all the data at once was almost 2x faster. E.g.
with wave.open(path, "rb") as wav:
nchannels, sampwidth, framerate, nframes, _, _ = wav.getparams()
all_bytes = wav.readframes(-1)
framewidth = sampwidth * nchannels
frames = (all_bytes[i * framewidth: (i + 1) * framewidth]
for i in range(nframes))
for frame in frames:
...
Although python-soundfile is roughly 2 orders of magnitude faster (hard to approach this speed with pure CPython).
I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.
Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/
Since I need to post code here is what each collapsible "section" should look like ->
<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
<td>1</td>
<td>05 May 2013</td>
<td>Credit Account</td>
<td class="text-success">$150.00</td>
<td class="text-error"></td>
<td class="text-success">$150.00</td>
</tr>
<tr>
<td colspan="6" class="hiddenRow">
<div class="accordion-body collapse" id="demo1">Demo1</div>
</td>
</tr>
For Power-Shell
./adb shell getprop | Select-String -Pattern '(model)|(version.sdk)|(manufacturer)|(platform)|(serialno)|(product.name)|(brand)'
For linux(burrowing asnwer from @0x8BADF00D)
adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"
For single string find in power shell
./adb shell getprop | Select-String -Pattern 'model'
or
./adb shell getprop | Select-String -Pattern '(model)'
For multiple
./adb shell getprop | Select-String -Pattern '(a|b|c|d)'
Here's the bare-knuckle no-seat-belts use-at-own-risk version:
import datetime
def minimalist_xldate_as_datetime(xldate, datemode):
# datemode: 0 for 1900-based, 1 for 1904-based
return (
datetime.datetime(1899, 12, 30)
+ datetime.timedelta(days=xldate + 1462 * datemode)
)
[What you need for interviews] A Node class is the sufficient data structure to represent a binary tree.
(While other answers are mostly correct, they are not required for a binary tree: no need to extend object class, no need to be a BST, no need to import deque).
class Node:
def __init__(self, value = None):
self.left = None
self.right = None
self.value = value
Here is an example of a tree:
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.left = n2
n1.right = n3
In this example n1 is the root of the tree having n2, n3 as its children.
I've been trying to just make a simple bash script that emails out html formatted content-type and all these are great but I don't want to be creating local files on the filesystem to be passing into the script and also on our version of mailx(12.5+) the -a parameter for mail doesn't work anymore since it adds an attachment and I couldn't find any replacement parameter for additional headers so the easiest way for me was to use sendmail.
Below is the simplest 1 liner I created to run in our bash script that works for us. It just basically passes the Content-Type: text/html, subject, and the body and works.
printf "Content-Type: text/html\nSubject: Test Email\nHTML BODY<b>test bold</b>" | sendmail <Email Address To>
If you wanted to create an entire html page from a variable an alternative method I used in the bash script was to pass the variable as below.
emailBody="From: <Email Address From>
Subject: Test
Content-Type: text/html; charset=\"us-ascii\"
<html>
<body>
body
<b> test bold</b>
</body>
</html>
"
echo "$emailBody" | sendmail <Email Address To>
Posting here as I think it may be useful for people using Flask
with pymongo
. This is my current "best practice" setup for allowing flask to marshall pymongo bson data types.
mongoflask.py
from datetime import datetime, date
import isodate as iso
from bson import ObjectId
from flask.json import JSONEncoder
from werkzeug.routing import BaseConverter
class MongoJSONEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, (datetime, date)):
return iso.datetime_isoformat(o)
if isinstance(o, ObjectId):
return str(o)
else:
return super().default(o)
class ObjectIdConverter(BaseConverter):
def to_python(self, value):
return ObjectId(value)
def to_url(self, value):
return str(value)
app.py
from .mongoflask import MongoJSONEncoder, ObjectIdConverter
def create_app():
app = Flask(__name__)
app.json_encoder = MongoJSONEncoder
app.url_map.converters['objectid'] = ObjectIdConverter
# Client sends their string, we interpret it as an ObjectId
@app.route('/users/<objectid:user_id>')
def show_user(user_id):
# setup not shown, pretend this gets us a pymongo db object
db = get_db()
# user_id is a bson.ObjectId ready to use with pymongo!
result = db.users.find_one({'_id': user_id})
# And jsonify returns normal looking json!
# {"_id": "5b6b6959828619572d48a9da",
# "name": "Will",
# "birthday": "1990-03-17T00:00:00Z"}
return jsonify(result)
return app
Why do this instead of serving BSON or mongod extended JSON?
I think serving mongo special JSON puts a burden on client applications. Most client apps will not care using mongo objects in any complex way. If I serve extended json, now I have to use it server side, and the client side. ObjectId
and Timestamp
are easier to work with as strings and this keeps all this mongo marshalling madness quarantined to the server.
{
"_id": "5b6b6959828619572d48a9da",
"created_at": "2018-08-08T22:06:17Z"
}
I think this is less onerous to work with for most applications than.
{
"_id": {"$oid": "5b6b6959828619572d48a9da"},
"created_at": {"$date": 1533837843000}
}
An alternative with data.table
:
library(data.table)
df1 = data.frame(a = c(1:5), b = c(6:10))
df2 = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
rbindlist(list(df1, df2), fill = TRUE)
rbind
will also work in data.table
as long as the objects are converted to data.table
objects, so
rbind(setDT(df1), setDT(df2), fill=TRUE)
will also work in this situation. This can be preferable when you have a couple of data.tables and don't want to construct a list.
You can you use permalinks to include code snippets in issues, PRs, etc.
References:
https://help.github.com/en/articles/creating-a-permanent-link-to-a-code-snippet
In my case, I have reinstalled ubuntu and the user name is changed from previous. In this case the the generated ssh key also differs from the previous one.
The issue solved by just copy the current ssh public key, in the repository. The key will be available in your user's /home/.ssh/id_rsa.pub
This fix worked very well for me:
Add the following to to your ~/.profile
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH
http://www.rickwargo.com/2010/12/16/installing-mysql-5-5-on-os-x-10-6-snow-leopard-and-rails-3/
With new version of flutter and material theme u need to use the "Padding" widgett too in order to have an image that doesn't fill its container.
For example if you want to insert a rounded image in the AppBar u must use padding or your image will always be as high as the AppBar.
Hope this will help someone
InkWell(
onTap: () {
print ('Click Profile Pic');
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ClipOval(
child: Image.asset(
'assets/images/profile1.jpg',
),
),
),
),
You can install the following two NuGet packages:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Binder;
And then you'll have the possibility to use the following extension method:
var myArray = _config.GetSection("MyArray").Get<string[]>();
git fetch <remote>
git status
Compare the two branches:
git fetch <remote>
git log <local_branch_name>..<remote_branch_name> --oneline
For example:
git fetch origin
# See if there are any incoming changes
git log HEAD..origin/master --oneline
(I'm assuming origin/master
is your remote tracking branch)
If any commits are listed in the output above, then you have incoming changes -- you need to merge. If no commits are listed by git log
then there is nothing to merge.
Note that this will work even if you are on a feature branch -- that does not have a tracking remote, since if explicitly refers to origin/master
instead of implicitly using the upstream branch remembered by Git.
Brace yourself, here there's another coming :-)
Today I had to explain to my girlfriend the difference between the expressive power of WS-Security as opposed to HTTPS. She's a computer scientist, so even if she doesn't know all the XML mumbo jumbo she understands (maybe better than me) what encryption or signature means. However I wanted a strong image, which could make her really understand what things are useful for, rather than how they are implemented (that came a bit later, she didn't escape it :-)).
So it goes like this. Suppose you are naked, and you have to drive your motorcycle to a certain destination. In the (A) case you go through a transparent tunnel: your only hope of not being arrested for obscene behaviour is that nobody is looking. That is not exactly the most secure strategy you can come out with... (notice the sweat drop from the guy forehead :-)). That is equivalent to a POST in clear, and when I say "equivalent" I mean it. In the (B) case, you are in a better situation. The tunnel is opaque, so as long as you travel into it your public record is safe. However, this is still not the best situation. You still have to leave home and reach the tunnel entrance, and once outside the tunnel probably you'll have to get off and walk somewhere... and that goes for HTTPS. True, your message is safe while it crosses the biggest chasm: but once you delivered it on the other side you don't really know how many stages it will have to go through before reaching the real point where the data will be processed. And of course all those stages could use something different than HTTP: a classical MSMQ which buffers requests which can't be served right away, for example. What happens if somebody lurks your data while they are in that preprocessing limbo? Hm. (read this "hm" as the one uttered by Morpheus at the end of the sentence "do you think it's air you are breathing?"). The complete solution (c) in this metaphor is painfully trivial: get some darn clothes on yourself, and especially the helmet while on the motorcycle!!! So you can safely go around without having to rely on opaqueness of the environments. The metaphor is hopefully clear: the clothes come with you regardless of the mean or the surrounding infrastructure, as the messsage level security does. Furthermore, you can decide to cover one part but reveal another (and you can do that on personal basis: airport security can get your jacket and shoes off, while your doctor may have a higher access level), but remember that short sleeves shirts are bad practice even if you are proud of your biceps :-) (better a polo, or a t-shirt).
I'm happy to say that she got the point! I have to say that the clothes metaphor is very powerful: I was tempted to use it for introducing the concept of policy (disco clubs won't let you in sport shoes; you can't go to withdraw money in a bank in your underwear, while this is perfectly acceptable look while balancing yourself on a surf; and so on) but I thought that for one afternoon it was enough ;-)
Architecture - WS, Wild Ideas
if you want update map view, for example change map center, you don’t have to delete and then recreate the map, you can just update coordinate
const mapInit = () => {
let map.current = w.L.map('map');
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright" target="_blank">OpenStreetMap</a> contributors'
}).addTo(map.current);
}
const setCoordinate = (gps_lat, gps_long) => {
map.setView([gps_lat, gps_long], 13);
}
initMap();
setCoordinate(50.403723 30.623538);
setTimeout(() => {
setCoordinate(51.505, -0.09);
}, 3000);
Bitwise operations, including bit shift, are fundamental to low-level hardware or embedded programming. If you read a specification for a device or even some binary file formats, you will see bytes, words, and dwords, broken up into non-byte aligned bitfields, which contain various values of interest. Accessing these bit-fields for reading/writing is the most common usage.
A simple real example in graphics programming is that a 16-bit pixel is represented as follows:
bit | 15| 14| 13| 12| 11| 10| 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| Blue | Green | Red |
To get at the green value you would do this:
#define GREEN_MASK 0x7E0
#define GREEN_OFFSET 5
// Read green
uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;
Explanation
In order to obtain the value of green ONLY, which starts at offset 5 and ends at 10 (i.e. 6-bits long), you need to use a (bit) mask, which when applied against the entire 16-bit pixel, will yield only the bits we are interested in.
#define GREEN_MASK 0x7E0
The appropriate mask is 0x7E0 which in binary is 0000011111100000 (which is 2016 in decimal).
uint16_t green = (pixel & GREEN_MASK) ...;
To apply a mask, you use the AND operator (&).
uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;
After applying the mask, you'll end up with a 16-bit number which is really just a 11-bit number since its MSB is in the 11th bit. Green is actually only 6-bits long, so we need to scale it down using a right shift (11 - 6 = 5), hence the use of 5 as offset (#define GREEN_OFFSET 5
).
Also common is using bit shifts for fast multiplication and division by powers of 2:
i <<= x; // i *= 2^x;
i >>= y; // i /= 2^y;
None of previous answers worked for me.
I noticed that my project was referencing another project using the System.Web.Mvc
reference from the .NET Framework.
I just deleted that assembly and added the "Microsoft.AspNet.Mvc" NuGet package and that fixed my problem.
A job I do a lot it seems, it's to send forms via ajax, that usually includes an attachment and several input fields. In the more classic workflow (HTML/PHP/JQuery) I've used $.ajax()
in the client and PHP on the server with total success.
I've used axios for dart/flutter but now I'm learning react for building my web sites, and JQuery doesn't make sense.
Problem is axios is giving me some headaches with PHP on the other side, when posting both normal input fields and uploading a file in the same form. I tried $_POST
and file_get_contents("php://input")
in PHP, sending from axios with FormData or using a json construct, but I can never get both the file upload and the input fields.
On the other hand with Fetch I've been successful with this code:
var formid = e.target.id;
// populate FormData
var fd = buildFormData(formid);
// post to remote
fetch('apiurl.php', {
method: 'POST',
body: fd,
headers:
{
'Authorization' : 'auth',
"X-Requested-With" : "XMLHttpRequest"
}
})
On the PHP side I'm able to retrieve the uploads via $_FILES
and processing the other fields data via $_POST:
$posts = [];
foreach ($_POST as $post) {
$posts[] = json_decode($post);
}
Swift 4 updated :
extension UIView {
var screenShot: UIImage? {
if #available(iOS 10, *) {
let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
return renderer.image { (context) in
self.layer.render(in: context.cgContext)
}
} else {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 5);
if let _ = UIGraphicsGetCurrentContext() {
drawHierarchy(in: bounds, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return screenshot
}
return nil
}
}
}
You need to give the array a size:
public static void main(String args[])
{
int array[] = new int[4];
int number = 5, i = 0,j = 0;
while (i<4){
array[i]=number;
i=i+1;
}
while (j<4){
System.out.println(array[j]);
j++;
}
}
If someone is having problem with finding CURL in the list in setup.exe (Cygwin package manager) then trying downloading 64bit version of this setup. Worked for me.
You can use snprintf to get a substring of a char array with precision. Here is a file example called "substring.c":
#include <stdio.h>
int main()
{
const char source[] = "This is a string array";
char dest[17];
// get first 16 characters using precision
snprintf(dest, sizeof(dest), "%.16s", source);
// print substring
puts(dest);
} // end main
Output:
This is a string
Note:
For further information see printf man page.
As Ben said, you'll need to work with the UIView's
layer, using a CATransform3D
to perform the layer's
rotation
. The trick to get perspective working, as described here, is to directly access one of the matrix cells
of the CATransform3D
(m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:
Objective-C
UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;
Swift 5.0
if let myView = self.subviews.first {
let layer = myView.layer
var rotationAndPerspectiveTransform = CATransform3DIdentity
rotationAndPerspectiveTransform.m34 = 1.0 / -500
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
layer.transform = rotationAndPerspectiveTransform
}
which rebuilds the layer transform from scratch for each rotation.
A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers
, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.
The sublayerTransform
you refer to in your response is a transform that is applied to the sublayers of your UIView's
CALayer
. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers
contained within the one layer that I'm rotating.
I'd say
concat('This is line 1.', 0xd0a, 'This is line 2.')
or
concat(N'This is line 1.', 0xd000a, N'This is line 2.')
The complement of a regular language is also a regular language, but to construct it you have to build the DFA for the regular language, and make any valid state change into an error. See this for an example. What the page doesn't say is that it converted /(ac|bd)/
into /(a[^c]?|b[^d]?|[^ab])/
. The conversion from a DFA back to a regular expression is not trivial. It is easier if you can use the regular expression unchanged and change the semantics in code, like suggested before.
If you are using php can do:
<script src="js/myscript.js?rev=<?php echo time();?>"
type="text/javascript"></script>
It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".
Use std::getline
:
int main()
{
std::string name, title;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your favourite movie: ";
std::getline(std::cin, title);
std::cout << name << "'s favourite movie is " << title;
}
Note that this is not the same as std::istream::getline
, which works with C-style char
buffers rather than std::string
s.
Update
Your edited question bears little resemblance to the original.
You were trying to getline
into an int
, not a string or character buffer. The formatting operations of streams only work with operator<<
and operator>>
. Either use one of them (and tweak accordingly for multi-word input), or use getline
and lexically convert to int
after-the-fact.
In your .htaccess file , if you are using apache you can try with
Rule for Error Page - 404ErrorDocument 404 http://www.domain.com/notFound.html
It's downloaded probably because there is not Adobe Reader plug-in installed. In this case, IE (it doesn't matter which version) doesn't know how to render it, and it'll simply download the file (Chrome, for example, has its own embedded PDF renderer).
That said. <iframe>
is not best way to display a PDF (do not forget compatibility with mobile browsers, for example Safari). Some browsers will always open that file inside an external application (or in another browser window). Best and most compatible way I found is a little bit tricky but works on all browsers I tried (even pretty outdated):
Keep your <iframe>
but do not display a PDF inside it, it'll be filled with an HTML page that consists of an <object>
tag. Create an HTML wrapping page for your PDF, it should look like this:
<html>
<body>
<object data="your_url_to_pdf" type="application/pdf">
<embed src="your_url_to_pdf" type="application/pdf" />
</object>
</body>
</html>
Of course, you still need the appropriate plug-in installed in the browser. Also, look at this post if you need to support Safari on mobile devices.
1st. Why nesting <embed>
inside <object>
? You'll find the answer here on SO. Instead of a nested <embed>
tag, you may (should!) provide a custom message for your users (or a built-in viewer, see next paragraph). Nowadays, <object>
can be used without worries, and <embed>
is useless.
2nd. Why an HTML page? So you can provide a fallback if PDF viewer isn't supported. Internal viewer, plain HTML error messages/options, and so on...
It's tricky to check PDF support so that you may provide an alternate viewer for your customers, take a look at PDF.JS project; it's pretty good but rendering quality - for desktop browsers - isn't as good as a native PDF renderer (I didn't see any difference in mobile browsers because of screen size, I suppose).
Is there any other way than these two?
Yes, there is.
LocalDate.now(
ZoneId.of( "Pacific/Auckland" )
)
Java 8 and later comes with the new java.time package built-in. See Tutorial. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Similar to Joda-Time, java.time offers a LocalDate
class to represent a date-only value without time-of-day and without time zone.
Note that time zone is critical to determining a particular date. At the stroke of midnight in Paris, for example, the date is still “yesterday” in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
By default, java.time uses the ISO 8601 standard in generating a string representation of a date or date-time value. (Another similarity with Joda-Time.) So simply call toString()
to generate text like 2015-05-21
.
String output = today.toString() ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
This error started for me when I added a new way to instantiate a class.
Example:
public class myClass
{
public string id{ get; set; }
public List<string> myList{get; set;}
// error happened after I added this
public myClass(string id, List<string> lst)
{
this.id= id;
this.myList= lst;
}
}
The error was resolved when I added when I made this change, adding a parameterless constructor. I believe the compiler creates a parameterless constuctor by default but if you add your own then you must explicitly create it.
public class myClass
{
public string id{ get; set; }
public List<string> myList{get; set;}
// error doesn't happen when I add this
public myClass() { }
// error happened after I added this, but no longer happens after adding above
public myClass(string id, List<string> lst)
{
this.id= id;
this.myList= lst;
}
}
Just using
HttpContext.Current.GetOwinContext()
did the trick in my case.
You can use client-side validation:
<asp:textbox onkeydown="return (!(event.keyCode>=65) && event.keyCode!=32);" />
If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.dateFormat(new ISO8601DateFormat());
}
};
}
For a group of UITextView
s inside a ViewController
:
Swift 3.0
for view in view.subviews {
if view is UITextField {
view.resignFirstResponder()
}
}
Objective-C
// hide keyboard before dismiss
for (UIView *view in [self.view subviews]) {
if ([view isKindOfClass:[UITextField class]]) {
// no need to cast
[view resignFirstResponder];
}
}
In my case, jQuery one had some side effects (in IE8) and I ended up using the following :
$(document).ready(function(){
$("*").dblclick(function(e){
e.preventDefault();
});
});
which works very nicely and looks simpler. Found it there: http://www.jquerybyexample.net/2013/01/disable-mouse-double-click-using-javascript-or-jquery.html
Try this for multiple CSS styles:
$(this).css({
"background-color": 'red',
"color" : "white"
});
switch (String.valueOf(value)){
case "null":
default:
}
I have a solution for that, tailor it to your own needs, an excerpt from one of my libs:
elvisStructureSeparator: '.',
// An Elvis operator replacement. See:
// http://coffeescript.org/ --> The Existential Operator
// http://fantom.org/doc/docLang/Expressions.html#safeInvoke
//
// The fn parameter has a SPECIAL SYNTAX. E.g.
// some.structure['with a selector like this'].value transforms to
// 'some.structure.with a selector like this.value' as an fn parameter.
//
// Configurable with tulebox.elvisStructureSeparator.
//
// Usage examples:
// tulebox.elvis(scope, 'arbitrary.path.to.a.function', fnParamA, fnParamB, fnParamC);
// tulebox.elvis(this, 'currentNode.favicon.filename');
elvis: function (scope, fn) {
tulebox.dbg('tulebox.elvis(' + scope + ', ' + fn + ', args...)');
var implicitMsg = '....implicit value: undefined ';
if (arguments.length < 2) {
tulebox.dbg(implicitMsg + '(1)');
return undefined;
}
// prepare args
var args = [].slice.call(arguments, 2);
if (scope === null || fn === null || scope === undefined || fn === undefined
|| typeof fn !== 'string') {
tulebox.dbg(implicitMsg + '(2)');
return undefined;
}
// check levels
var levels = fn.split(tulebox.elvisStructureSeparator);
if (levels.length < 1) {
tulebox.dbg(implicitMsg + '(3)');
return undefined;
}
var lastLevel = scope;
for (var i = 0; i < levels.length; i++) {
if (lastLevel[levels[i]] === undefined) {
tulebox.dbg(implicitMsg + '(4)');
return undefined;
}
lastLevel = lastLevel[levels[i]];
}
// real return value
if (typeof lastLevel === 'function') {
var ret = lastLevel.apply(scope, args);
tulebox.dbg('....function value: ' + ret);
return ret;
} else {
tulebox.dbg('....direct value: ' + lastLevel);
return lastLevel;
}
},
works like a charm. Enjoy the less pain!
I wrote a realpath utility for OS X which can provide the same results as readlink -f
.
Here is an example:
(jalcazar@mac tmp)$ ls -l a
lrwxrwxrwx 1 jalcazar jalcazar 11 8? 25 19:29 a -> /etc/passwd
(jalcazar@mac tmp)$ realpath a
/etc/passwd
If you are using MacPorts, you can install it with the following command: sudo port selfupdate && sudo port install realpath
.
Try apachectl -V:
$ apachectl -V
Server version: Apache/2.2.9 (Unix)
Server built: Sep 18 2008 21:54:05
Server's Module Magic Number: 20051115:15
Server loaded: APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
... etc ...
If it does not work for you, run the command with sudo
.
check it useing loop for each index in comboxlist.Items[i]
bool CheckedOrUnchecked= comboxlist.CheckedItems.Contains(comboxlist.Items[0]);
I think it solve your purpose
Find this useful solution
function get_duplicates( $array ) {
return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}
After that count result if greater than 0 than duplicates else unique.
I also got the error you mention:
CMake Error: CMake can not determine linker language for target:helloworld
CMake Error: Cannot determine link language for target "helloworld".
In my case this was due to having C++ files with the .cc
extension.
If CMake is unable to determine the language of the code correctly you can use the following:
set_target_properties(hello PROPERTIES LINKER_LANGUAGE CXX)
The accepted answer that suggests appending the language to the project()
statement simply adds more strict checking for what language is used (according to the documentation), but it wasn't helpful to me:
Optionally you can specify which languages your project supports. Example languages are CXX (i.e. C++), C, Fortran, etc. By default C and CXX are enabled. E.g. if you do not have a C++ compiler, you can disable the check for it by explicitly listing the languages you want to support, e.g. C. By using the special language "NONE" all checks for any language can be disabled. If a variable exists called CMAKE_PROJECT__INCLUDE_FILE, the file pointed to by that variable will be included as the last step of the project command.
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
Answering to myself. From the RequireJS website:
//THIS WILL FAIL
define(['require'], function (require) {
var namedModule = require('name');
});
This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.
My solution:
// Modules configuration (modules that will be used as Jade helpers)
define(function () {
return {
'moment': 'path/to/moment',
'filesize': 'path/to/filesize',
'_': 'path/to/lodash',
'_s': 'path/to/underscore.string'
};
});
The loader:
define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
var deps;
// Dynamic require
require(_.values(Config), function () {
deps = _.object(_.keys(Config), arguments);
// Use deps...
});
});
You get the cursor position by calling GetCursorPos
.
POINT p;
if (GetCursorPos(&p))
{
//cursor position now in p.x and p.y
}
This returns the cursor position relative to screen coordinates. Call ScreenToClient
to map to window coordinates.
if (ScreenToClient(hwnd, &p))
{
//p.x and p.y are now relative to hwnd's client area
}
You hide and show the cursor with ShowCursor
.
ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again
You must ensure that every call to hide the cursor is matched by one that shows it again.
I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.
BE MINDFUL, If you use angular.equals()
on objects that have property obj.$something
(property name starts with $) those properties will get ignored in comparison.
Example:
var obj1 = {
$key0: "A",
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
$key0: "B"
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)
This doesn't seem to have <a> </a>
tags so selenium might not be able to detect it as a link.
You may try and use
driver.findElement(By.xpath("//*[@class='ng-binding']")).click();
if this is the only element in that page with this class .
It has to do with how much memory is available for AS to create a VM environment for your app to populate. The thing is that ever since the update to 2.2 I've had the same problem every time I try to create a new project in AS.
How I solve it is by going into Project (on the left hand side) > Gradle Scripts > gradle.properties. When it opens the file go to the line under "(Line 10)# Specifies the JVM arguments used for the daemon process. (Line 11)# The setting is particularly useful for tweaking memory settings." You're looking for the line that starts with "org.gradle.jvmargs". This should be line 12. Change line 12 to this
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
After changing this line you can either sync the gradle with the project by clicking Try again on the notification telling you the gradle sync failed (it'll be at the top of the file you opened). Or you can simply close and restart the AS and it should sync.
Essentially what this is saying is for AS to allocate more memory to the app initialization. I know it's not a permanent fix but it should get you through actually starting your app.
After doing some more googling I came across the float package which lets you prevent LaTeX from repositioning the tables.
In the preamble:
\usepackage{float}
\restylefloat{table}
Then for each table you can use the H
placement option (e.g. \begin{table}[H]
) to make sure it doesn't get repositioned.
font-family:'Open Sans' , sans-serif;
For light:
font-weight : 100;
Or
font-weight : lighter;
For normal:
font-weight : 500;
Or
font-weight : normal;
For bold:
font-weight : 700;
Or
font-weight : bold;
For more bolder:
font-weight : 900;
Or
font-weight : bolder;
For those who need path() change without controllers reload - Here is plugin: https://github.com/anglibs/angular-location-update
Usage:
$location.update_path('/notes/1');
Based on https://stackoverflow.com/a/24102139/1751321
P.S. This solution https://stackoverflow.com/a/24102139/1751321 contains bug after path(, false) called - it will break browser navigation back/forward until path(, true) called
Also if your variable is an ARRAY, there are few options too:
{% if arrayVariable[0] is defined %}
#if variable is not null#
{% endif %}
OR
{% if arrayVariable|length > 0 %}
#if variable is not null#
{% endif %}
This will only works if your array is defined
AND is NULL
A minor but notable advantage of a list over a tuple is that lists tend to be slightly more portable. Standard tools are less likely to support tuples. JSON, for example, does not have a tuple type. YAML does, but its syntax is ugly compared to its list syntax, which is quite nice.
In those cases, you may wish to use a tuple internally then convert to list as part of an export process. Alternately, you might want to use lists everywhere for consistency.
This variant is much shorter
try { final File path = new File( Environment.getExternalStorageDirectory(), "DBO_logs5"); if (!path.exists()) { path.mkdir(); } Runtime.getRuntime().exec( "logcat -d -f " + path + File.separator + "dbo_logcat" + ".txt"); } catch (IOException e) { e.printStackTrace(); }
try this:
SELECT model, date
FROM doc
WHERE date = (SELECT MAX(date)
FROM doc GROUP BY model LIMIT 0, 1)
GROUP BY model
This should work.
string temp = mystring.Replace("\n", "");
Are you sure there are actual \n new lines in your original string?
You can create an alias to open a file in your default editor by appending the following line to your .gitconfig file:
edit = "!f() { $(git config core.editor) -- $@; }; f"
Then, git edit foo.txt
will open the file foo.txt
for editing.
It's much easier to open .gitconfig with git config --global --edit
and paste the line, rather than figure out how to escape all the characters to enter the alias directly from the command line with git config alias.edit "..."
!
starts a bash command, not an internal git commandf() {...};
starts a function$(git config core.editor)
will get the name of your editor, from the local config, or the global if the local is not set. Unfortunately it will not look in $VISUAL
or $EDITOR
for this, if none is set.--
separates the editor command with the file list. This works for most command line editors, so is safer to put in. If skipped and the core.editor
is not set then it is possible that an executable file is executed instead of being edited. With it here, the command will just fail.$@
will add the files entered at the command line.f
will execute the function after it is defined.The other answers express doubt as to why you would want this. My use case is that I want to edit files as part of other git functions that I am building, and I want to edit them in the same editor that the user has configured. For example, the following is one of my aliases:
reedit = "!f() { $(git config core.editor) -- $(git diff --name-only $1); }; f"
Then, git reedit
will open all the files that I have already started modifying, and git reedit --cached
will open all the staged files.
This:
document.getElementById('myField').onblur();
works because your element (the <input>
) has an attribute called "onblur" whose value is a function. Thus, you can call it. You're not telling the browser to simulate the actual "blur" event, however; there's no event object created, for example.
Elements do not have a "blur" attribute (or "method" or whatever), so that's why the first thing doesn't work.
I like the two line approach of jmh_gr.
It won't work with single digit numbers unless you put ()
around the portion of the command before the redirect. since 1>
is a special command "Echo is On" will be redirected to the file.
This example should take care of single digit numbers but not the other special characters such as <
that may be in the string.
(ECHO %strvar%)> tempfile.txt
With Mercurial you do a
$ hg grep "search for this" [file...]
There are other options that narrow down the range of revisions that are searched.
Use
var arrayNames = (from DataColumn x in dt.Columns
select x.ColumnName).ToArray();
int day=0,month=0,year=0;
DateTime smallDate = Convert.ToDateTime(string.Format("{0}", "01.01.1900"));
DateTime bigDate = Convert.ToDateTime(string.Format("{0}", "05.06.2019"));
TimeSpan timeSpan = new TimeSpan();
//timeSpan is diff between bigDate and smallDate as days
timeSpan = bigDate - smallDate;
//year is totalDays / 365 as int
year = timeSpan.Days / 365;
//smallDate.AddYears(year) is closing the difference for year because we found the year variable
smallDate = smallDate.AddYears(year);
//again subtraction because we don't need the year now
timeSpan = bigDate - smallDate;
//month is totalDays / 30 as int
month = timeSpan.Days / 30;
//smallDate.AddMonths(month) is closing the difference for month because we found the month variable
smallDate = smallDate.AddMonths(month);
if (bigDate > smallDate)
{
timeSpan = bigDate - smallDate;
day = timeSpan.Days;
}
//else it is mean already day is 0
In VS2010, right click the project in the Solution Explorer and select 'Add Deployable Dependencies'. Then check the MVC related check boxes in the following dialog.
This creates a '_bin_deployableAssemblies' folder in the project which contains all the .dll files mentioned in other answers. I believe these get copied to the bin folder when creating a deployment package.
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
The difference is not just for Chrome but for most of the web browsers.
F5
refreshes the web page and often reloads the same page from the cached contents of the web browser. However, reloading from cache every time is not guaranteed and it also depends upon the cache expiry.
Shift + F5
forces the web browser to ignore its cached contents and retrieve a fresh copy of the web page into the browser.
Shift + F5
guarantees loading of latest contents of the web page.
However, depending upon the size of page, it is usually slower than F5
.
You may want to refer to: What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?
In my case this error was provoked by a size of a string column. What was weird was when I executed the exact same query in different tool, repeated values nor null values weren't there.
Then I discovered that the size of a string column size was 50 so when I called the fill method the value was chopped, throwing this exception.
I click on the column and set in the properties the size to 200 and the error was gone.
Hope this help
Check what $TERM gives: mine is xterm-color and ls -alG then does colorised output.
Get all the outdated packages and create a batch file with the following commands pip install xxx --upgrade for each outdated packages
It is not possible to use relative paths for AuthUserFile:
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the
ServerRoot
.
You have to accept and work around that limitation.
We're using IfDefine
together with an apache2 command line parameter:
.htaccess
(suitable for both development and live systems):<IfDefine !development>
AuthType Basic
AuthName "Say the secret word"
AuthUserFile /var/www/hostname/.htpasswd
Require valid-user
</IfDefine>
Append the following to /etc/apache2/envvars
:
export APACHE_ARGUMENTS=-Ddevelopment
Restart your apache afterwards and you'll get a password prompt only when you're not on the development server.
You can of course add another IfDefine for the development server, just copy the block and remove the !
.
I would change the query in the following ways:
group by
.left outer join
to ensure that all data is available.count(<fieldname>)
you can eliminate the comparisons to is null
. This is important for the second and third calculated values.mde
table. These use mde.mdeid
.The following version follows your example by using union all
:
SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
SUM(TOTALMAILED) as TotalMailed,
SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
from MailDataExtract
where SentDate is not null
group by SentDate
) union all
(select MDE.ReturnMailDate AS ReceiptDate, 0,
COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by MDE.ReturnMailDate;
)
) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;
The following does something similar using full outer join
:
SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
from MailDataExtract
where SentDate is not null
group by cast(SentDate as date)
) sd full outer join
(select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by cast(MDE.ReturnMailDate as date)
) mde
on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;
In my case, .composer
was owned by root, so I did sudo rm -fr .composer
and then my global require worked.
Be warned! You don't wanna use that command if you are not sure what you are doing.
Mod-rewrite based solution :
Using the following code in htaccess automatically forwards all http requests to https.
RewriteEngine on
RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
This will redirect your non-www and www http requests to www version of https.
Another solution (Apache 2.4*)
RewriteEngine on
RewriteCond %{REQUEST_SCHEME}::%{HTTP_HOST} ^http::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
This doesn't work on lower versions of apache as %{REQUEST_SCHEME} variable was added to mod-rewrite since 2.4.
Check you have:
1- Access to Internet connectivity.
2- The permission for internet is present in the manifest.
3- The url host is valid and registered in a trusted domain name server.
Use following code to show menu instead go to href addres
function show_more_menu(e) {_x000D_
if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
I had also the same problem. Please add this line in application tag in manifest. I hope it will also help you.
android:usesCleartextTraffic="true"
For long response bodies (and various other similar situations), the solution I use is always to pipe to less
, so
curl -i https://api.github.com/users | less
or
curl -s -D - https://api.github.com/users | less
will do the job.
ResultSet rsTst = hiSession.connection().prepareStatement(queryStr).executeQuery();
ResultSetMetaData meta = rsTst.getMetaData();
int columnCount = meta.getColumnCount();
// The column count starts from 1
String nameValuePair = "";
while (rsTst.next()) {
for (int i = 1; i < columnCount + 1; i++ ) {
String name = meta.getColumnName(i);
// Do stuff with name
String value = rsTst.getString(i); //.getObject(1);
nameValuePair = nameValuePair + name + "=" +value + ",";
//nameValuePair = nameValuePair + ", ";
}
nameValuePair = nameValuePair+"||" + "\t";
}
Python 3 handles strings a bit different. Originally there was just one type for
strings: str
. When unicode gained traction in the '90s the new unicode
type
was added to handle Unicode without breaking pre-existing code1. This is
effectively the same as str
but with multibyte support.
In Python 3 there are two different types:
bytes
type. This is just a sequence of bytes, Python doesn't know
anything about how to interpret this as characters.str
type. This is also a sequence of bytes, but Python knows how to
interpret those bytes as characters.unicode
type was dropped. str
now supports unicode.In Python 2 implicitly assuming an encoding could cause a lot of problems; you
could end up using the wrong encoding, or the data may not have an encoding at
all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to
guess) is often a lot better and much more in line with the "Python philosophy"
of "explicit is better than implicit".
This change is incompatible with Python 2 as many return values have changed,
leading to subtle problems like this one; it's probably the main reason why
Python 3 adoption has been so slow. Since Python doesn't have static typing2
it's impossible to change this automatically with a script (such as the bundled
2to3
).
str
to bytes
with bytes('h€llo', 'utf-8')
; this should
produce b'H\xe2\x82\xacllo'
. Note how one character was converted to three
bytes.bytes
to str
with b'H\xe2\x82\xacllo'.decode('utf-8')
.Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.
In your specific piece of code, nextline
is of type bytes
, not str
,
reading stdout
and stdin
from subprocess
changed in Python 3 from str
to
bytes
. This is because Python can't be sure which encoding this uses. It
probably uses the same as sys.stdin.encoding
(the encoding of your system),
but it can't be sure.
You need to replace:
sys.stdout.write(nextline)
with:
sys.stdout.write(nextline.decode('utf-8'))
or maybe:
sys.stdout.write(nextline.decode(sys.stdout.encoding))
You will also need to modify if nextline == ''
to if nextline == b''
since:
>>> '' == b''
False
Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.
1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A'
) and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')
). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.
2 Yes, you can use function annotations, but it's a comparatively new feature and little used.
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
Also works fine within a class:
def update_property(self, property, value):
setattr(self, property, value)
You can also do more succinctly:
df.sort_index(axis=1)
Make sure you assign the result back:
df = df.sort_index(axis=1)
Or, do it in-place:
df.sort_index(axis=1, inplace=True)
In my case, I had copied some code from another project that was using Automapper - took me ages to work that one out. Just had to add automapper nuget package to project.
You can also convert by creating a dictionary of elements and then directly converting to a data frame:
import xml.etree.ElementTree as ET
import pandas as pd
# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags> <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" /> <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" /> <row Id="3" TagName="elicitation" Count="10" /> <row Id="5" TagName="open-source" Count="16" /> </tags>
root = ET.parse('test.xml').getroot()
tags = {"tags":[]}
for elem in root:
tag = {}
tag["Id"] = elem.attrib['Id']
tag["TagName"] = elem.attrib['TagName']
tag["Count"] = elem.attrib['Count']
tags["tags"]. append(tag)
df_users = pd.DataFrame(tags["tags"])
df_users.head()
.html(''). was the only method that solved it for me.
By default, git will update execute file permissions if you change them. It will not change or track any other permissions.
If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.
Look into your project, in the .git
folder for the config
file and you should see something like this:
[core]
filemode = false
You can either change it to true
in your favorite text editor, or run:
git config core.filemode true
Then, you should be able to commit normally your files. It will only commit the permission changes.
Sleep is used in cases where independent program(s) that you have no control over may sometimes use a commonly used resource (say, a file), that your program needs to access when it runs, and when the resource is in use by these other programs your program is blocked from using it. In this case, where you access the resource in your code, you put your access of the resource in a try-catch (to catch the exception when you can't access the resource), and you put this in a while loop. If the resource is free, the sleep never gets called. But if the resource is blocked, then you sleep for an appropriate amount of time, and attempt to access the resource again (this why you're looping). However, bear in mind that you must put some kind of limiter on the loop, so it's not a potentially infinite loop. You can set your limiting condition to be N number of attempts (this is what I usually use), or check the system clock, add a fixed amount of time to get a time limit, and quit attempting access if you hit the time limit.
I got this error because I was trying to run
javac HelloWorld.java && java HelloWorld.class
when I should have removed .class
:
javac HelloWorld.java && java HelloWorld
What should I do to prepare my website for https. (Do I need to alter the code / Config)
You should keep best practices for secure coding in mind (here is a good intro: http://www.owasp.org/index.php/Secure_Coding_Principles ), otherwise all you need is a correctly set up SSL certificate.
Is SSL and https one and the same..
Pretty much, yes.
Do I need to apply with someone to get some license or something.
You can buy an SSL certificate from a certificate authority or use a self-signed certificate. The ones you can purchase vary wildly in price - from $10 to hundreds of dollars a year. You would need one of those if you set up an online shop, for example. Self-signed certificates are a viable option for an internal application. You can also use one of those for development. Here's a good tutorial on how to set up a self-signed certificate for IIS: Enabling SSL on IIS 7.0 Using Self-Signed Certificates
Do I need to make all my pages secured or only the login page..
Use HTTPS for everything, not just the initial user login. It's not going to be too much of an overhead and it will mean the data that the users send/receive from your remotely hosted application cannot be read by outside parties if it is intercepted. Even Gmail now turns on HTTPS by default.
Essentially, a List<>
in .NET is a wrapper over an array. A LinkedList<>
is a linked list. So the question comes down to, what is the difference between an array and a linked list, and when should an array be used instead of a linked list. Probably the two most important factors in your decision of which to use would come down to:
Here's how I did it:
void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
{
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
void sha256_string(char *string, char outputBuffer[65])
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(hash, &sha256);
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
int sha256_file(char *path, char outputBuffer[65])
{
FILE *file = fopen(path, "rb");
if(!file) return -534;
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
const int bufSize = 32768;
unsigned char *buffer = malloc(bufSize);
int bytesRead = 0;
if(!buffer) return ENOMEM;
while((bytesRead = fread(buffer, 1, bufSize, file)))
{
SHA256_Update(&sha256, buffer, bytesRead);
}
SHA256_Final(hash, &sha256);
sha256_hash_string(hash, outputBuffer);
fclose(file);
free(buffer);
return 0;
}
It's called like this:
static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);
First of all I recommend this
video may this is clears all yours doubts
If not please go through it
Procedure for decoding .apk files, step-by-step method:
Step 1:
Make a new folder and put .apk file in it (which you want to decode). Now rename the extension of this .apk
file to .zip
(eg.: rename from filename.apk to filename.zip) and save it.
If problems in the converting into .zip please refers link
After getting .zip now you get classes.dex files, etc. At this stage you are able to see drawable but not xml and java files, so continue. If you don’t see the extensions go through check the configuration
Step 2:
Now extract this zip apk file in the same folder. Now download dex2jar from this link
and extract it to the same folder. Now open command prompt and change directory to that folder.
Then write dex2jar classes.dex
and press enter. Now you get classes.dex.dex2jar
file in the same folder.
Then download java decompiler
And now double click on jd-gui and click on open file. Then open classes.dex.dex2jar
file from that folder. Now you get class files and save all these class files (click on file then click "save all sources" in jd-gui) by src name. Extract that zip file (classes_dex2jar.src.zip)
and you will get all java files of the application.
At this stage you get java source but the xml files are still unreadable, so continue.
Step 3:
Now open another new folder and put these files
put .apk file which you want to decode
download Apktool for windows v1.x
And Apktool
install window using google and put in the same folder
download framework-res.apk file using google and put in the same folder (Not all apk file need framework-res.apk file)
Open a command window
Navigate to the root directory of APKtool and type the following command:
apktool if framework-res.apk.
Above command should result in Framework installed ...
.
Step 4:
Finally we got the res/
as well as java code of project which is our target at starting.
P.S.
If you are not able to get res folder by above steps please do install newapktool
- Is Java 1.7 installed? Install Apktool 2.x
- Is Java 1.6 or higher installed? Install Apktool 1.x
Enjoy and happy coding
To avoid this exception you can take help of VM arguments just as I used in Spring 1.5.8.RELEASE:
-Dspring.http.multipart.maxFileSize=70Mb
-Dspring.http.multipart.maxRequestSize=70Mb
Same as Sergii Pozharov's answer, but with a PowerShell cmdlet:
New-Service -Name "MyService" -BinaryPathName "C:\Path\to\myservice.exe"
See New-Service
for more customization.
This will only work for executables that already implement the Windows Services API.
The only software that I found that already exists is Matrox PowerDesk. Among other things it lets you split a monitor into 2 virtual desktops. You have to have a compatible matrox video card though. It also does a bunch of other multi-monitor functions.
I used to get such an error. I found a more reliable solution. I have mentioned the import statements too which have worked for me. The below piece of code perfectly mocks restemplate.
import org.mockito.Matchers;
import static org.mockito.Matchers.any;
HttpHeaders headers = new Headers();
headers.setExpires(10000L);
ResponseEntity<String> responseEntity = new ResponseEntity<>("dummyString", headers, HttpStatus.OK);
when(restTemplate.exchange( Matchers.anyString(),
Matchers.any(HttpMethod.class),
Matchers.<HttpEntity<?>> any(),
Matchers.<Class<String>> any())).thenReturn(responseEntity);
I think I tried everything mentioned here, and it still didn't work. Turns out it didn't recognize my domain login to the server as being in the Administrators group because it was implicit through my membership in another group ( Developers ) which is a member of the Administrators group.
I added my individual domain\login to the Administrators group explicitly, logged off and then logged back on to the box, and IE admitted me to the Report Manager homepage without requiring me to run IE as administrator.
This might be completely off base, but can't you just copy the whole column into a new spreadsheet and then sort the column? I'm assuming that you don't need to maintain the order integrity.
Use XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
We had the same problem sometime ago where a site suddenly began giving this error. The reason was that a js include was temporarily remarked with a # (i.e. src="#./js...").
Before everyone jumps on the 'You can't delete rows in an Enumeration' bandwagon, you need to first realize that DataTables are transactional, and do not technically purge changes until you call AcceptChanges()
If you are seeing this exception while calling Delete, you are already in a pending-changes data state. For instance, if you have just loaded from the database, calling Delete would throw an exception if you were inside a foreach loop.
BUT! BUT!
If you load rows from the database and call the function 'AcceptChanges()' you commit all of those pending changes to the DataTable. Now you can iterate through the list of rows calling Delete() without a care in the world, because it simply ear-marks the row for Deletion, but is not committed until you again call AcceptChanges()
I realize this response is a bit dated, but I had to deal with a similar issue recently and hopefully this saves some pain for a future developer working on 10-year-old code :)
P.s. Here is a simple code example added by Jeff:
C#
YourDataTable.AcceptChanges();
foreach (DataRow row in YourDataTable.Rows) {
// If this row is offensive then
row.Delete();
}
YourDataTable.AcceptChanges();
VB.Net
ds.Tables(0).AcceptChanges()
For Each row In ds.Tables(0).Rows
ds.Tables(0).Rows(counter).Delete()
counter += 1
Next
ds.Tables(0).AcceptChanges()
List:
List allows duplicate elements and null values. Easy to search using the corresponding index of the elements and also it will display elements in insertion order.
Example:(linkedlist)
import java.util.*;
public class ListExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> l=new LinkedList<Integer>();
l.add(001);
l.add(555);
l.add(333);
l.add(888);
l.add(555);
l.add(null);
l.add(null);
Iterator<Integer> il=l.iterator();
System.out.println(l.get(0));
while(il.hasNext()){
System.out.println(il.next());
}
for(Integer str : l){
System.out.println("Value:"+str);
}
}
}
Output:
1
1
555
333
888
555
null
null
Value:1
Value:555
Value:333
Value:888
Value:555
Value:null
Value:null
Set:
Set isn't allow any duplicate elements and it allow single null value.It will not maintain any order to display elements.Only TreeSet
will display in ascending order.
Example:(TreeSet)
import java.util.TreeSet;
public class SetExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<String> set = new TreeSet<String>();
try {
set.add("hello");
set.add("world");
set.add("welcome");
set.add("all");
for (String num : set) {
System.out.println( num);
}
set.add(null);
} catch (NullPointerException e) {
System.out.println(e);
System.out.println("Set doesn't allow null value and duplicate value");
}
}
}
Output:
all
hello
welcome
world
java.lang.NullPointerException
Set doesn't allow null value and duplicate value
My response is fairly late. I faced the same problem. I am on Windows 10. This is what I did:
set myvar1=myvalue1
code
and then press ENTER
Optionally, you can also use the Control Panel -> System properties window to set the variables on a more permanent basis
Hope this helps.
To change the size of (almost) all text elements, in one place, and synchronously, rel()
is quite efficient:
g+theme(text = element_text(size=rel(3.5))
You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)),
strip.text.x = element_text(size=rel(3.5)),
strip.text.y = element_text(size=rel(3.5)))
I had some strings in the MongoDB Stored wich had to be reformated to a proper and valid dateTime field in the mongodb.
here is my code for the special date format: "2014-03-12T09:14:19.5303017+01:00"
but you can easyly take this idea and write your own regex to parse the date formats:
// format: "2014-03-12T09:14:19.5303017+01:00"
var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/;
db.Product.find().forEach(function(doc) {
var matches = myregexp.exec(doc.metadata.insertTime);
if myregexp.test(doc.metadata.insertTime)) {
var offset = matches[9] * (matches[8] == "+" ? 1 : -1);
var hours = matches[4]-(-offset)+1
var date = new Date(matches[1], matches[2]-1, matches[3],hours, matches[5], matches[6], matches[7] / 10000.0)
db.Product.update({_id : doc._id}, {$set : {"metadata.insertTime" : date}})
print("succsessfully updated");
} else {
print("not updated");
}
})
this
SELECT field,datetime_field
FROM database
WHERE datetime_field > (sysdate-1)
will work. The question is: is the 'datetime_field' has the same format as sysdate ? My way to handle that: use 'to_char()' function (only works in Oracle).
samples: previous day:
select your_column
from your_table
where to_char(sysdate-1, 'dd.mm.yyyy')
or
select extract(day from date_field)||'/'||
extract(month from date_field)||'/'||
extract(year from date_field)||'/'||
as mydate
from dual(or a_table)
where extract(day from date_field) = an_int_number and
extract(month from date_field) = an_int_number and so on..
comparing date:
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate, 'dd.mm.yyyy')
time range between yesterday and a day before yesterday:
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-1, 'dd.mm.yyyy') and
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-2, 'dd.mm.yyyy')
other time range variation
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') is between to_char(sysdate-1, 'dd.mm.yyyy')
and to_char(sysdate-2, 'dd.mm.yyyy')
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)
In swift 3, We can simply use DispatchQueue.main.asyncAfter function to trigger any function or action after the delay of 'n' seconds. Here in code we have set delay after 1 second. You call any function inside the body of this function which will trigger after the delay of 1 second.
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {
// Trigger the function/action after the delay of 1Sec
}
I know that if you were to change that to an href you'd do:
$("a#link1").click(function(event) { event.preventDefault(); $('div.link1').show(); //whatever else you want to do });
so if you want to keep it with the div, I'd try
$("div.clickable").click(function(event) { event.preventDefault(); window.location = $(this).attr("url"); });
I improved upon psycho brm's filterByData extension to jQuery.
Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.
(function ($) {
$.fn.filterByData = function (prop, val) {
var $self = this;
if (typeof val === 'undefined') {
return $self.filter(
function () { return typeof $(this).data(prop) !== 'undefined'; }
);
}
return $self.filter(
function () { return $(this).data(prop) == val; }
);
};
})(window.jQuery);
Usage:
$('<b>').data('x', 1).filterByData('x', 1).length // output: 1
$('<b>').data('x', 1).filterByData('x').length // output: 1
// test data_x000D_
function extractData() {_x000D_
log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);_x000D_
log('data-prop .......... ' + $('div').filterByData('prop').length);_x000D_
log('data-random ........ ' + $('div').filterByData('random').length);_x000D_
log('data-test .......... ' + $('div').filterByData('test').length);_x000D_
log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);_x000D_
}_x000D_
_x000D_
$(document).ready(function() {_x000D_
$('#b5').data('test', 'anyval');_x000D_
});_x000D_
_x000D_
// the actual extension_x000D_
(function($) {_x000D_
_x000D_
$.fn.filterByData = function(prop, val) {_x000D_
var $self = this;_x000D_
if (typeof val === 'undefined') {_x000D_
return $self.filter(_x000D_
_x000D_
function() {_x000D_
return typeof $(this).data(prop) !== 'undefined';_x000D_
});_x000D_
}_x000D_
return $self.filter(_x000D_
_x000D_
function() {_x000D_
return $(this).data(prop) == val;_x000D_
});_x000D_
};_x000D_
_x000D_
})(window.jQuery);_x000D_
_x000D_
_x000D_
//just to quickly log_x000D_
function log(txt) {_x000D_
if (window.console && console.log) {_x000D_
console.log(txt);_x000D_
//} else {_x000D_
// alert('You need a console to check the results');_x000D_
}_x000D_
$("#result").append(txt + "<br />");_x000D_
}
_x000D_
#bPratik {_x000D_
font-family: monospace;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="bPratik">_x000D_
<h2>Setup</h2>_x000D_
<div id="b1" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
<div id="b2" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
<div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div>_x000D_
<div id="b4" data-test="val">Data added inline :: data-test="val"</div>_x000D_
<div id="b5">Data will be added via jQuery</div>_x000D_
<h2>Output</h2>_x000D_
<div id="result"></div>_x000D_
_x000D_
<hr />_x000D_
<button onclick="extractData()">Reveal</button>_x000D_
</div>
_x000D_
Or the fiddle: http://jsfiddle.net/PTqmE/46/
Accurate explanation from Armin Ronacher above, expanding on his answers so that beginners like me understand it well:
Difference in the methods defined in a class, whether static or instance method(there is yet another type - class method - not discussed here so skipping it), lay in the fact whether they are somehow bound to the class instance or not. For example, say whether the method receives a reference to the class instance during runtime
class C:
a = []
def foo(self):
pass
C # this is the class object
C.a # is a list object (class property object)
C.foo # is a function object (class property object)
c = C()
c # this is the class instance
The __dict__
dictionary property of the class object holds the reference to all the properties and methods of a class object and thus
>>> C.__dict__['foo']
<function foo at 0x17d05b0>
the method foo is accessible as above. An important point to note here is that everything in python is an object and so references in the dictionary above are themselves pointing to other objects. Let me call them Class Property Objects - or as CPO within the scope of my answer for brevity.
If a CPO is a descriptor, then python interpretor calls the __get__()
method of the CPO to access the value it contains.
In order to determine if a CPO is a descriptor, python interpretor checks if it implements the descriptor protocol. To implement descriptor protocol is to implement 3 methods
def __get__(self, instance, owner)
def __set__(self, instance, value)
def __delete__(self, instance)
for e.g.
>>> C.__dict__['foo'].__get__(c, C)
where
self
is the CPO (it could be an instance of list, str, function etc) and is supplied by the runtimeinstance
is the instance of the class where this CPO is defined (the object 'c' above) and needs to be explicity supplied by usowner
is the class where this CPO is defined(the class object 'C' above) and needs to be supplied by us. However this is because we are calling it on the CPO. when we call it on the instance, we dont need to supply this since the runtime can supply the instance or its class(polymorphism)value
is the intended value for the CPO and needs to be supplied by usNot all CPO are descriptors. For example
>>> C.__dict__['foo'].__get__(None, C)
<function C.foo at 0x10a72f510>
>>> C.__dict__['a'].__get__(None, C)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__get__'
This is because the list class doesnt implement the descriptor protocol.
Thus the argument self in c.foo(self)
is required because its method signature is actually this C.__dict__['foo'].__get__(c, C)
(as explained above, C is not needed as it can be found out or polymorphed)
And this is also why you get a TypeError if you dont pass that required instance argument.
If you notice the method is still referenced via the class Object C and the binding with the class instance is achieved via passing a context in the form of the instance object into this function.
This is pretty awesome since if you chose to keep no context or no binding to the instance, all that was needed was to write a class to wrap the descriptor CPO and override its __get__()
method to require no context.
This new class is what we call a decorator and is applied via the keyword @staticmethod
class C(object):
@staticmethod
def foo():
pass
The absence of context in the new wrapped CPO foo
doesnt throw an error and can be verified as follows:
>>> C.__dict__['foo'].__get__(None, C)
<function foo at 0x17d0c30>
Use case of a static method is more of a namespacing and code maintainability one(taking it out of a class and making it available throughout the module etc).
It maybe better to write static methods rather than instance methods whenever possible, unless ofcourse you need to contexualise the methods(like access instance variables, class variables etc). One reason is to ease garbage collection by not keeping unwanted reference to objects.
I believe - your Laravel files/folders should not be placed in root directory.
e.g. If your domain is pointed to public_html
directory then all content should placed in that directory. How ? let me tell you
Open your bootstrap/paths.php and then changed 'public' => __DIR__.'/../public',
into 'public' => __DIR__.'/..',
and finally in index.php,
Change
require __DIR__.'/../bootstrap/autoload.php'; $app = require_once __DIR__.'/../bootstrap/start.php';
into
require __DIR__.'/bootstrap/autoload.php'; $app = require_once __DIR__.'/bootstrap/start.php';
Your Laravel application should work now.
Old question, but apparently Google likes it so I thought I put an answer down here after some research about this problem.
If you create a figure from scratch you can give it a size option while creation:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(3, 6))
plt.plot(range(10)) #plot example
plt.show() #for control
fig.savefig('temp.png', dpi=fig.dpi)
figsize(width,height) adjusts the absolute dimension of your plot and helps to make sure both plots look the same.
As stated in another answer the dpi option affects the relative size of the text and width of the stroke on lines, etc. Using the option dpi=fig.dpi makes sure the relative size of those are the same both for show() and savefig().
Alternatively the figure size can be changed after creation with:
fig.set_size_inches(3, 6, forward=True)
forward allows to change the size on the fly.
If you have trouble with too large borders in the created image you can adjust those either with:
plt.tight_layout()
#or:
plt.tight_layout(pad=2)
or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight')
#or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight', pad_inches=0.5)
The first option just minimizes the layout and borders and the second option allows to manually adjust the borders a bit. These tips helped at least me to solve my problem of different savefig() and show() images.
Following recursive function I have written, if it helps anyone. It will copy all the files inside sourcedirectory to destinationDirectory.
example:
rfunction("D:/MyDirectory", "D:/MyDirectoryNew", "D:/MyDirectory");
public static void rfunction(String sourcePath, String destinationPath, String currentPath) {
File file = new File(currentPath);
FileInputStream fi = null;
FileOutputStream fo = null;
if (file.isDirectory()) {
String[] fileFolderNamesArray = file.list();
File folderDes = new File(destinationPath);
if (!folderDes.exists()) {
folderDes.mkdirs();
}
for (String fileFolderName : fileFolderNamesArray) {
rfunction(sourcePath, destinationPath + "/" + fileFolderName, currentPath + "/" + fileFolderName);
}
} else {
try {
File destinationFile = new File(destinationPath);
fi = new FileInputStream(file);
fo = new FileOutputStream(destinationPath);
byte[] buffer = new byte[1024];
int ind = 0;
while ((ind = fi.read(buffer))>0) {
fo.write(buffer, 0, ind);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (null != fi) {
try {
fi.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != fo) {
try {
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Correct way (if you are not trying to reset the value of the hidden_field input) is:
f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form
Where :method
is the method that when called on the object results in the value you want
So following the example above:
= simple_form_for @movie do |f|
= f.hidden :title, "some value"
= f.button :submit
The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:
= simple_form_for @movie do |f|
= f.hidden :title, :value => params[:movie][:title]
= f.button :submit
Again only use my answer is you do not want to reset the value submitted by the user.
I hope this makes sense.
a += b
is in this case the same as
a = a + b
In this case cnt += 1 means that cnt is increased by one.
Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.
Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.
command = "ls *"
def execute_state=sh(returnStdout: true, script: command)
but if the command failure the process will terminate
you can use window.confirm inside your function combined with if condition
delete(whatever:any){
if(window.confirm('Are sure you want to delete this item ?')){
//put your delete method logic here
}
}
when you call the delete method it will popup a confirmation message and when you press ok it will perform all the logic inside the if condition.
SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.
As it happens, you are close. Just need leading+trailing wildcards and move the NOT
WHERE whatever NOT LIKE '%[a-z0-9]%'
I was getting similar problem and Stating string for URL worked for me. :)
package Chrome_Example;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Launch_Chrome {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\doyes\\Downloads\\chromedriver_win324\\chromedriver.exe");
String URL = "http://www.google.com";
WebDriver driver = new ChromeDriver();
driver.get(URL);
}
}
You don't need to wrap it in a list with [..]
, just provide the subselection of the columns index:
df.drop(df.columns[[1, 69]], axis=1, inplace=True)
as the index object is already regarded as list-like.
I usually use usort, and pass my own comparison function. In this case, it is very simple:
function compareOrder($a, $b)
{
return $a['order'] - $b['order'];
}
usort($array, 'compareOrder');
In PHP 7 using spaceship operator:
usort($array, function($a, $b) {
return $a['order'] <=> $b['order'];
});
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
| | Struct | Class |
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
| Type | Value-type | Reference-type |
| Where | On stack / Inline in containing type | On Heap |
| Deallocation | Stack unwinds / containing type gets deallocated | Garbage Collected |
| Arrays | Inline, elements are the actual instances of the value type | Out of line, elements are just references to instances of the reference type residing on the heap |
| Aldel Cost | Cheap allocation-deallocation | Expensive allocation-deallocation |
| Memory usage | Boxed when cast to a reference type or one of the interfaces they implement, | No boxing-unboxing |
| | Unboxed when cast back to value type | |
| | (Negative impact because boxes are objects that are allocated on the heap and are garbage-collected) | |
| Assignments | Copy entire data | Copy the reference |
| Change to an instance | Does not affect any of its copies | Affect all references pointing to the instance |
| Mutability | Should be immutable | Mutable |
| Population | In some situations | Majority of types in a framework should be classes |
| Lifetime | Short-lived | Long-lived |
| Destructor | Cannot have | Can have |
| Inheritance | Only from an interface | Full support |
| Polymorphism | No | Yes |
| Sealed | Yes | When have sealed keyword |
| Constructor | Can not have explicit parameterless constructors | Any constructor |
| Null-assignments | When marked with nullable question mark | Yes (+ When marked with nullable question mark in C# 8+) |
| Abstract | No | When have abstract keyword |
| Member Access Modifiers| public, private, internal | public, protected, internal, protected internal, private protected |
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
for any1 using ie8 and dont want to use a plugin i've made something inspired by Rohit Azad and Bacotasan's blog, i just added a span using JS to show the selected value.
the html:
<div class="styled-select">
<select>
<option>Here is the first option</option>
<option>The second option</option>
</select>
<span>Here is the first option</span>
</div>
the css (i used only an arrow for BG but you could put a full image and drop the positioning):
.styled-select div
{
display:inline-block;
border: 1px solid darkgray;
width:100px;
background:url("/Style Library/Nifgashim/Images/drop_arrrow.png") no-repeat 10px 10px;
position:relative;
}
.styled-select div select
{
height: 30px;
width: 100px;
font-size:14px;
font-family:ariel;
-moz-opacity: 0.00;
opacity: .00;
filter: alpha(opacity=00);
}
.styled-select div span
{
position: absolute;
right: 10px;
top: 6px;
z-index: -5;
}
the js:
$(".styled-select select").change(function(e){
$(".styled-select span").html($(".styled-select select").val());
});
An easy way to do this is to process each character of the string with each delimiter and build an array of the splits:
splix = function ()
{
u = [].slice.call(arguments); v = u.slice(1); u = u[0]; w = [u]; x = 0;
for (i = 0; i < u.length; ++i)
{
for (j = 0; j < v.length; ++j)
{
if (u.slice(i, i + v[j].length) == v[j])
{
y = w[x].split(v[j]); w[x] = y[0]; w[++x] = y[1];
};
};
};
return w;
};
console.logg = function ()
{
document.body.innerHTML += "<br>" + [].slice.call(arguments).join();
}
splix = function() {
u = [].slice.call(arguments);
v = u.slice(1);
u = u[0];
w = [u];
x = 0;
console.logg("Processing: <code>" + JSON.stringify(w) + "</code>");
for (i = 0; i < u.length; ++i) {
for (j = 0; j < v.length; ++j) {
console.logg("Processing: <code>[\x22" + u.slice(i, i + v[j].length) + "\x22, \x22" + v[j] + "\x22]</code>");
if (u.slice(i, i + v[j].length) == v[j]) {
y = w[x].split(v[j]);
w[x] = y[0];
w[++x] = y[1];
console.logg("Currently processed: " + JSON.stringify(w) + "\n");
};
};
};
console.logg("Return: <code>" + JSON.stringify(w) + "</code>");
};
setTimeout(function() {
console.clear();
splix("1.23--4", ".", "--");
}, 250);
_x000D_
@import url("http://fonts.googleapis.com/css?family=Roboto");
body {font: 20px Roboto;}
_x000D_
Usage:
splix(string, delimiters...)
Example:
splix("1.23--4", ".", "--")
Returns:
["1", "23", "4"]
In ECS6, one may use Array.from()
:
const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
listArray.forEach((item) => {console.log(item)});
We can use [(ngModel)] in following way and have a value selection variable radioSelected
app.component.html
<div class="text-center mt-5">
<h4>Selected value is {{radioSel.name}}</h4>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of itemsList">
<input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/>
{{item.name}}
</li>
</ul>
</div>
<h5>{{radioSelectedString}}</h5>
</div>
app.component.ts
import {Item} from '../app/item';
import {ITEMS} from '../app/mock-data';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
radioSel:any;
radioSelected:string;
radioSelectedString:string;
itemsList: Item[] = ITEMS;
constructor() {
this.itemsList = ITEMS;
//Selecting Default Radio item here
this.radioSelected = "item_3";
this.getSelecteditem();
}
// Get row item from array
getSelecteditem(){
this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
this.radioSelectedString = JSON.stringify(this.radioSel);
}
// Radio Change Event
onItemChange(item){
this.getSelecteditem();
}
}
Sample Data for Listing
export const ITEMS: Item[] = [
{
name:'Item 1',
value:'item_1'
},
{
name:'Item 2',
value:'item_2'
},
{
name:'Item 3',
value:'item_3'
},
{
name:'Item 4',
value:'item_4'
},
{
name:'Item 5',
value:'item_5'
}
];
This solution doesn't require you to put a scrollable class on all your scrollable divs so is more general. Scrolling is allowed on all elements which are, or are children of, INPUT elements contenteditables and overflow scroll or autos.
I use a custom selector and I also cache the result of the check in the element to improve performance. No need to check the same element every time. This may have a few issues as only just written but thought I'd share.
$.expr[':'].scrollable = function(obj) {
var $el = $(obj);
var tagName = $el.prop("tagName");
return (tagName !== 'BODY' && tagName !== 'HTML') && (tagName === 'INPUT' || $el.is("[contentEditable='true']") || $el.css("overflow").match(/auto|scroll/));
};
function preventBodyScroll() {
function isScrollAllowed($target) {
if ($target.data("isScrollAllowed") !== undefined) {
return $target.data("isScrollAllowed");
}
var scrollAllowed = $target.closest(":scrollable").length > 0;
$target.data("isScrollAllowed",scrollAllowed);
return scrollAllowed;
}
$('body').bind('touchmove', function (ev) {
if (!isScrollAllowed($(ev.target))) {
ev.preventDefault();
}
});
}
Here is how I do it in Angular 7.3
// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {
form.reset();
Object.keys(form.controls).forEach(key => {
form.get(key).setErrors(null) ;
});
}
There was no need to call form.clearValidators()
It's quite simple:
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/html');
// do whatever you want with htmlDoc.getElementsByTagName('a');
According to MDN, to do this in chrome you need to parse as XML like so:
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(txt, 'text/xml');
// do whatever you want with htmlDoc.getElementsByTagName('a');
It is currently unsupported by webkit and you'd have to follow Florian's answer, and it is unknown to work in most cases on mobile browsers.
Edit: Now widely supported
I found a solution, first, delete the ng file with
sudo rm /usr/bin/ng
then install nvm (you need to restart your terminal to use nvm).
then install and use node 6 via nvm
nvm install 6
nvm use 6
finally install angular cli
npm install -g @angular/cli
this worked for me, I wanted to update to v1.0 stable from 1.0.28 beta, but couldn't uninstall the beta version (same situation that you desrcibed). Hope this works
In the answer from @mariubog (https://stackoverflow.com/a/27882337/1279002) I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.
...
public ResourceOwnerPasswordResourceDetails() {
setGrantType("password");
}
...
The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form);
was not set.
See the switch in:
org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler.authenticateTokenRequest()
Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.
@EnableOAuth2Client
@Configuration
class MyConfig {
@Value("${security.oauth2.client.access-token-uri}")
private String tokenUrl;
@Value("${security.oauth2.client.client-id}")
private String clientId;
@Value("${security.oauth2.client.client-secret}")
private String clientSecret;
@Value("${security.oauth2.client.password-token}")
private String passwordToken;
@Value("${security.user.name}")
private String username;
@Value("${security.user.password}")
private String password;
@Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setAccessTokenUri(tokenUrl);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setClientAuthenticationScheme(AuthenticationScheme.form);
resource.setUsername(username);
resource.setPassword(password + passwordToken);
return resource;
}
@Bean
public OAuth2RestOperations restTemplate() {
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
}
}
@Service
@SuppressWarnings("unchecked")
class MyService {
@Autowired
private OAuth2RestOperations restTemplate;
public MyService() {
restTemplate.getAccessToken();
}
}
The first solution above works only in IE The second solution above works only in FF
This combination of both functions works in both browsers:
//Firefox Only!!
if ($(document).height() > $(window).height()) {
// has scrollbar
$("#mtc").addClass("AdjustOverflowWidth");
alert('scrollbar present - Firefox');
} else {
$("#mtc").removeClass("AdjustOverflowWidth");
}
//Internet Explorer Only!!
(function($) {
$.fn.hasScrollBar = function() {
return this.get(0).scrollHeight > this.innerHeight();
}
})(jQuery);
if ($('#monitorWidth1').hasScrollBar()) {
// has scrollbar
$("#mtc").addClass("AdjustOverflowWidth");
alert('scrollbar present - Internet Exploder');
} else {
$("#mtc").removeClass("AdjustOverflowWidth");
}?
HTH
Applying inline-block
to the element that is to be centered and applying text-align:center
to the parent block did the trick for me.
Works even on <span>
tags.
I faced the same issue and was not able to find it out where git.exe is located. After spending so much time I fount that in my windows 8, it is located at
C:\Program Files (x86)\Git\bin
And for command line :
C:\Program Files (x86)\Git\cmd
Hope this helps someone facing the same issue.
after research i found solution with short code. first of all create a public instance on fragment and just remove your fragment on onSaveInstanceState if fragment not recreating on orientation change.
@Override
public void onSaveInstanceState(Bundle outState) {
if (null != mCalFragment) {
FragmentTransaction bt = getChildFragmentManager().beginTransaction();
bt.remove(mFragment);
bt.commit();
}
super.onSaveInstanceState(outState);
}
Use continue;
instead of break;
to enter the next iteration of the loop without executing any more of the contained code.
foreach (Item item in myItemsList)
{
if (item.Name == string.Empty)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
if (item.Weight > 100)
{
// Display error message and move to next item in list. Skip/ignore all validation
// that follows beneath
continue;
}
}
Official docs are here, but they don't add very much color.
.NET Framework provides many collection classes too. You can use Dictionary in C#. Please find the below msdn link for details and samples http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
In modern c++
you may use the <random>
header that came with c++11
.
To get random float
's you can use std::uniform_real_distribution<>
.
You can use a function to generate the numbers and if you don't want the numbers to be the same all the time, set the engine and distribution to be static
.
Example:
float get_random()
{
static std::default_random_engine e;
static std::uniform_real_distribution<> dis(0, 1); // rage 0 - 1
return dis(e);
}
It's ideal to place the float
's in a container such as std::vector
:
int main()
{
std::vector<float> nums;
for (int i{}; i != 5; ++i) // Generate 5 random floats
nums.emplace_back(get_random());
for (const auto& i : nums) std::cout << i << " ";
}
Example output:
0.0518757 0.969106 0.0985112 0.0895674 0.895542
Smultron is another good (and free) one.
The other answers are helpful, but the JSON in your question isn't valid. I have formatted it to make it clearer below, note the missing single quote on line 24.
1 {
2 'Orientation Sensor':
3 [
4 {
5 sampleTime: '1450632410296',
6 data: '76.36731:3.4651554:0.5665419'
7 },
8 {
9 sampleTime: '1450632410296',
10 data: '78.15431:0.5247617:-0.20050584'
11 }
12 ],
13 'Screen Orientation Sensor':
14 [
15 {
16 sampleTime: '1450632410296',
17 data: '255.0:-1.0:0.0'
18 }
19 ],
20 'MPU6500 Gyroscope sensor UnCalibrated':
21 [
22 {
23 sampleTime: '1450632410296',
24 data: '-0.05006743:-0.013848438:-0.0063915867
25 },
26 {
27 sampleTime: '1450632410296',
28 data: '-0.051132694:-0.0127831735:-0.003325345'
29 }
30 ]
31 }
There are a lot of great articles on how to manipulate objects in Javascript (whether using Node JS or a browser). I suggest here is a good place to start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
The best way to do it is:
return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");
'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/
Once you choose your StatusCode, return it with a message.
Try the following:
select * From emp_master
where emp_last_name=
case emp_first_name
when 'test' then 'test'
when 'Mr name' then 'name'
end
If you have SELinux running, you might have to grant httpd permission to read from /home dir using:
sudo setsebool httpd_read_user_content=1
To iterate through all files and folders you can use
for /F "delims=" %%a in ('dir /b /s') do echo %%a
To iterate through all folders only not with files, then you can use
for /F "delims=" %%a in ('dir /a:d /b /s') do echo %%a
Where /s
will give all results throughout the directory tree in unlimited depth. You can skip /s
if you want to iterate through the content of that folder not their sub folder
To iterate through a particular named files and folders you can search for the name and iterate using for loop
for /F "delims=" %%a in ('dir "file or folder name" /b /s') do echo %%a
To iterate through a particular named folders/directories and not files, then use /AD
in the same command
for /F "delims=" %%a in ('dir "folder name" /b /AD /s') do echo %%a
@Query("SELECT DISTINCT name FROM people WHERE name NOT IN (:names)")
List<String> findNonReferencedNames(@Param("names") List<String> names);
Instead of typedef struct { ... } pos;
you should be doing struct pos { ... };
. The issue here is that you are using the pos
type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.
Further, the typedef struct { ... } name;
pattern is a C-ism, and doesn't have much place in C++.
To answer your question about inline
, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline
, the compiler effectively ignores it because the method is already declared inline.
(inline
methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)
A Stacked bar chart should suffice:
Setup data as follows
Name Start End Duration (End - Start)
Fred 1/01/1981 1/06/1985 1612
Bill 1/07/1985 1/11/2000 5602
Joe 1/01/1980 1/12/2001 8005
Jim 1/03/1999 1/01/2000 306
Start
and Duration
as a stacked bar chartX-Axis minimum
to the desired start date Fill
Colour of thestart
range to no fill
Fill
of individual bars to suit(example prepared in Excel 2010)
I'm using XAMPP, in which there are several php.ini files.
You can find the line in the php.ini files:
;extension=php_curl.dll
Please remove ;
at the beginning of this line. And you may need to restart apache server.
There are precious few immutable collections in the current framework. I can think of one relatively pain-free option in .NET 3.5:
Use Enumerable.ToLookup()
- the Lookup<,>
class is immutable (but multi-valued on the rhs); you can do this from a Dictionary<,>
quite easily:
Dictionary<string, int> ids = new Dictionary<string, int> {
{"abc",1}, {"def",2}, {"ghi",3}
};
ILookup<string, int> lookup = ids.ToLookup(x => x.Key, x => x.Value);
int i = lookup["def"].Single();
Try This:
using System;
using System.Configuration;
using System.Web.Configuration;
namespace SampleApplication.WebConfig
{
public partial class webConfigFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Helps to open the Root level web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
//Modifying the AppKey from AppValue to AppValue1
webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
//Save the Modified settings of AppSettings.
webConfigApp.Save();
}
}
}
Here is an example that shows the differences, which will help with the explanation.
var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;
String
is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2
in the example above creates a new string without the use of the new
keyword and without explicitly using the String
object.
string
is the TypeScript string type, which you can use to type variables, parameters and return values.
Additional notes...
Currently (Feb 2013) Both s1
and s2
are valid JavaScript. s3
is valid TypeScript.
Use of String
. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:
var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();
If you really had a penchant for the string, you could use it in TypeScript in one of two ways...
var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type
Compare integer and print its value in value ascending or descending order. All you have to do is implements Comparator interface and override its compare method and compare its value as below:
@Override
public int compare(Integer o1, Integer o2) {
if (ascending) {
return o1.intValue() - o2.intValue();
} else {
return o2.intValue() - o1.intValue();
}
}
Is this any help?
#include <stdio.h>
#define MAX 10
int main()
{
char grid[MAX][MAX];
int i,j,row,col;
printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
printf("%c ", grid[i][j]);
}
printf("\n");
}
return 0;
}
The fully-qualified name is opbtained as follows:
String fqn = YourClass.class.getName();
But you need to read a classpath resource. So use
InputStream in = YourClass.getResourceAsStream("resource.txt");
This is another way to do it. I think maybe a little more general:
df.ix[:,-1]
It's a warning, not an error. It occurs because fsevents
is an optional dependency, used only when project is run on macOS environment (the package provides 'Native Access to Mac OS-X FSEvents').
And since you're running your project on Windows, fsevents
is skipped as irrelevant.
There is a PR to fix this behaviour here: https://github.com/npm/cli/pull/169
I tried to add the primary key afterwards by changing the sqlite_master table directly. This trick seems to work. It is a hack solution of course.
In short: create a regular (unique) index on the table, then make the schema writable and change the name of the index to the form reserved by sqlite to identify a primary key index, (i.e. sqlite_autoindex_XXX_1, where XXX is the table name) and set the sql string to NULL. At last change the table definition itself. One pittfal: sqlite does not see the index name change until the database is reopened. This seems like a bug, but not a severe one (even without reopening the database, you can still use it).
Suppose the table looks like:
CREATE TABLE tab1(i INTEGER, j INTEGER, t TEXT);
Then I did the following:
BEGIN;
CREATE INDEX pk_tab1 ON tab1(i,j);
pragma writable_schema=1;
UPDATE sqlite_master SET name='sqlite_autoindex_tab1_1',sql=null WHERE name='pk_tab1';
UPDATE sqlite_master SET sql='CREATE TABLE tab1(i integer,j integer,t text,primary key(i,j))' WHERE name='tab1';
COMMIT;
Some tests (in sqlite shell):
sqlite> explain query plan select * from tab1 order by i,j;
0|0|0|SCAN TABLE tab1 USING INDEX sqlite_autoindex_tab1_1
sqlite> drop index sqlite_autoindex_tab1_1;
Error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped
Use Convert.ToString (value, 2)
so in your case
string binValue = Convert.ToString (3, 2);
Put this in your init function:
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
It will work.
quite simple:
ul.yourlist li { float:left; }
or
ul.yourlist li { display:inline; }
On Solaris 11
Use LD_LIBRARY_PATH_64
to resolve symlink to python libs.
In my case for python3.6 LD_LIBRARY_PATH
didn't work but LD_LIBRARY_PATH_64
did.
Hope this helps.
Regards
You can use vanilla javascript by simply writing:
var width = el.clientWidth;
You could also use this to get the width of the document as follows:
var docWidth = document.documentElement.clientWidth || document.body.clientWidth;
Source: MDN
You can also get the width of the full window, including the scrollbar, as follows:
var fullWidth = window.innerWidth;
However this is not supported by all browsers, so as a fallback, you may want to use docWidth
as above, and add on the scrollbar width.
Source: MDN
Resemblence with c# string static method isNullOrWhiteSpace.
def isNullOrWhiteSpace(str):
"""Indicates whether the specified string is null or empty string.
Returns: True if the str parameter is null, an empty string ("") or contains
whitespace. Returns false otherwise."""
if (str is None) or (str == "") or (str.isspace()):
return True
return False
isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("") -> True
isNullOrWhiteSpace(" ") -> True
Ideally, margins in CSS containers should collapse, so you can define a parent container which sets its margins(s) to the minimum you want, and then use the margin(s) you want for the child, and the content of the child will use the larger margins between the parent and child margin:
if the child margin(s) are smaller than the parent margin(s)+its padding(s), then the child margins(s) will have no effect.
if the child margin(s) are larger than the parent margin(s)+its padding(s), then the parent padding(s) should be increased to fit.
This is still frequently not working as intended in CSS: currently CSS allows margin(s) of a child to collapse into the margin(s) of the parent (extending them if necesary), only if the parent defines NO padding and NO border and no intermediate sibling content exist in the parent between the child and the begining of the content box of the parent; however there may be floatting or positioned sibling elements, which are ignored for computing margins, unless they use "clear:" to also extend the parent's content-box and compltely fit their own content vertically in it (only the parent's height of the content-box is increased for the top-to-bottom or bottom-to-top block-direction of its content box, or only the parent's width for the left-to-right or right-to-left block-direction; the inline-direction of the parent's content-box plays no role) .
So if the parent defines only 1px of padding, or only 1px of border, then this stops the child from collapsing its margin into the parent's margin. Instead the child margins will take effect from the content box of the parent (or the border box of the intermediate sibling content if there's any one). This means that any non-null border or non-null padding in the parent is treated by the child as if this was a sibling content in the same parent.
So this simple solution should work: use an additional parent without any border or padding to set the minimum margin to nest the child element in it; you can still add borders or paddings to the child (if needed) where you'll defining its own secondary margin (collapsing into the parent(s) margins) !
Note that a child element may collapse its margin(s) into several levels of parents ! This means that you can define several minimums (e.g. for the minimum between 3 values, use two levels of parents to contain the child).
Sometimes 3 or more values are needed to account for: the viewport width, the document width, the section container width, the presence or absence of external floats stealing space in the container, and the minimum width needed for the child content itself. All these widths may be variable and may depend as well on the kind of browser used (including its accessibility settings, such as text zoom, or "Hi-DPI" adjustments of sizes in renderers depending on capabilities of the target viewing device, or sometimes because there's a user-tunable choice of layouts such as personal "skins" or other user's preferences, or the set of available fonts on the final rendering host, which means that exact font sizes are hard to predict safely, to match exact sizes in "pixels" for images or borders ; as well users have a wide variety of screen sizes or paper sizes if printing, and orientations ; scrolling is also not even available or possible to compensate, and truncation of overflowing contents is most often undesirable; as well using excessive "clears" is wasting space and makes the rendered document much less accessible).
We need to save space, without packing too much info and keeping clarity fore readers, and ease of navigation : a layout is a constant tradeoff, between saving space and showing more information at once to avoid additional scrolling or navigation to other pages, and keeping the packed info displayed easy to navigate or interact with).
But HTML is often not enough flexible for all goals, and even if it offers some advanced features, they becomes difficult to author or to maintain/change the documents (or the infos they contain), or readapt the content later for other goals or presentations. Keeping things simple avoids this issue and if we use these simple tricks that have nearly no cost and are easy to understand, we should use them (this will always save lot of precious time, including for web designers).