pChart is another great PHP graphing library.
Here is some resource you can read about pseudo-random number generator.
https://en.wikipedia.org/wiki/Pseudorandom_number_generator
Basically, random numbers in computer need a seed (this number can be the current system time).
Replace
std::default_random_engine generator;
By
std::default_random_engine generator(<some seed number>);
In your example, performance probalby isn't too different but there are other issues to consider: namely memory fragmentation. Even concatenate operation is creating a new string, even if its temporary (it takes time to GC it and it's more work). String.format() is just more readable and it involves less fragmentation.
Also, if you're using a particular format a lot, don't forget you can use the Formatter() class directly (all String.format() does is instantiate a one use Formatter instance).
Also, something else you should be aware of: be careful of using substring(). For example:
String getSmallString() {
String largeString = // load from file; say 2M in size
return largeString.substring(100, 300);
}
That large string is still in memory because that's just how Java substrings work. A better version is:
return new String(largeString.substring(100, 300));
or
return String.format("%s", largeString.substring(100, 300));
The second form is probably more useful if you're doing other stuff at the same time.
Using Guava
List<Object> lst ...
List<String> ls = Lists.transform(lst, Functions.toStringFunction());
If you want to hide on specific screen than do like this:
// create a component
export default class Login extends Component<{}> {
static navigationOptions = { header: null };
}
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
You can't checkout a single directory of a repository because the entire repository is handled by the single .git folder in the root of the project instead of subversion's myriad of .svn directories.
The problem with working on plugins in a single repository is that making a commit to, e.g., mytheme will increment the revision number for myplugin, so even in subversion it is better to use separate repositories.
The subversion paradigm for sub-projects is svn:externals which translates somewhat to submodules in git (but not exactly in case you've used svn:externals before.)
The simple way to do that is to use git format-patch.
Assume we have 2 git repositories foo and bar.
foo contains:
bar contains:
and we want to end-up with foo containing the bar history and these files:
So to do that:
1. create a temporary directory eg PATH_YOU_WANT/patch-bar
2. go in bar directory
3. git format-patch --root HEAD --no-stat -o PATH_YOU_WANT/patch-bar --src-prefix=a/foobar/ --dst-prefix=b/foobar/
4. go in foo directory
5. git am PATH_YOU_WANT/patch-bar/*
And if we want to rewrite all message commits from bar we can do, eg on Linux:
git filter-branch --msg-filter 'sed "1s/^/\[bar\] /"' COMMIT_SHA1_OF_THE_PARENT_OF_THE_FIRST_BAR_COMMIT..HEAD
This will add "[bar] " at the beginning of each commit message.
I can tell you for Windows.
Install Java Extension Pack and Code Runner Extension from VS Code Extensions.
Edit your java home location in VS Code settings, "java.home
": "C:\\Program Files\\Java\\jdk-9.0.4"
.
Check if javac is recognized in VS Code internal terminal. If this check fails, try opening VS Code as administrator.
Create a simple Java program in Main.java file as:
public class Main {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
Note: Do not add package in your main class.
Right click anywhere on the java file and select run code.
Check the output in the console.
Done, hope this helps.
You can use the command split for this task. For example this command entered into the command prompt
split YourLogFile.txt -b 500m
creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.
Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.
(tested on Windows 7 64 bit)
File size by MySQL type:
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
<form id="uploadForm" class="disp-inline" role="form" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
</form>
<button onclick="checkSize();"></button>
<script>
function checkSize(){
var size = $('#uploadForm')["0"].firstChild.files["0"].size;
console.log(size);
}
</script>
I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything.
NOTES:
var size = $('#uploadForm')["0"]["0"].files["0"].size;
This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). The second ["0"] is now firstChild.
Or with a list comprehension:
>>> base = r"c:\User\xtofl"
>>> binfiles = [ os.path.join(base,f)
for base, _, files in os.walk(root)
for f in files if f.endswith(".jpg") ]
The below regex would match white spaces but not of a new line character.
(?:(?!\n)\s)
If you want to add carriage return also then add \r
with the |
operator inside the negative lookahead.
(?:(?![\n\r])\s)
Add +
after the non-capturing group to match one or more white spaces.
(?:(?![\n\r])\s)+
I don't know why you people failed to mention the POSIX character class [[:blank:]]
which matches any horizontal whitespaces (spaces and tabs). This POSIX chracter class would work on BRE(Basic REgular Expressions), ERE(Extended Regular Expression), PCRE(Perl Compatible Regular Expression).
I think that Object = Instance. Reference is a "link" to an Object.
Car c = new Car();
variable c stores a reference to an object of type Car.
The same problem takes me here. After all, I found that link, it's good for me.
CHECK THE STATUS OF PLUGGABLE DATABASE.
SQL> STARTUP; ORACLE instance started.
Total System Global Area 788529152 bytes Fixed Size 2929352 bytes Variable Size 541068600 bytes Database Buffers 239075328 bytes Redo Buffers 5455872 bytes Database mounted. Database opened. SQL> select name,open_mode from v$pdbs;
NAME OPEN_MODE ------------------------------ ---------- PDB$SEED MOUNTED PDBORCL MOUNTED PDBORCL2 MOUNTED PDBORCL1
MOUNTEDWE NEED TO START PDB$SEED PLUGGABLE DATABASE in UPGRADE STATE FOR THAT
SQL> SHUTDOWN IMMEDIATE;
Database closed. Database dismounted. ORACLE instance shut down.
SQL> STARTUP UPGRADE;
ORACLE instance started.
Total System Global Area 788529152 bytes Fixed Size 2929352 bytes Variable Size 541068600 bytes Database Buffers 239075328 bytes Redo Buffers 5455872 bytes Database mounted. Database opened.
SQL> ALTER PLUGGABLE DATABASE ALL OPEN UPGRADE; Pluggable database altered.
SQL> select name,open_mode from v$pdbs;
NAME OPEN_MODE ------------------------------ ---------- PDB$SEED MIGRATE PDBORCL MIGRATE PDBORCL2 MIGRATE PDBORCL1
MIGRATE
You can use:
(instancetype)init {
return [[YourSubclassOfTableView alloc] initWithStyle:UITableViewStyleGrouped];
}
Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.
The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.
As a bonus, text is responsively centered in the quarters.
HTML:
<head>
<meta charset="utf-8">
<title>Box model</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="title">Title Bar</h1>
<div id="dividedbox">
<div class="quarter" id="NW">
<p>NW</p>
</div>
<div class="quarter" id="NE">
<p>NE</p>
</div>
<div class="quarter" id="SE">
<p>SE</p>
</div>?
<div class="quarter" id="SW">
<p>SW</p>
</div>
</div>
</body>
</html>
CSS:
html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%} /* for div growth */
.quarter {position: absolute; width:50%; height:50%; /* gives quarters their size */
display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0; left:0; background:orange; }
#NE { top:0; left:50%; background:lightblue; }
#SW { top:50%; left:0; background:green; }
#SE { top:50%; left:50%; background:red; }
I had to use Debug.print
instead of Print
, which works in the Immediate window.
Sub SendEmail()
'Dim objHTTP As New MSXML2.XMLHTTP
'Set objHTTP = New MSXML2.XMLHTTP60
'Dim objHTTP As New MSXML2.XMLHTTP60
Dim objHTTP As New WinHttp.WinHttpRequest
'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost:8888/rest/mail/send"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
Debug.Print objHTTP.Status
Debug.Print objHTTP.ResponseText
End Sub
I think X-Istence is on the right track, but there are a few more improvements you can make to this strategy. First, use:
$pg_dump --schema ...
to dump the tables, sequences, etc and place this file under version control. You'll use this to separate the compatibility changes between your branches.
Next, perform a data dump for the set of tables that contain configuration required for your application to operate (should probably skip user data, etc), like form defaults and other data non-user modifiable data. You can do this selectively by using:
$pg_dump --table=.. <or> --exclude-table=..
This is a good idea because the repo can get really clunky when your database gets to 100Mb+ when doing a full data dump. A better idea is to back up a more minimal set of data that you require to test your app. If your default data is very large though, this may still cause problems though.
If you absolutely need to place full backups in the repo, consider doing it in a branch outside of your source tree. An external backup system with some reference to the matching svn rev is likely best for this though.
Also, I suggest using text format dumps over binary for revision purposes (for the schema at least) since these are easier to diff. You can always compress these to save space prior to checking in.
Finally, have a look at the postgres backup documentation if you haven't already. The way you're commenting on backing up 'the database' rather than a dump makes me wonder if you're thinking of file system based backups (see section 23.2 for caveats).
In addition to the answers above, here is a benchmark comparing different ways to add rows of data to an already existing dataframe. It shows that using at or set-value is the most efficient way for large dataframes (at least for these test conditions).
For the test, an existing dataframe comprising 100,000 rows and 1,000 columns and random numpy values was used. To this dataframe, 100 new rows were added.
Code see below:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 21 16:38:46 2018
@author: gebbissimo
"""
import pandas as pd
import numpy as np
import time
NUM_ROWS = 100000
NUM_COLS = 1000
data = np.random.rand(NUM_ROWS,NUM_COLS)
df = pd.DataFrame(data)
NUM_ROWS_NEW = 100
data_tot = np.random.rand(NUM_ROWS + NUM_ROWS_NEW,NUM_COLS)
df_tot = pd.DataFrame(data_tot)
DATA_NEW = np.random.rand(1,NUM_COLS)
#%% FUNCTIONS
# create and append
def create_and_append(df):
for i in range(NUM_ROWS_NEW):
df_new = pd.DataFrame(DATA_NEW)
df = df.append(df_new)
return df
# create and concatenate
def create_and_concat(df):
for i in range(NUM_ROWS_NEW):
df_new = pd.DataFrame(DATA_NEW)
df = pd.concat((df, df_new))
return df
# store as dict and
def store_as_list(df):
lst = [[] for i in range(NUM_ROWS_NEW)]
for i in range(NUM_ROWS_NEW):
for j in range(NUM_COLS):
lst[i].append(DATA_NEW[0,j])
df_new = pd.DataFrame(lst)
df_tot = df.append(df_new)
return df_tot
# store as dict and
def store_as_dict(df):
dct = {}
for j in range(NUM_COLS):
dct[j] = []
for i in range(NUM_ROWS_NEW):
dct[j].append(DATA_NEW[0,j])
df_new = pd.DataFrame(dct)
df_tot = df.append(df_new)
return df_tot
# preallocate and fill using .at
def fill_using_at(df):
for i in range(NUM_ROWS_NEW):
for j in range(NUM_COLS):
#print("i,j={},{}".format(i,j))
df.at[NUM_ROWS+i,j] = DATA_NEW[0,j]
return df
# preallocate and fill using .at
def fill_using_set(df):
for i in range(NUM_ROWS_NEW):
for j in range(NUM_COLS):
#print("i,j={},{}".format(i,j))
df.set_value(NUM_ROWS+i,j,DATA_NEW[0,j])
return df
#%% TESTS
t0 = time.time()
create_and_append(df)
t1 = time.time()
print('Needed {} seconds'.format(t1-t0))
t0 = time.time()
create_and_concat(df)
t1 = time.time()
print('Needed {} seconds'.format(t1-t0))
t0 = time.time()
store_as_list(df)
t1 = time.time()
print('Needed {} seconds'.format(t1-t0))
t0 = time.time()
store_as_dict(df)
t1 = time.time()
print('Needed {} seconds'.format(t1-t0))
t0 = time.time()
fill_using_at(df_tot)
t1 = time.time()
print('Needed {} seconds'.format(t1-t0))
t0 = time.time()
fill_using_set(df_tot)
t1 = time.time()
print('Needed {} seconds'.format(t1-t0))
This is the example code taken from the PHP documentation here: https://www.php.net/manual/en/function.filemtime.php
// outputs e.g. somefile.txt was last changed: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
The code specifies the filename, then checks if it exists and then displays the modification time using filemtime()
.
filemtime()
takes 1 parameter which is the path to the file, this can be relative or absolute.
For completeness: with dplyr v0.2 ddply
with colwise
will also do this:
> ddply(df, .(grp), colwise(mean))
grp a b c d
1 1 4.333333 4.00 1.000000 2.000000
2 2 2.000000 2.75 2.750000 2.750000
3 3 3.000000 4.00 4.333333 3.666667
but it is slower, at least in this case:
> microbenchmark(ddply(df, .(grp), colwise(mean)),
df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
expr min lq mean
ddply(df, .(grp), colwise(mean)) 3.278002 3.331744 3.533835
df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337
median uq max neval
3.353633 3.378089 7.592209 100
1.121954 1.133428 2.292216 100
You should not replace the text entirely. Add the text after the "# END WordPress".
Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way. You might want to consider:
Set<String> dayNames = Calendar.getInstance()
.getDisplayNames(Calendar.DAY_OF_WEEK,
Calendar.SHORT,
Locale.getDefault())
.keySet();
From there you can use .startsWith or .matches or whatever other method that others have mentioned above. This way you get the default locale for the jvm. You could always pass in the locale (and maybe default it to the system locale if it's null) as well to be more robust.
In Notepad++ v. 6.4.1 is this possibility in:Settings->Preferences->Auto-Completion and there check Enable auto-completion on each input.
For auto-complete in code press Ctrl + Enter
.
Use ld.charAt(0)
. It will return the first char
of the String
.
With ld.substring(0, 1)
, you can get the first character as String
.
If you want to just shift everything down you can use:
Rows(1).Insert shift:=xlShiftDown
Similarly to shift everything over:
Columns(1).Insert shift:=xlShiftRight
If you're using Radiant CMS, simply add
require 'thread'
to the top of config/boot.rb
.
(Kudos to Aaron's and nathanvda's responses.)
This code is also work cause The Object.create() method creates a new object with the specified prototype object and properties.
var obj1 = {x:5, y:5};
var obj2 = Object.create(obj1);
obj2.x; //5
obj2.x = 6;
obj2.x; //6
obj1.x; //5
Short answer is you can't as above posts point out. But for my case, I simply didn't want to clutter the namespace but still have implicit conversions, so I just did:
#include <iostream>
using namespace std;
namespace Foo {
enum Foo { bar, baz };
}
int main() {
cout << Foo::bar << endl; // 0
cout << Foo::baz << endl; // 1
return 0;
}
The namespacing sort of adds a layer of type-safety while I don't have to static cast any enum values to the underlying type.
This makes up the fields
$("#form_questionario").validate({
debug: false,
errorElement: "span",
errorClass: "help-block",
highlight: function (element, errorClass, validClass) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).closest('.form-group').removeClass('has-error');
},
errorPlacement: function (error, element) {
if (element.parent('.input-group').length || element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
error.insertBefore(element.parent());
} else {
error.insertAfter(element);
}
},
// Specify the validation rules
rules: {
'campo1[]': 'required',
'campo2[]': 'required',
'campo3[]': 'required',
'campo4[]': 'required',
'campo5[]': 'required'
},
submitHandler: function (form) {
form.submit();
}
});
You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:
import random
def generate_random_number(length):
return int(''.join([str(random.randint(0,10)) for _ in range(length)]))
Unless the writer of the executable has specifically provided a way for you to display a list of all the command line switches that it offers, then there is no way of doing this.
As Marcin suggests, the typical switches for displaying all of the options are either /?
or /help
(some applications might prefer the Unix-style syntax, -?
and -help
, respectively). But those are just a common convention.
If those don't work, you're out of luck. You'll need to check the documentation for the application, or perhaps try decompiling the executable (if you know what you're looking for).
$.each($("#MySelect option"), function(){
alert($(this).text() + " - " + $(this).val());
});
error in the very first line public class StaticDemo {
Any Class A
which has access modifier as public
must have a separate source file as A.java
or A.jav
. This is specified in JLS 7.6 section:
If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
The type is referred to by code in other compilation units of the package in which the type is declared.
The type is declared public (and therefore is potentially accessible from code in other packages).
However, you may have to remove public
access modifier from the Class declaration StaticDemo
. Then as StaticDemo
class will have no modifier it will become package-private, That is, it will be visible only within its own package.
Check out Controlling Access to Members of a Class
If you want to save the ASCII value of the character: (I did this in BASH and it worked)
{
char="A"
testing=$( printf "%d" "'${char}" )
echo $testing}
output: 65
Just create a new branch:
git checkout -b newBranch
And if you do git status
you'll see that the state of the code hasn't changed and you can commit it to the new branch.
unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))
Use the DateTime.SpecifyKind
static method.
Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.
Example:
DateTime dateTime = DateTime.Now;
DateTime other = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
Console.WriteLine(dateTime + " " + dateTime.Kind); // 6/1/2011 4:14:54 PM Local
Console.WriteLine(other + " " + other.Kind); // 6/1/2011 4:14:54 PM Utc
This functions works for me in CKEditor version 4.4.5, it does not have any memory leaks
function CKEditor_Render(CkEditor_id) {
var instance = CKEDITOR.instances[CkEditor_id];
if (CKEDITOR.instances.instance) {
CKEDITOR.instances.instance.destroy();
}
CKEDITOR.replace(CkEditor_id);
}
// call this function as below
var id = 'ckeditor'; // Id of your textarea
CKEditor_Render(id);
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
For more info, see Base64.
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
For direct byte arrays:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils
class more ergonomic:
For direct byte arrays:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded)) // Outputs "Hello"
If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64
.
For direct byte arrays:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
This is not ideal as it removes all, but might work for your needs:
z = document.querySelector('video');
z.parentNode.replaceChild(z.cloneNode(1), z);
Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener()
You can easily import your model and run this:
from models import User
# User is the name of table that has a column name
users = User.query.all()
for user in users:
print user.name
Looks like you are doing a Python implementation of the Coursera Machine Learning Neural Network exercise. Here's what I did for randInitializeWeights(L_in, L_out)
#get a random array of floats between 0 and 1 as Pavel mentioned
W = numpy.random.random((L_out, L_in +1))
#normalize so that it spans a range of twice epsilon
W = W * 2 * epsilon
#shift so that mean is at zero
W = W - epsilon
You can try this new library. JellyGif respects Gif frame duration while being highly CPU & Memory performant. It works great with UITableViewCell & UICollectionViewCell too. To get started you just need to
import JellyGif
let imageView = JellyGifImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
//Animates Gif from the main bundle
imageView.startGif(with: .name("Gif name"))
//Animates Gif with a local path
let url = URL(string: "Gif path")!
imageView.startGif(with: .localPath(url))
//Animates Gif with data
imageView.startGif(with: .data(Data))
For more information you can look at its README
(http|https)?:\/\/(\S+)
This works for me
Not a regex specialist, but i will try to explain the awnser.
(http|https) : Parenthesis indicates a capture group, "I" a OR statement.
\/\/ : "\" allows special characters, such as "/"
(\S+) : Anything that is not whitespace until the next whitespace
I think this is a great tutorial on writing a simple jquery popup. Plus it looks very beautiful
awk '{print substr($0,6)}' file
set its position:fixed and bottom:0 so that it will always reside at bottom of your browser windows
$db->getProfiler()->setEnabled(true);
// your code
$this->update('table', $data, $where);
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQuery());
Zend_Debug::dump($db->getProfiler()->getLastQueryProfile()->getQueryParams());
$db->getProfiler()->setEnabled(false);
If you don't need to support IE7, the following is a great, concise hack:
JSON.parse(JSON.stringify(new Date()))
You can use the bootstrap grid system. as Yoann said
<div class="container">
<div class="row">
<form role="form">
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
</div>
<div class="clearfix"></div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Confirm Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
</div>
</form>
<div class="clearfix">
</div>
</div>
</div>
just use javascript:---- exemplale
javascript:var JFL_81371678974472 = new JotformFeedback({ formId: '81371678974472', base: 'https://form.jotform.me/', windowTitle: 'Photobook Series', background: '#e44c2a', fontColor: '#FFFFFF', type: 'false', height: 700, width: 500, openOnLoad: true })
Hi try this it will create directory + file inside it
File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
mediaDir.mkdir();
}
File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();
System.out.println("Your file has been written");
Simply create a property in your view model of type MvcHtmlString. You won't need to Html.Raw it then either.
I Faced the same issue. For me it was just to unckeck the option :
Tablix Properties=> Page Break Option => Keep together on one page if possible
Of SSRS Report. It was trying to put all records on the same page instead of creating many pages.
Yet another solution.
Add ErrorControllers or static page to with 404 error information.
Modify your web.config (in case of controller).
<system.web>
<customErrors mode="On" >
<error statusCode="404" redirect="~/Errors/Error404" />
</customErrors>
</system.web>
Or in case of static page
<system.web>
<customErrors mode="On" >
<error statusCode="404" redirect="~/Static404.html" />
</customErrors>
</system.web>
This will handle both missed routes and missed actions.
if you have the property "MyProperty" on your data-class, then you bind the IsChecked like this.... (the converter is optional, but sometimes you need that)
<Window.Resources>
<local:MyBoolConverter x:Key="MyBoolConverterKey"/>
</Window.Resources>
<checkbox IsChecked="{Binding Path=MyProperty, Converter={StaticResource MyBoolConverterKey}}"/>
I have updated accepted answer and removed unnecessary things.
I have created XML for following image.
Your XML code for RadioButton
will be:
<RadioGroup
android:id="@+id/daily_weekly_button_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="@+id/radio0"
android:layout_width="@dimen/_80sdp"
android:gravity="center"
android:layout_height="wrap_content"
android:background="@drawable/radio_flat_selector"
android:button="@android:color/transparent"
android:checked="true"
android:paddingLeft="@dimen/_16sdp"
android:paddingTop="@dimen/_3sdp"
android:paddingRight="@dimen/_16sdp"
android:paddingBottom="@dimen/_3sdp"
android:text="Daily"
android:textColor="@color/radio_flat_text_selector" />
<RadioButton
android:id="@+id/radio1"
android:gravity="center"
android:layout_width="@dimen/_80sdp"
android:layout_height="wrap_content"
android:background="@drawable/radio_flat_selector"
android:button="@android:color/transparent"
android:paddingLeft="@dimen/_16sdp"
android:paddingTop="@dimen/_3sdp"
android:paddingRight="@dimen/_16sdp"
android:paddingBottom="@dimen/_3sdp"
android:text="Weekly"
android:textColor="@color/radio_flat_text_selector" />
</RadioGroup>
radio_flat_selector.xml
for background selector:<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/radio_flat_selected" android:state_checked="true" />
<item android:drawable="@drawable/radio_flat_regular" />
</selector>
radio_flat_selected.xml
for selected button:<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="1dp"
/>
<solid android:color="@color/colorAccent" />
<stroke
android:width="1dp"
android:color="@color/colorAccent" />
</shape>
radio_flat_regular.xml
for regular selector:<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1dp" />
<solid android:color="#fff" />
<stroke
android:width="1dp"
android:color="@color/colorAccent" />
</shape>
All the above 3 file code will be in drawable/
folder.
Now we also need Text
Color Selector to change color of text accordingly.
radio_flat_text_selector.xml
for text color selector(Use color/
folder for this file.)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/colorAccent" android:state_checked="false" />
<item android:color="@color/colorWhite" android:state_checked="true" />
</selector>
Note: I refereed many answers for this type of solution but didn't found good solution so I make it.
Hope it will be helpful to you.
Thanks.
I had a such problem too because i was using IMG tag and UL tag.
Try to apply the 'corners' plugin to elements such as $('#mydiv').corner()
, $('#myspan').corner()
, $('#myp').corner()
but NOT for $('#img').corner()
!
This rule is related with adding child DIVs into specified element for emulation round-corner effect. As we know IMG element couldn't have any child elements.
I've solved this by wrapping a needed element within the div and changing IMG to DIV with background: CSS property.
Good luck!
You can use laravel MessageBag to add our own messages to existing messages.
To use MessageBag you need to use:
use Illuminate\Support\MessageBag;
In the controller:
MessageBag $message_bag
$message_bag->add('message', trans('auth.confirmation-success'));
return redirect('login')->withSuccess($message_bag);
Hope it will help some one.
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
Try this
var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
type: 'POST',
url: '/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
You need to use the FormData API and set the jQuery.ajax
's processData
and contentType
to false
.
Using Angular Cli
npm install jquery --save
In angular.json under scripts array
"scripts": [ "node_modules/jquery/dist/jquery.min.js" ] // copy relative path of node_modules>jquery>dist>jquery.min.js to avoid path error
Now to use jQuery, all you have to do is to import it as follows in whatever component you want to use jQuery.
For example importing and using jQuery in root component
import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery'; // I faced issue in using jquery's popover
Or
declare var $: any; // declaring jquery in this way solved the problem
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
}
jQueryExampleModal() { // to show a modal with dummyId
$('#dummyId').modal('show');
}
You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.
commands.h
#ifndef COMMANDS_H_
#define COMMANDS_H_
void f123();
#endif
commands.c
#include "commands.h"
void f123()
{
/* code */
}
A simple 4on4 pasting function that works-
def paste(background,foreground,pos=(0,0)):
#get position and crop pasting area if needed
x = pos[0]
y = pos[1]
bgWidth = background.shape[0]
bgHeight = background.shape[1]
frWidth = foreground.shape[0]
frHeight = foreground.shape[1]
width = bgWidth-x
height = bgHeight-y
if frWidth<width:
width = frWidth
if frHeight<height:
height = frHeight
# normalize alpha channels from 0-255 to 0-1
alpha_background = background[x:x+width,y:y+height,3] / 255.0
alpha_foreground = foreground[:width,:height,3] / 255.0
# set adjusted colors
for color in range(0, 3):
fr = alpha_foreground * foreground[:width,:height,color]
bg = alpha_background * background[x:x+width,y:y+height,color] * (1 - alpha_foreground)
background[x:x+width,y:y+height,color] = fr+bg
# set adjusted alpha and denormalize back to 0-255
background[x:x+width,y:y+height,3] = (1 - (1 - alpha_foreground) * (1 - alpha_background)) * 255
return background
Open report in Report designer
Go to View menu -> Report data
Here's the final solution for the case in update section (with the help of Google Collections):
Collections2.transform (fooCollection, new Function<Foo, Bar>() {
public Bar apply (Foo foo) {
return new Bar (foo);
}
}).toArray (new Bar[fooCollection.size()]);
But, the key approach here was mentioned in the doublep's answer (I forgot for toArray
method).
case when first_condition
then first_condition_result_true
else
case when second_condition
then second_condition_result_true
else
second_condition_result_false
end
end
end as qty
Try this
import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time
OUTPUT :
0:00:05
This simple way worked fine for me:
<ul style="margin-top:-30px;">
Function is not a property/method from range.
If you want to sum values then use the following:
Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))
EDIT:
if you want the formula then use as follows:
Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"
'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).
In case you are allways going to use the same range address then you can use as Rory sugested:
Range("A1").Formula ="=Sum(A2:B3)"
Redis and MongoDB are both non-relational databases but they're of different categories.
Redis is a Key/Value database, and it's using In-memory storage which makes it super fast. It's a good candidate for caching stuff and temporary data storage(in memory) and as the most of cloud platforms (such as Azure,AWS) support it, it's memory usage is scalable.But if you're gonna use it on your machines with limited resources, consider it's memory usage.
MongoDB on the other hand, is a document database. It's a good option for keeping large texts, images, videos, etc and almost anything you do with databases except transactions.For example if you wanna develop a blog or social network, MongoDB is a proper choice. It's scalable with scale-out strategy. It uses disk as storage media, so data would be persisted.
Please try this:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
use array.splice
/*array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index) // SpiderMonkey/Firefox extension*/
array.splice(1,1)
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Beautiful Soup 4 allows you to set a formatter to your output
If you pass in
formatter=None
, Beautiful Soup will not modify strings at all on output. This is the fastest option, but it may lead to Beautiful Soup generating invalid HTML/XML, as in these examples:
print(soup.prettify(formatter=None))
# <html>
# <body>
# <p>
# Il a dit <<Sacré bleu!>>
# </p>
# </body>
# </html>
link_soup = BeautifulSoup('<a href="http://example.com/?foo=val1&bar=val2">A link</a>')
print(link_soup.a.encode(formatter=None))
# <a href="http://example.com/?foo=val1&bar=val2">A link</a>
I suggest using pip in place of easy_install. With pip, you can list all installed packages and their versions with
pip freeze
In most linux systems, you can pipe this to grep
(or findstr
on Windows) to find the row for the particular package you're interested in:
Linux:
$ pip freeze | grep lxml
lxml==2.3
Windows:
c:\> pip freeze | findstr lxml
lxml==2.3
For an individual module, you can try the __version__
attribute, however there are modules without it:
$ python -c "import requests; print(requests.__version__)"
2.14.2
$ python -c "import lxml; print(lxml.__version__)"
Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute '__version__'
Lastly, as the commands in your question are prefixed with sudo
, it appears you're installing to the global python environment. Strongly advise to take look into python virtual environment managers, for example virtualenvwrapper
Hope it helps:
DELETE FROM tablename
WHERE tablename.id = ANY (SELECT id FROM tablename WHERE id = id);
When I saw this today, a developer had moved part of the tree into a new sub-directory and it looks as though his git client did not record the updated Subproject rules in the tree, instead they were just nuked, leaving .gitmodules
referring both to stale locations and to subprojects which no longer existed in the current tree.
Adding the submodules back in, and comparing the commit shas of the submodule to those found in git show $breaking_commit_sha
(search for lines matching regexp ^-Subproject
) to adjust as needed fixed things.
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
In case, your data is in the following structure, you get string as an index
items = {
am:"Amharic",
ar:"Arabic",
az:"Azerbaijani",
ba:"Bashkir",
be:"Belarusian"
}
In this case, you can use extra variable to get the index in number:
<ul>
<li v-for="(item, key, index) in items">
{{ item }} - {{ key }} - {{ index }}
</li>
</ul>
I tried t.boolean :active, :default => 1 in migration file for creating entire table. After ran that migration when i checked in db it made as null. Even though i told default as "1". After that slightly i changed migration file like this then it worked for me for setting default value on create table migration file.
t.boolean :active, :null => false,:default =>1. Worked for me.
My Rails framework version is 4.0.0
This is a simple program to capture an image from using a default camera. Also, It can Detect a human face.
import cv2
import sys
import logging as log
import datetime as dt
from time import sleep
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('s'):
check, frame = video_capture.read()
cv2.imshow("Capturing", frame)
cv2.imwrite(filename='saved_img.jpg', img=frame)
video_capture.release()
img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
img_new = cv2.imshow("Captured Image", img_new)
cv2.waitKey(1650)
print("Image Saved")
print("Program End")
cv2.destroyAllWindows()
break
elif cv2.waitKey(1) & 0xFF == ord('q'):
print("Turning off camera.")
video_capture.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
# Display the resulting frame
cv2.imshow('Video', frame)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
output
Also, You can check out my GitHub code
Try using these theme: Theme.AppCompat.Light.NoActionBar
Mi Style XML file looks like these and works just fine:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
As the React Native Documentation says, all your images sources needs to be loaded before compiling your bundle
So another way you can use dynamic images it's using a switch statement. Let's say you want to display a different avatar for a different character, you can do something like this:
class App extends Component {
state = { avatar: "" }
get avatarImage() {
switch (this.state.avatar) {
case "spiderman":
return require('./spiderman.png');
case "batman":
return require('./batman.png');
case "hulk":
return require('./hulk.png');
default:
return require('./no-image.png');
}
}
render() {
return <Image source={this.avatarImage} />
}
}
Check the snack: https://snack.expo.io/@abranhe/dynamic-images
Also, remember if your image it's online you don't have any problems, you can do:
let superhero = "spiderman";
<Image source={{ uri: `https://some-website.online/${superhero}.png` }} />
I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:
FOR /F "tokens=*" %G IN ('dir /b') DO robocopy "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0
As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.
It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.
For me nothing from above worked. So I solved my problem with this workaround. Just check that you have added SYSTEM in directory folder. I hope it will help somoene.
import os
# create file
@staticmethod
def create_file(path):
if not os.path.exists(path):
os.system('echo # > {}'.format(path))
# append lines to the file
split_text = text_file.split('\n')
for st in split_text:
os.system('echo {} >> {}'.format(st,path))
public static bool MoveFile(string CurrentFilePath, string NewFilePath)
{
try
{
using (var f = new File(CurrentFilePath))
using (var i = new FileInputStream(f))
using (var o = new FileOutputStream(NewFilePath))
{
i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);
f.Delete();
}
return true;
}
catch { return false; }
}
public static bool CopyFile(string CurrentFilePath, string NewFilePath)
{
try
{
using (var i = new FileInputStream(CurrentFilePath))
using (var o = new FileOutputStream(NewFilePath))
i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);
return true;
}
catch { return false; }
}
public static bool DeleteFile(string FilePath)
{
try
{
using (var file = new File(FilePath))
file.Delete();
return true;
}
catch { return false; }
}
As dfsq said i just had to use removeClass("hide")
instead of toggle()
If you are using RichTextBox control. You can simply define the ToolTip object and show the tool-tip as the text is selected by moving the mouse inside the RichTextBox control.
ToolTip m_ttInput = new ToolTip(); // define as member variable
private void rtbInput_SelectionChanged(object sender, EventArgs e)
{
if (rtbInput.SelectedText.Length > 0)
{
m_ttInput.Show(rtbInput.SelectedText.Length.ToString(), rtbInput, 1000);
}
}
public static int countWords(String input) {
int wordCount = 0;
boolean isBlankSet = false;
input = input.trim();
for (int j = 0; j < input.length(); j++) {
if (input.charAt(j) == ' ')
isBlankSet = true;
else {
if (isBlankSet) {
wordCount++;
isBlankSet = false;
}
}
}
return wordCount + 1;
}
While several answers are similar, I still had an issue - the user would click the button several times, playing the audio over itself (either it was clicked by accident or they were just 'playing'....)
An easy fix:
var music = new Audio();
function playMusic(file) {
music.pause();
music = new Audio(file);
music.play();
}
Setting up the audio on load allowed 'music' to be paused every time the function is called - effectively stopping the 'noise' even if they user clicks the button several times (and there is also no need to turn off the button, though for user experience it may be something you want to do).
Try this:
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public' AND table_type='BASE TABLE'
this one works!
As for me, I removed the provided
scope in tomcat dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope> // remove this scope
</dependency>
change your ssh url by an http url for your remote 'origin', use:
> git remote set-url origin https://github.com/<user_name>/<repo_name>.git
It will ask for your GitHub password on the git push.
The following approach is similar to a2800276's, but with some C99 macro magic added:
// we need `size_t`
#include <stddef.h>
// argument types to accept
enum sum_arg_types { SUM_LONG, SUM_ULONG, SUM_DOUBLE };
// a structure to hold an argument
struct sum_arg
{
enum sum_arg_types type;
union
{
long as_long;
unsigned long as_ulong;
double as_double;
} value;
};
// determine an array's size
#define count(ARRAY) ((sizeof (ARRAY))/(sizeof *(ARRAY)))
// this is how our function will be called
#define sum(...) _sum(count(sum_args(__VA_ARGS__)), sum_args(__VA_ARGS__))
// create an array of `struct sum_arg`
#define sum_args(...) ((struct sum_arg []){ __VA_ARGS__ })
// create initializers for the arguments
#define sum_long(VALUE) { SUM_LONG, { .as_long = (VALUE) } }
#define sum_ulong(VALUE) { SUM_ULONG, { .as_ulong = (VALUE) } }
#define sum_double(VALUE) { SUM_DOUBLE, { .as_double = (VALUE) } }
// our polymorphic function
long double _sum(size_t count, struct sum_arg * args)
{
long double value = 0;
for(size_t i = 0; i < count; ++i)
{
switch(args[i].type)
{
case SUM_LONG:
value += args[i].value.as_long;
break;
case SUM_ULONG:
value += args[i].value.as_ulong;
break;
case SUM_DOUBLE:
value += args[i].value.as_double;
break;
}
}
return value;
}
// let's see if it works
#include <stdio.h>
int main()
{
unsigned long foo = -1;
long double value = sum(sum_long(42), sum_ulong(foo), sum_double(1e10));
printf("%Le\n", value);
return 0;
}
string founded = FindStringTakeX("UID: 994zxfa6q", "UID:", 9);
string FindStringTakeX(string strValue,string findKey,int take,bool ignoreWhiteSpace = true)
{
int index = strValue.IndexOf(findKey) + findKey.Length;
if (index >= 0)
{
if (ignoreWhiteSpace)
{
while (strValue[index].ToString() == " ")
{
index++;
}
}
if(strValue.Length >= index + take)
{
string result = strValue.Substring(index, take);
return result;
}
}
return string.Empty;
}
You can do this:
If your tomcat installation is default and you have not done any changes, then the default war will be ROOT.war
. Thus whenever you will call http://yourserver.example.com/
, it will call the index.html
or index.jsp
of your default WAR file. Make the following changes in your webapp/ROOT
folder for redirecting requests to http://yourserver.example.com/somewhere/else
:
Open webapp/ROOT/WEB-INF/web.xml
,
remove any servlet mapping with path /index.html
or /index.jsp
,
and save.
Remove webapp/ROOT/index.html
, if it exists.
Create the file webapp/ROOT/index.jsp
with this line of content:
<% response.sendRedirect("/some/where"); %>
or if you want to direct to a different server,
<% response.sendRedirect("http://otherserver.example.com/some/where"); %>
That's it.
I think this behavior can be turned off, but Window's online help wasn't extremely clear:
If you disable NetBIOS over TCP/IP, you cannot use broadcast-based NetBIOS name resolution to resolve computer names to IP addresses for computers on the same network segment. If your computers are on the same network segment, and NetBIOS over TCP/IP is disabled, you must install a DNS server and either have the computers register with DNS (or manually configure DNS records) or configure entries in the local Hosts file for each computer.
In Windows XP, there is a checkbox:
Advanced TCP/IP Settings
[ ] Enable LMHOSTS lookup
There is also a book that covers this at length, "Networking Personal Computers with TCP/IP: Building TCP/IP Networks (old O'Reilly book)". Unfortunately, I cannot look it up because I disposed of my copy a while ago.
If you are using a rooted phone then try this application WiFi ADB.
Probably this is the most simplest way to debug on wifi.
I am using this application from many days and it works flawlessly.
Thanks I have added below snippet in POM.xml file and Mp problem resolved and create fat jar file that include all dependent jars.
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
Follow the next steps:
I would like to point out that none of the T-SQL on this page will work precisely because none of them join to the syssessions table to get only the current session and therefore could include false positives.
See this for reference: What does it mean to have jobs with a null stop date?
You can also validate this by analyzing the sp_help_jobactivity procedure in msdb.
I realize that this is an old message on SO, but I found this message only partially helpful because of the problem.
SELECT
job.name,
job.job_id,
job.originating_server,
activity.run_requested_date,
DATEDIFF( SECOND, activity.run_requested_date, GETDATE() ) as Elapsed
FROM
msdb.dbo.sysjobs_view job
JOIN
msdb.dbo.sysjobactivity activity
ON
job.job_id = activity.job_id
JOIN
msdb.dbo.syssessions sess
ON
sess.session_id = activity.session_id
JOIN
(
SELECT
MAX( agent_start_date ) AS max_agent_start_date
FROM
msdb.dbo.syssessions
) sess_max
ON
sess.agent_start_date = sess_max.max_agent_start_date
WHERE
run_requested_date IS NOT NULL AND stop_execution_date IS NULL
Use the link http://ip-api.com/json. This will provide all the information as JSON. From this JSON content you can get the country easily. This site works using your current IP address. It automatically detects the IP address and sendback details.
This is what I got:
{
"as": "AS55410 C48 Okhla Industrial Estate, New Delhi-110020",
"city": "Kochi",
"country": "India",
"countryCode": "IN",
"isp": "Vodafone India",
"lat": 9.9667,
"lon": 76.2333,
"org": "Vodafone India",
"query": "123.63.81.162",
"region": "KL",
"regionName": "Kerala",
"status": "success",
"timezone": "Asia/Kolkata",
"zip": ""
}
N.B. - As this is a third-party API, do not use it as the primary solution. And also I am not sure whether it's free or not.
print("{latitude} {longitude}".format(**geopoint))
hai the most easiest way is this:
add this code to mainactivity.java
public void start(View view) {
stop.setBackgroundResource(R.color.red);
start.setBackgroundResource(R.color.yellow);
}
public void stop(View view) {
stop.setBackgroundResource(R.color.yellow);
start.setBackgroundResource(R.color.red);
}
and then in your activity main
<button android:id="@+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="start" android:text="Click">
</button><button android:id="@+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="stop" android:text="Click">
or follow along this tutorial
Also found google collections reverse method.
I guess the answer you need is referenced here Python sets are not json serializable
Not all datatypes can be json serialized . I guess pickle module will serve your purpose.
Click event Bubbles, now what is meant by bubbling, a good point to starts is here.
you can use event.stopPropagation()
, if you don't want that event should propagate further.
Also a good link to refer on MDN
I'm using JSON5, and it's works pretty well.
The good part is it contains no eval
and no new Function
, very safe to use.
If you wrote this "getElementByClassName" then you will encounter with this error "document.getElementByClass is not a function" so to overcome that error just write "getElementsByClassName". Because it should be Elements not Element.
Hope the following demo can help you out.
$(function() {_x000D_
$("button").on('click', function() {_x000D_
var data = "";_x000D_
var tableData = [];_x000D_
var rows = $("table tr");_x000D_
rows.each(function(index, row) {_x000D_
var rowData = [];_x000D_
$(row).find("th, td").each(function(index, column) {_x000D_
rowData.push(column.innerText);_x000D_
});_x000D_
tableData.push(rowData.join(","));_x000D_
});_x000D_
data += tableData.join("\n");_x000D_
$(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
type: "text/csv"_x000D_
})) + '/>');_x000D_
_x000D_
_x000D_
$('#download-link')[0].click();_x000D_
$('#download-link').remove();_x000D_
});_x000D_
});
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
border: 1px solid #aaa;_x000D_
padding: 0.5rem;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
background-color: #fff;_x000D_
border: 1px solid #000;_x000D_
margin-top: 0.5rem;_x000D_
border-radius: 3px;_x000D_
padding: 0.5rem 1rem;_x000D_
font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
cursor: pointer;_x000D_
background-color: #000;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id='PrintDiv'>_x000D_
<table id="mainTable">_x000D_
<tr>_x000D_
<td>Col1</td>_x000D_
<td>Col2</td>_x000D_
<td>Col3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val1</td>_x000D_
<td>Val2</td>_x000D_
<td>Val3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val11</td>_x000D_
<td>Val22</td>_x000D_
<td>Val33</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Val111</td>_x000D_
<td>Val222</td>_x000D_
<td>Val333</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="btn-group">_x000D_
<button>csv</button>_x000D_
</div>
_x000D_
You should not define global variables in header files. You can declare them as extern
in header file and define them in a .c
source file.
(Note: In C, int i;
is a tentative definition, it allocates storage for the variable (= is a definition) if there is no other definition found for that variable in the translation unit.)
>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
1) Article.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent{
protected $table = 'articles';
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
}
2) Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent
{
protected $table = "categories";
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
3) User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent
{
protected $table = 'users';
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
and you can use this like so:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
You can learn more at http://laravel.com/docs/5.0/eloquent
If you don't want 'a' in the index
In :
col = ['a','b','c']
data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In :
data2 = data.set_index('a')
Out:
b c
a
1 2 3
10 11 12
20 21 22
In :
data2.index.name = None
Out:
b c
1 2 3
10 11 12
20 21 22
rdd = textFile('/data/{1.txt,2.txt}')
The easiest way without installing msysgit is right click on the Git Bash shortcut icon ? Start in: ? "C:\Program Files (x86)".
Change the Start in entry and point out the Git Bash starting position. If you don't remove the --cd-to-home
part from the Target box, the Start in change gets overridden.
In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;"
to the <ul class="navbar-nav">
and then add the ml-auto
class to your navbar item.
For Spring boot web apps, Spring boot provides the out-of-box solution for graceful shutdown from version 2.3.0.RELEASE
.
An excerpt from Spring doc
Refer this answer for the Code Snippet
For TFS 2013:
Start in VisualStudio-Team Explorer, in the PendingChanges Dialog undo the Changes whith the state [add], which should be ignored.
Visual Studio will detect the Add(s) again. Click On "Detected: x add(s)"-in Excluded Changes
In the opened "Promote Cadidate Changes"-Dialog You can easy exclude Files and Folders with the Contextmenu. Options are:
Don't forget to Check In the changed .tfignore-File.
For VS 2015/2017:
The same procedure: In the "Excluded Changes Tab" in TeamExplorer\Pending Changes click on Detected: xxx add(s)
The "Promote Candidate Changes" Dialog opens, and on the entries you can Right-Click for the Contextmenu. Typo is fixed now :-)
Extension attributes are added by Exchange. According to this Technet article something like this should work:
Set-Mailbox -Identity "anyUser" -ExtensionCustomAttribute4 @{Remove="myString"}
To make changes to sudo from putty/bash:
I came upon this post, and while it has already been answered, felt I should post some information that helped me with this problem specific to IE 10, and might help others arriving at this post with a similar problem.
I was baffled how animated gifs were just not displaying in IE 10 and then found this gem.
Tools→Internet Options→Advanced→MultiMedia→Play animations in webpages
hope this helps.
Don't know why (the method is not documented), but by looking at the source code, this line should do it :
mime_body_part.setHeader("Content-Type", "text/html");
Attribute_Brands is a named range.
On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.
This will take you to the named range.
The data in it can be updated by typing new values into the cells.
The named range can be altered via the 'Insert - Name - Define' menu.
Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:
NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.
Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:
export NLS_LANG=AMERICAN_AMERICA.UTF8
Oracle gets a big fat F for usability.
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle: https://jsfiddle.net/zm75cq2a/
// using System.Xml;
String rawXml =
@"<root>
<person firstname=""Riley"" lastname=""Scott"" />
<person firstname=""Thomas"" lastname=""Scott"" />
</root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);
I think this should work.
I've come across many errors on Windows XP computers when using WMIC (eg due to corrupted files on machines). Hence imo best not to use WMIC for Win XP in code. No problems with WMIC on Win 7 though.
I went through this when trying to get a clientcert and private key out of a keystore.
The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version
to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working
So export the keys into .p12
keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \ -srcstoretype JKS -deststoretype PKCS12 \ -srcstorepass $jkspassword -deststorepass $p12password -srcalias $myalias -destalias $myalias \ -srckeypass $keypass -destkeypass $keypass -noprompt
And generate the pem file that holds only the key
echo making ${fileroot}.key.pem openssl pkcs12 -in $p12 -out ${fileroot}.key.pem \ -passin pass:$p12password \ -passout pass:$p12password -nocerts
mkdir ~/nss chmod 700 ~/nss certutil -N -d ~/nss
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >
Now curl should work.
curl --insecure --cert <client cert alias>:<password for cert> \ --key ${fileroot}.key.pem <URL>
As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.
I was given a bunch of columns from a CSV spreadsheet of full names of users and I needed to keep the formatting, with spaces. The easiest way I found to get them in while using ruby was to do:
names = %( Porter Smith
Jimmy Jones
Ronald Jackson).split('\n')
This highlights that %()
creates a string like "Porter Smith\nJimmyJones\nRonald Jackson"
and to get the array you split
the string on the "\n"
["Porter Smith", "Jimmy Jones", "Ronald Jackson"]
So to answer the OP's original question too, they could have wrote %(cgi\ spaeinfilename.rb;complex.rb;date.rb).split(';')
if there happened to be space
when you want the space
to exist in the final array output.
I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try
adb shell ls -R /
You probably need the root permission though.
Edit:
As other answers suggest, use ls
with grep
like this:
adb shell ls -Ral yourDirectory | grep -i yourString
eg.
adb shell ls -Ral / | grep -i myfile
-i
is for ignore-case. and /
is the root directory.
I'm using Kotlin here
Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example
var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
strwrt=FileWriter(File("sdcard/${NamaFile}"))
strwrt.write(teks)
strwrt.close()
after that you can acces File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folder.
$time = strtotime("2010.12.11");
$final = date("Y-m-d", strtotime("+1 month", $time));
// Finally you will have the date you're looking for.
This comment syntax should work for you:
@* enter comments here *@
getAssets()
is only works in Activity in other any class you have to use Context
for it.
Make a constructor for Utils class pass reference of activity (ugly way) or context of application as a parameter to it. Using that use getAsset() in your Utils class.
I suppose that you are using an array to create your select
form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php @print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php @print($selected[$k]);?>>Yes</options>
<option value="2" <?php @print($selected[$k]);?>>No</options>
<option value="3" <?php @print($selected[$k]);?>>Fine</options>
Notes that I don't know:
$_REQUEST
, You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.
For example:
HTML:
<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>
<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>
JS:
$( ".selected" ).each(function(index) {
$(this).on("click", function(){
// For the boolean value
var boolKey = $(this).data('selected');
// For the mammal value
var mammalKey = $(this).attr('id');
});
});
Instead of using recursion to deal with multi-dimensional arrays, which can be slow, you can do the following:
$res = json_decode(
json_encode(
iconv(
mb_detect_encoding($res, mb_detect_order(), true),
'UTF-8',
$res
)
),
true
);
This will convert any character set to UTF8 and also preserve keys in your array. So instead of "lazy" converting each row using array_walk
, you could do the whole result set in one go.
Use DateTime::createFromFormat like this :
$date = DateTime::createFromFormat('m/d/Y H:i:s', $input_string.' 00:00:00');
$mysql_date_string = $date->format('Y-m-d H:i:s');
You can adapt this to any input format, whereas strtotime() will assume you're using the US date format if you use /, even if you're not.
The added 00:00:00 is because createFromFormat will use the current date to fill missing data, ie : it will take the current hour:min:sec and not 00:00:00 if you don't precise it.
I had the same issue. Tried all the above answers. It was actually complained about a .dll file. I clean the project in Visual Studio but the .dll file still remains, so I deleted in manually from the bin folder and it worked.
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Maybe your method for adding items into fragment should be public (placed in desired Fragment) and should have parameter the same type as selectedItems ..
That will make it visible from activity, which will have selectedItems array and voila..
p.s. better name it addItemsFromArray(typeOfSelectedItems[] pSelectedItems)
cause name addItem()
is quite undescriptive
Edit: stackoverflow just suggested similar topic :) Check here for detailed idea implementation.. :)
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
Please find the below query also split the string with delimeter.
Select Substring(@String1,0,CharIndex(@delimeter,@String1))
The following works in Firefox interestingly enough if I remove the write line it doesn't work. Anyone have any insight why the write line is needed.
<script type="text/javascript">
document.write(".");
document.body.style.MozUserSelect='none';
</script>
team! For execute SQL-query from your Servlet you should add JDBC jar library in folder
WEB-INF/lib
After this you could call driver, example :
Class.forName("oracle.jdbc.OracleDriver");
Now Y can use connection to DB-server
==> 73!
select A, B, 'c' as C
from MyTable
**
bundle install --no-deployment
**
$ jekyll help
jekyll 4.0.0 -- Jekyll is a blog-aware, static site generator in Ruby
I am very late to this but I want to mention that that new is actually unsafe in the Obj-C with Swift world. Swift will only create a default init method if you do not create any other initializer. Calling new on a swift class with a custom initializer will cause a crash. If you use alloc/init then the compiler will properly complain that init does not exist.
I had Same problem and soved by moved
ic_launcher.png files from drawable folder to mipmap folder.
The readr package has a function to do everything for you.
install.packages("readr") # you only need to do this one time on your system
library(readr)
mystring <- read_file("path/to/myfile.txt")
This replaces the version in the package stringr.
Static memory allocation is allocated memory before execution pf program during compile time. Dynamic memory alocation is alocated memory during execution of program at run time.
Download and run the latest MSI. The MSI will update your installed node and npm.
I recommend to see this:
Optimizing AngularJS: 1200ms to 35ms
they made a new directive by optimizing ng-repeat at 4 parts:
Optimization#1: Cache DOM elements
Optimization#2: Aggregate watchers
Optimization#3: Defer element creation
Optimization#4: Bypass watchers for hidden elements
the project is here on github:
1- include these files in your single-page app:
2- add module dependency:
var app = angular.module("app", ['sly']);
3- replace ng-repeat
<tr sly-repeat="m in rows"> .....<tr>
ENjoY!
Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79
.
Ignore XAK. Do not explore any private methods if you want your app to have the chance of being accepted by apple.
This is easiest if you are using Interface Builder. You would add a UIView at the top of the view (where the images will go), then add your tableview below that. IB should size it accordingly; that is, the top of the tableview touches the bottom of the UIView you've just added and it's height covers the rest of the screen.
The thinking here is that if that UIView is not actually part of the table view, it will not scroll with the tableview. i.e. ignore the tableview header.
If you're not using interface builder, it's a little more complicated because you've got to get the positioning and height correct for the tableview.
Actually there is an operator for that in PostgreSQL:
SELECT *
FROM table
WHERE lower(value) ~~ ANY('{%foo%,%bar%,%baz%}');
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
Use Interfaces to enforce a contract ACROSS families of unrelated classes. For example, you might have common access methods for classes that represent collections, but contain radically different data i.e. one class might represent a result set from a query, while the other might represent the images in a gallery. Also, you can implement multiple interfaces, thus allowing you to blend (and signify) the capabilities of the class.
Use Inheritance when the classes bear a common relationship and therefore have a similair structural and behavioural signature, i.e. Car, Motorbike, Truck and SUV are all types of road vehicle that might contain a number of wheels, a top speed
You can use Carbon library.
Example: Next week friday
Carbon::parse("friday next week");
One can reproduce the error with the code below:
public ActionResult ClosingTheConnectionAction(){
try
{
//we need to set buffer to false to
//make sure data is written in chunks
Response.Buffer = false;
var someText = "Some text here to make things happen ;-)";
var content = GetBytes( someText );
for(var i=0; i < 100; i++)
{
Response.OutputStream.Write(content, 0, content.Length);
}
return View();
}
catch(HttpException hex)
{
if (hex.Message.StartsWith("The remote host closed the connection. The error code is 0x800704CD."))
{
//react on remote host closed the connection exception.
var msg = hex.Message;
}
}
catch(Exception somethingElseHappened)
{
//handle it with some other code
}
return View();
}
Now run the website in debug mode. Put a breakpoint in the loop that writes to the output stream. Go to that action method and after the first iteration passed close the tab of the browser. Hit F10 to continue the loop. After it hit the next iteration you will see the exception. Enjoy your exception :-)
We can accomplish the task in two simple way one is using Json.NET dll and another is by using StringBuilder class.
Using Newtonsoft Json.NET
string JSONresult;
JSONresult = JsonConvert.SerializeObject(dt);
Response.Write(JSONresult);
Reference Link: Newtonsoft: Convert DataTable to JSON object in ASP.Net C#
Using StringBuilder
public string DataTableToJsonObj(DataTable dt)
{
DataSet ds = new DataSet();
ds.Merge(dt);
StringBuilder JsonString = new StringBuilder();
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
JsonString.Append("[");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
JsonString.Append("{");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
if (j < ds.Tables[0].Columns.Count - 1)
{
JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\",");
}
else if (j == ds.Tables[0].Columns.Count - 1)
{
JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\"");
}
}
if (i == ds.Tables[0].Rows.Count - 1)
{
JsonString.Append("}");
}
else
{
JsonString.Append("},");
}
}
JsonString.Append("]");
return JsonString.ToString();
}
else
{
return null;
}
}
// Here is the code for unicode strings!
int mystrstr(wchar_t *txt1,wchar_t *txt2)
{
wchar_t *posstr=wcsstr(txt1,txt2);
if(posstr!=NULL)
{
return (posstr-txt1);
}else
{
return -1;
}
}
// assume: supplied buff is enough to hold generated text
void StringReplace(wchar_t *buff,wchar_t *txt1,wchar_t *txt2)
{
wchar_t *tmp;
wchar_t *nextStr;
int pos;
tmp=wcsdup(buff);
pos=mystrstr(tmp,txt1);
if(pos!=-1)
{
buff[0]=0;
wcsncpy(buff,tmp,pos);
buff[pos]=0;
wcscat(buff,txt2);
nextStr=tmp+pos+wcslen(txt1);
while(wcslen(nextStr)!=0)
{
pos=mystrstr(nextStr,txt1);
if(pos==-1)
{
wcscat(buff,nextStr);
break;
}
wcsncat(buff,nextStr,pos);
wcscat(buff,txt2);
nextStr=nextStr+pos+wcslen(txt1);
}
}
free(tmp);
}
Much longer solution, but accounts for the following scenarios:
Is the image taller than the bounding box
private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
{
//throw error if bouning box is to small
if (desiredWidth < 4 || desiredHeight < 4)
throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");
var original = Bitmap.FromFile(sourceImage.FullName);
//store image widths in variable for easier use
var oW = (decimal)original.Width;
var oH = (decimal)original.Height;
var dW = (decimal)desiredWidth;
var dH = (decimal)desiredHeight;
//check if image already fits
if (oW < dW && oH < dH)
return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
//check for double squares
if (oW == oH && dW == dH)
{
//image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
Bitmap square = new Bitmap(original, (int)dW, (int)dH);
original.Dispose();
return square;
}
//check original image is square
if (oW == oH)
{
//image is square, bounding box isn't. Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
int smallSide = (int)Math.Min(dW, dH);
Bitmap square = new Bitmap(original, smallSide, smallSide);
original.Dispose();
return square;
}
//not dealing with squares, figure out resizing within aspect ratios
if (oW > dW && oH > dH) //image is wider and taller than bounding box
{
var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
var nW = oW * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
else
{
if (oW > dW) //image is wider than bounding box
{
var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
var nW = oW * r; //downscale image by r to fit in the bounding box...
var nH = oH * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
else
{
//original image is taller than bounding box
var r = dH / oH;
var nH = oH * r;
var nW = oW * r;
var resized = new Bitmap(original, (int)nW, (int)nH);
original.Dispose();
return resized;
}
}
}
I spent almost two days on finding the solution for this problem and I found this at last.
This uses javascript and jquery.
(GitHub) pointer_events_polyfill
This could use a javascript plug-in to be downloaded/copied.
Just copy/download the codes from that site and save it as pointer_events_polyfill.js
. Include that javascript to your site.
<script src="JS/pointer_events_polyfill.js></script>
Add this jquery scripts to your site
$(document).ready(function(){
PointerEventsPolyfill.initialize({});
});
And don't forget to include your jquery plug-in.
It works! I can click elements under the transparent element. I'm using IE 10. I hope this can also work in IE 9 and below.
EDIT: Using this solution does not work when you click the textboxes below the transparent element. To solve this problem, I use focus when the user clicks on the textbox.
Javascript:
document.getElementById("theTextbox").focus();
JQuery:
$("#theTextbox").focus();
This lets you type the text into the textbox.
There is a much faster CTE implementation available in this excellent post: http://weblogs.sqlteam.com/mladenp/archive/2009/07/28/SQL-Server-2005-Fast-Running-Totals.aspx
The problem in this thread can be expressed like this:
DECLARE @RT INT
SELECT @RT = 0
;
WITH abcd
AS ( SELECT TOP 100 percent
id
,SomeNumt
,MySum
order by id
)
update abcd
set @RT = MySum = @RT + SomeNumt
output inserted.*
The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.
For Ubuntu use
apt-get install openjdk-7-jdk
to get Java 7 as default. You may have to uninstall openjdk-6 first.
use set serveroutput on;
for example:
set serveroutput on;
DECLARE
x NUMBER;
BEGIN
x := 72600;
dbms_output.put_line('The variable X = '); dbms_output.put_line(x);
END;
Angular has a built-in filter
for showing JSON
<pre>{{data | json}}</pre>
Note the use of the pre
-tag to conserve whitespace and linebreaks
Demo:
angular.module('app', [])_x000D_
.controller('Ctrl', ['$scope',_x000D_
function($scope) {_x000D_
_x000D_
$scope.data = {_x000D_
a: 1,_x000D_
b: 2,_x000D_
c: {_x000D_
d: "3"_x000D_
},_x000D_
};_x000D_
_x000D_
}_x000D_
]);
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="app">_x000D_
_x000D_
<head>_x000D_
<script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>_x000D_
</head>_x000D_
_x000D_
<body ng-controller="Ctrl">_x000D_
<pre>{{data | json}}</pre>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
There's also an angular.toJson
method, but I haven't played around with that (Docs)
If you have worked with time/date formatting/parsing in other languages you might have noticed that the other languages use special placeholders for time/date formatting. For eg ruby language uses
%d for day
%Y for year
etc. Golang, instead of using codes such as above, uses date and time format placeholders that look like date and time only. Go uses standard time, which is:
Mon Jan 2 15:04:05 MST 2006 (MST is GMT-0700)
or
01/02 03:04:05PM '06 -0700
So if you notice Go uses
01 for the day of the month,
02 for the month
03 for hours,
04 for minutes
05 for second
and so on
Therefore for example for parsing 2020-01-29, layout string should be 06-01-02 or 2006-01-02.
You can refer to the full placeholder layout table at this link - https://golangbyexample.com/parse-time-in-golang/
Indeed, it is O(n^2). See also a very similar example with the same runtime here.
Based on Olivier Refalo's answer
if [ $# -eq 2 ]
then
echo "Setting tracking for branch " $1 " -> " $2
git branch --set-upstream $1 $2
else
echo "-- Local --"
git for-each-ref --shell --format="[ %(upstream:short) != '' ] && echo -e '\t%(refname:short) <--> %(upstream:short)'" refs/heads | sh
echo "-- Remote --"
REMOTES=$(git remote -v)
if [ "$REMOTES" != '' ]
then
echo $REMOTES
fi
fi
It shows only local with track configured.
Write it on a script called git-track on your path an you will get a git track command
A more elaborated version on https://github.com/albfan/git-showupstream
Add ?var1=data1&var2=data2
to the end of url to submit values to the page via GET:
using System.Net;
using System.IO;
string url = "https://www.example.com/scriptname.php?var1=hello";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
For a more generic answer, convert the error value to hex, then lookup the hex value at Windows Task Scheduler Error and Success Constants
This seems too simple, but:
val.Replace("-","");
From something that is ContainerAware (like a controller):
$request = $this->container->get('request');
$routeName = $request->get('_route');
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
According to the doc, scipy.misc.imread
is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread
instead.
Example:
import imageio
im = imageio.imread('my_image.png')
print(im.shape)
You can also use imageio to load from fancy sources:
im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')
Edit:
To load all of the *.png
files in a specific folder, you could use the glob
package:
import imageio
import glob
for im_path in glob.glob("path/to/folder/*.png"):
im = imageio.imread(im_path)
print(im.shape)
# do whatever with the image here
You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!
Since at this point this question is almost a support group for people who suffer with various reasons on why WhatsApp wouldn't load the image preview, here's what was the root cause for my case, hoping it may help someone eventually:
og:image
content link is using HTTPSWhen I made my website available through https
, I forgot to specifically change the meta tags from http
to https
. Every other social media preview handled the image regardless, except for WhatsApp.
Simply making it https
fixed it for me.
check if the div exists with a certain class
if ($(".mydivclass").length > 0) //it exists
{
}
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
A very basic approach is alert(arrayObj.join('\n'))
, which will display each array element in a row.
I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:
string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
*
FROM
tableA
WHERE
Name = '{0}' AND
Gender = '{1}'", name, gender);
It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting
All are good answers explaining why you cannot modify string literals because they are placed in read-only memory. However, when push comes to shove, there is a way to do this. Check out this example:
#include <sys/mman.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int take_me_back_to_DOS_times(const void *ptr, size_t len);
int main()
{
const *data = "Bender is always sober.";
printf("Before: %s\n", data);
if (take_me_back_to_DOS_times(data, sizeof(data)) != 0)
perror("Time machine appears to be broken!");
memcpy((char *)data + 17, "drunk!", 6);
printf("After: %s\n", data);
return 0;
}
int take_me_back_to_DOS_times(const void *ptr, size_t len)
{
int pagesize;
unsigned long long pg_off;
void *page;
pagesize = sysconf(_SC_PAGE_SIZE);
if (pagesize < 0)
return -1;
pg_off = (unsigned long long)ptr % (unsigned long long)pagesize;
page = ((char *)ptr - pg_off);
if (mprotect(page, len + pg_off, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
return -1;
return 0;
}
I have written this as part of my somewhat deeper thoughts on const-correctness, which you might find interesting (I hope :)).
Hope it helps. Good Luck!
There is already a Connect Middleware for Timeout support:
var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4
app.use(timeout(120000));
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut
middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.
Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:
The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
use property UseSimpleDictionaryFormat
on DataContractJsonSerializer
and set it to true
.
Does the job :)
Edited Java 8 Solution:
final Drawable drawable =
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());
You can declare drawable
final
in this case.
As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.
Seems to be identical just in case that SQL server will not try to read data which is not required for the query, the optimizer is clever enough
It can have sense when join on complex query (i.e which have joings, groupings etc itself) then, yes, it is better to specify required fields.
But there is one more point. If the query is simple there is no difference but EVERY extra action even which is supposed to improve performance makes optimizer works harder and optimizer can fail to get the best plan in time and will run not optimal query. So extras select can be a such action which can even decrease performance
public String getFileNameWithoutExtension(URL url) {
String path = url.getPath();
if (StringUtils.isBlank(path)) {
return null;
}
if (StringUtils.endsWith(path, "/")) {
//is a directory ..
return null;
}
File file = new File(url.getPath());
String fileNameWithExt = file.getName();
int sepPosition = fileNameWithExt.lastIndexOf(".");
String fileNameWithOutExt = null;
if (sepPosition >= 0) {
fileNameWithOutExt = fileNameWithExt.substring(0,sepPosition);
}else{
fileNameWithOutExt = fileNameWithExt;
}
return fileNameWithOutExt;
}
On load of My Windows Form the comboBox
will display the ClassName
column of my DataTable
as it's the DisplayMember
also has its ValueMember
(not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}