There is much simpler way:
using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
This code snippet is working properly
DataTable DT = new DataTable();
DT.Columns.Add("first", typeof(string));
DT.Columns.Add("second", typeof(string));
DT.Rows.Add("ss", "test1");
DT.Rows.Add("sss", "test2");
DT.Rows.Add("sys", "test3");
DT.Rows.Add("ss", "test4");
DT.Rows.Add("ss", "test5");
DT.Rows.Add("sts", "test6");
var dr = DT.AsEnumerable().GroupBy(S => S.Field<string>("first")).Select(S => S.First()).
Select(S => new KeyValuePair<string, string>(S.Field<string>("first"), S.Field<string>("second"))).
ToDictionary(S => S.Key, T => T.Value);
foreach (var item in dr)
{
Console.WriteLine(item.Key + "-" + item.Value);
}
Use the ToDictionary
method directly.
var result =
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);
Not a Java guy, but in JS and other languages I use it's "Not a Number", meaning some operation caused it to become not a valid number.
you should be searching about how to add favicon.ico
. You can try adding favicon.ico
directly in your html pages like this
<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />
Or you can update that in your webserver
. It is advised to add in your webserver
as you don't need to add this in each of your html
pages (assuming no includes
).
To add in your apache
place the favicon.ico
in your root website director and add this in httpd.conf
AddType image/x-icon .ico
Use the <embed>
element:
<embed src="file.swf" width="854" height="480"></embed>
You can also use django.utils.html.escape
from django.utils.html import escape
something_nice = escape(request.POST['something_naughty'])
Try to use:
require('events').EventEmitter.defaultMaxListeners = Infinity;
This is the proper way to access data in laravel :
@foreach($data-> ac as $link)
{{$link->url}}
@endforeach
Using Spring Boot (1.2.4) and Jackson (2.4.6) the following annotation based configuration worked for me.
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
return mapper;
}
}
Here is simplified tutorial:
For more I recommend to get some literature.
You do not need to activate the sheet (you'll take a huge performance hit for doing so, actually). Since you are declaring an object for the sheet, when you call the method starting with "wb." you are selecting that object. For example, you can jump in between workbooks without activating anything like here:
Sub Test()
Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test1.xls")
Dim wb2 As Excel.Workbook
Set wb2 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test2.xls")
wb1.Sheets("Sheet1").Cells(1, 1).Value = 24
wb2.Sheets("Sheet1").Cells(1, 1).Value = 24
wb1.Sheets("Sheet1").Cells(2, 1).Value = 54
End Sub
A function call needs to be performed with objects. You are doing the equivalent of this:
// function declaration/definition
void foo(int) {}
// function call
foo(int); // wat!??
i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing
int i = 42;
foo(i);
or
foo(42);
It looks like you are trying to use (almost) straight up C code here. Go has a few differences.
const
. The term const
has a different meaning in Go, as it does in C. The list should be defined as var
instead.basenameOpts
as opposed to basename_opts
.char
type in Go. You probably want byte
(or rune
if you intend to allow unicode codepoints).var x = foo
.For example:
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts = []opt {
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
An alternative is to declare the list with its type and then use an init
function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init
functions are run when the program is being initialized and are guaranteed to finish before main
is executed. You can have multiple init
functions in a package, or even in the same source file.
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts []opt
func init() {
basenameOpts = []opt{
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
}
Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.
private string GetFileSize(double byteCount)
{
string size = "0 Bytes";
if (byteCount >= 1073741824.0)
size = String.Format("{0:##.##}", byteCount / 1073741824.0) + " GB";
else if (byteCount >= 1048576.0)
size = String.Format("{0:##.##}", byteCount / 1048576.0) + " MB";
else if (byteCount >= 1024.0)
size = String.Format("{0:##.##}", byteCount / 1024.0) + " KB";
else if (byteCount > 0 && byteCount < 1024.0)
size = byteCount.ToString() + " Bytes";
return size;
}
private void btnBrowse_Click(object sender, EventArgs e)
{
if (openFile1.ShowDialog() == DialogResult.OK)
{
FileInfo thisFile = new FileInfo(openFile1.FileName);
string info = "";
info += "File: " + Path.GetFileName(openFile1.FileName);
info += Environment.NewLine;
info += "File Size: " + GetFileSize((int)thisFile.Length);
label1.Text = info;
}
}
This is one way to do it aswell (The number 1073741824.0 is from 1024*1024*1024 aka GB)
int64
(from numpy) to int
.For example, if variable x
is a int64:
int(x)
If is array of int64:
map(int, x)
I'm not sure if Chrome has added this feature since the last answer, but I was able to view the json response by...
...I was able to view the response as a readable hierarchy that showed what to ask for and what is returned. (Neither Network or Resources tab had anything helpful that I was able to find.)
Happy requesting!
For the server-side solution (which your question was originally ambiguous about), this page at sun lists one way to specify a JRE. Specifically,
<OBJECT
classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
width="200" height="200">
<PARAM name="code" value="Applet1.class">
</OBJECT>
The classid attribute identifies which version of Java Plug-in to use.
Following is an alternative form of the classid attribute:
classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"
In this form, "xxxx", "yyyy", and "zzzz" are four-digit numbers that identify the specific version of Java Plug-in to be used.
For example, to use Java Plug-in version 1.5.0, you specify:
classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"
Is there an easy way to view all methods which contain this comment? Some sort of menu option?
Yes, choose one of the following:
Go to Window ? Show View ? Tasks (Not TaskList). The new view will show up where the "Console" and "Problems" tabs are by default.
As mentioned elsewhere, you can see them next to the scroll bar as little blue rectangles if you have the source file in question open.
If you just want the // TODO Auto-generated method stub
messages (rather than all // TODO
messages) you should use the search function (Ctrl-F for ones in this file Search ? Java Search ? Search string for the ability to specify this workspace, that file, this project, etc.)
For repeating the last command in python, you can use <Alt + n>
in windows
As pointed out by @Christian, best to try operation first then login only if necessary. Problem is that "if necessary" is not that obvious to do robustly. One approach is to compare the stderr of the docker operation with some strings that are known (by trial and error). For example,
try "docker OPERATION"
if it failed:
capture the stderr of "docker OPERATION"
if it ends with "no basic auth credentials":
try docker login
else if it ends with "not found":
fatal error: image name/tag probably incorrect
else if it ends with <other stuff you care to trap>:
...
else:
fatal error: unknown cause
try docker OPERATION again
if this fails: you're SOL!
ExeOutput is also can Turn PHP Websites into Windows Applications and Software
Turn PHP Websites into Windows Applications and Software
Applications made with ExeOutput for PHP run PHP scripts, PHP applications, and PHP websites natively, and do not require a web server, a web browser, or PHP distribution. They are stand-alone and work on any computer with recent Windows versions.
ExeOutput for PHP is a powerful website compiler that works with all of the elements found on modern sites: PHP scripts, JavaScript, HTML, CSS, XML, PDF files, Flash, Flash videos, Silverlight videos, databases, and images. Combining these elements with PHP Runtime and PHP Extensions, ExeOutput for PHP builds an EXE file that contains your complete application.
PEP 3155 introduced __qualname__
, which was implemented in Python 3.3.
For top-level functions and classes, the
__qualname__
attribute is equal to the__name__
attribute. For nested classes, methods, and nested functions, the__qualname__
attribute contains a dotted path leading to the object from the module top-level.
It is accessible from within the very definition of a class or a function, so for instance:
class Foo:
print(__qualname__)
will effectively print Foo
.
You'll get the fully qualified name (excluding the module's name), so you might want to split it on the .
character.
However, there is no way to get an actual handle on the class being defined.
>>> class Foo:
... print('Foo' in globals())
...
False
As of now in 2017, you can just write
$(window).on('wheel', function(event){
// deltaY obviously records vertical scroll, deltaX and deltaZ exist too
if(event.originalEvent.deltaY < 0){
// wheeled up
}
else {
// wheeled down
}
});
Works with current Firefox 51, Chrome 56, IE9+
I had the same problem.
after a few minutes, i figured it that i was trying the load the file.fxml from wrong location.
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/[wrong-path]/abc.fxml"));
fxmlLoader.setClassLoader(getClass().getClassLoader());
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
fxmlLoader.load();
In case You are using the VSC's screen terminal, The error might be due to the fact that you already runserver in some other shell.
Just click on the dropbox on the left of the + sign in the header of the terminal of VSC and select some other shell and check if the server is already running there. Quit that server and you are ready to launch a another server.
If you're concatenating something in the loop, you can do it in this way too:
$coma = "";
foreach($a as $b){
$string .= $coma.$b;
$coma = ",";
}
If I get you right, you need ..\..\src
When I
git init
a folder it doesn't create a master branch
This is true, and expected behaviour. Git will not create a master
branch until you commit something.
When I do
git --bare init
it creates the files.
A non-bare git init
will also create the same files, in a hidden .git
directory in the root of your project.
When I type
git branch master
it says "fatal: Not a valid object name: 'master'"
That is again correct behaviour. Until you commit, there is no master branch.
You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add
them to prepare a commit. Then git commit
to create your initial commit and master
branch.
SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'
...is probably what you want.
>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…
Since the answer has already been picked and problem known to be a bug, I thought I would add a "Possible Work Around".
You can toggle fullScreen mode when soft keyboard is shown. This allows the "adjustPan" to work correctly.
In other words, I still use @android:style/Theme.Black.NoTitleBar.Fullscreen as part of the application theme and stateVisible|adjustResize as part of the activity window soft input mode but to get them to work together I must toggle fullscreen mode before the keyboard comes up.
Use the following Code:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
Note - inspiration came from: Hiding Title in a Fullscreen mode
The solution:
particular_script || true
Example:
$ cat /tmp/1.sh
particular_script()
{
false
}
set -e
echo one
particular_script || true
echo two
particular_script
echo three
$ bash /tmp/1.sh
one
two
three
will be never printed.
Also, I want to add that when pipefail
is on,
it is enough for shell to think that the entire pipe has non-zero exit code
when one of commands in the pipe has non-zero exit code (with pipefail
off it must the last one).
$ set -o pipefail
$ false | true ; echo $?
1
$ set +o pipefail
$ false | true ; echo $?
0
if you don't want to use MultipartFile.transferTo(). You can write file like this
val dir = File(filePackagePath)
if (!dir.exists()) dir.mkdirs()
val file = File("$filePackagePath${multipartFile.originalFilename}").apply {
createNewFile()
}
FileOutputStream(file).use {
it.write(multipartFile.bytes)
}
You can also try right menu click option to format the selection of the coding document. Take a look at below screen shot
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
Just a slight modification for the code written by Roel Van de Paar, as all credit goes to him. I am using this in Windows and it is working perfectly, both for setting and adding cookies:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('chromedriver.exe',options=chrome_options)
driver.get('https://web.whatsapp.com') # Already authenticated
time.sleep(30)
The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.
Something like:
public void method() throws Exception{
try{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}catch(IOException e){
System.out.println(e.getMessage());
}
}
or
public void method(){
try{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}catch(IOException e){
System.out.println("Catching IOException");
System.out.println(e.getMessage());
}catch(Exception e){
System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
System.out.println(e.getMessage());
}
}
To answer the question:
What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes, Websocket can be used to transmit over 30 fps and even 60 fps.
The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.
Don't forget to check if the conversion was successful!
bool ok;
auto str= tr("1337");
str.toDouble(&ok); // returns 1337.0, ok set to true
auto strr= tr("LEET");
strr.toDouble(&ok); // returns 0.0, ok set to false
// "Main" is name of .storybord file "
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// "MiniGameView" is the ID given to the ViewController in the interfacebuilder
// MiniGameViewController is the CLASS name of the ViewController.swift file acosiated to the ViewController
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MiniGameView") as MiniGameViewController
var rootViewController = self.window!.rootViewController
rootViewController?.presentViewController(setViewController, animated: false, completion: nil)
This worked fine for me when i put it in AppDelegate
How about this?
#include <stdio.h>
typedef struct hello {
int (*someFunction)();
} hello;
int foo() {
return 0;
}
hello Hello() {
struct hello aHello;
aHello.someFunction = &foo;
return aHello;
}
int main()
{
struct hello aHello = Hello();
printf("Print hello: %d\n", aHello.someFunction());
return 0;
}
If you want a native bash
solution
for file in /home/user/*; do
echo "${file##*/}"
done
The above uses Parameter Expansion which is native to the shell and does not require a call to an external binary such as basename
However, might I suggest just using find
find /home/user -type f -printf "%f\n"
class Student(object):
name = ""
age = 0
major = ""
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def make_student(name, age, major):
student = Student(name, age, major)
return student
Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:
class Student(object):
name = ""
age = 0
major = ""
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
# Note: I didn't need to create a variable in the class definition before doing this.
student.gpa = float(4.0)
return student
I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.
function selectText(containerid) {_x000D_
if (document.selection) { // IE_x000D_
var range = document.body.createTextRange();_x000D_
range.moveToElementText(document.getElementById(containerid));_x000D_
range.select();_x000D_
} else if (window.getSelection) {_x000D_
var range = document.createRange();_x000D_
range.selectNode(document.getElementById(containerid));_x000D_
window.getSelection().removeAllRanges();_x000D_
window.getSelection().addRange(range);_x000D_
}_x000D_
}
_x000D_
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>
_x000D_
Now you have to pass the ID as an argument, which in this case is "selectable", but it's more global, allowing you to use it anywhere multiple times without using, as chiborg mentioned, jQuery.
Just in case that the remote file needs your credential to get accessed, you can generate a System.Net.WebClient object using cmdlet New-Object to "Copy File Remotely", like so
$Source = "\\192.168.x.x\somefile.txt"
$Dest = "C:\Users\user\somefile.txt"
$Username = "username"
$Password = "password"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$WebClient.DownloadFile($Source, $Dest)
Or if you need to upload a file, you can use UploadFile:
$Dest = "\\192.168.x.x\somefile.txt"
$Source = "C:\Users\user\somefile.txt"
$WebClient.UploadFile($Dest, $Source)
Loop through the dictionary to find the index and then remove it.
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
You may try this:
public static void main(String[] args) {
BigDecimal a = new BigDecimal("10.12345");
System.out.println(toPrecision(a, 2));
}
private static BigDecimal toPrecision(BigDecimal dec, int precision) {
String plain = dec.movePointRight(precision).toPlainString();
return new BigDecimal(plain.substring(0, plain.indexOf("."))).movePointLeft(precision);
}
OUTPUT:
10.12
Depends on what you run in that thread. If that's your code, then you can implement a stop condition (see other answers).
However, if what you want is to run someone else's code, then you should fork and start a process. Like this:
import multiprocessing
proc = multiprocessing.Process(target=your_proc_function, args=())
proc.start()
now, whenever you want to stop that process, send it a SIGTERM like this:
proc.terminate()
proc.join()
And it's not slow: fractions of a second. Enjoy :)
Try LIKE
construction, e.g. (assuming StudentId
is of type Char
, VarChar
etc.)
select *
from Students
where StudentId like '%' || TEXT || '%' -- <- TEXT - text to contain
In a project of mine I wrap Text
instances around Container
s. This particular code sample features two stacked Text objects.
Here's a code sample.
//80% of screen width
double c_width = MediaQuery.of(context).size.width*0.8;
return new Container (
padding: const EdgeInsets.all(16.0),
width: c_width,
child: new Column (
children: <Widget>[
new Text ("Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 ", textAlign: TextAlign.left),
new Text ("Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2", textAlign: TextAlign.left),
],
),
);
[edit] Added a width constraint to the container
From the documentation:
/is
Includes the same files./it
Includes "tweaked" files.
"Same files" means files that are identical (name, size, times, attributes). "Tweaked files" means files that have the same name, size, and times, but different attributes.
robocopy src dst sample.txt /is # copy if attributes are equal
robocopy src dst sample.txt /it # copy if attributes differ
robocopy src dst sample.txt /is /it # copy irrespective of attributes
This answer on Super User has a good explanation of what kind of files the selection parameters match.
With that said, I could reproduce the behavior you describe, but from my understanding of the documentation and the output robocopy
generated in my tests I would consider this a bug.
PS C:\temp> New-Item src -Type Directory >$null PS C:\temp> New-Item dst -Type Directory >$null PS C:\temp> New-Item src\sample.txt -Type File -Value "test001" >$null PS C:\temp> New-Item dst\sample.txt -Type File -Value "test002" >$null PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00" PS C:\temp> Set-ItemProperty dst\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00" PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ Modified 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ Same 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> Get-Content .\src\sample.txt test001 PS C:\temp> Get-Content .\dst\sample.txt test002
The file is listed as copied, and since it becomes a same file after the first robocopy
run at least the times are synced. However, even though seven bytes have been copied according to the output no data was actually written to the destination file in both cases despite the data flag being set (via /copyall
). The behavior also doesn't change if the data flag is set explicitly (/copy:d
).
I had to modify the last write time to get robocopy
to actually synchronize the data.
PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value (Get-Date) PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ 100% Newer 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> Get-Content .\dst\sample.txt test001
An admittedly ugly workaround would be to change the last write time of same/tweaked files to force robocopy
to copy the data:
& robocopy src dst /is /it /l /ndl /njh /njs /ns /nc |
Where-Object { $_.Trim() } |
ForEach-Object {
$f = Get-Item $_
$f.LastWriteTime = $f.LastWriteTime.AddSeconds(1)
}
& robocopy src dst /copyall /mir
Switching to xcopy
is probably your best option:
& xcopy src dst /k/r/e/i/s/c/h/f/o/x/y
Here is an edited version of your code which is based on ISO C++ and which works well with G++:
#include <string.h>
#include <iostream>
using namespace std;
#define NO_OF_TEST 1
struct studentType {
string studentID;
string firstName;
string lastName;
string subjectName;
string courseGrade;
int arrayMarks[4];
double avgMarks;
};
studentType input() {
studentType newStudent;
cout << "\nPlease enter student information:\n";
cout << "\nFirst Name: ";
cin >> newStudent.firstName;
cout << "\nLast Name: ";
cin >> newStudent.lastName;
cout << "\nStudent ID: ";
cin >> newStudent.studentID;
cout << "\nSubject Name: ";
cin >> newStudent.subjectName;
for (int i = 0; i < NO_OF_TEST; i++) {
cout << "\nTest " << i+1 << " mark: ";
cin >> newStudent.arrayMarks[i];
}
return newStudent;
}
int main() {
studentType s;
s = input();
cout <<"\n========"<< endl << "Collected the details of "
<< s.firstName << endl;
return 0;
}
Visit https://www.tutorialspoint.com/python/string_join.htm
s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))
ab cd ef
s="."
print(s.join(seq))
ab.cd.ef
SELECT
AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit,
BillLimit, Mode, PNotes, gtab82.memno
FROM
VCustomer AS v1
INNER JOIN
gtab82 ON gtab82.memacid = v1.AcId
WHERE (AcGrCode = '204' OR CreDebt = 'True')
AND Masked = 'false'
ORDER BY AcName
You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer
but only use it in the ON
clause for uncertain reasons. You may want to review that aspect of your code.
SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
string GetString(RichTextBox rtb)
{
var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
return textRange.Text;
}
You can make this.
CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
@CODE XML
,@ERRFLAG CHAR(1) = '0' OUTPUT
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )
IF @@ROWCOUNT = 0 SET @ERRFLAG = 200
SET NOCOUNT OFF
For those who want to convert an Int to a Unicode string, you can do the following:
let myInteger: Int = 97
// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
return ""
}
// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)
// results
print(myString) // a
Or alternatively:
let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
let myString = String(myUnicodeScalar)
}
A more concise version is:
def softmax(x):
return np.exp(x) / np.exp(x).sum(axis=0)
You could use this:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
BASED ON ANALOGY
Camel based routing can be understood much easily by putting yourself in the shoes of a Airline owner (eg.: American Airlines, Jet Airways) .
Purpose of 'your airline' is to 'carry' 'passengers' from one 'city' to another one in the world. You use aircrafts from different 'aircraft companies' like Boeing, Airbus, HAL for carrying passengers.
Your airline's boards passengers using 'airports' of the from city and deboards them using the airport of the to city. A passenger may 'travel' to multiple cities, but everywhere they have to go through the airport to travel between your airline's aircraft and the city.
Note that a passenger 'departing' from the city is essentially 'arriving' into your airlines' aircraft. And a passeger 'arriving' into the city, is essentially departing from the aircraft. Since we are in the shoes of airline owner, the term 'arrival passenger' and 'departing passenger' are reversed from our conventional notions which are based on cities perspective.
Same 'airport' infrastructure of each city is used by 'departing' passengers and 'arrival' passengers. An airport provides 'departing infrastructure' for departing passengers, which is different from the 'arrival infrastructure' provided for arriving passengers.
Passengers can continue doing their day to their activities due to various 'amenities' provided inside the aircraft by your airlines, while travelling.
On top of that, your airline also provides lounge facilities for special treatments like 'understanding local language' and or preparing you for the 'travel'.
Lets replace few words/phrases used above with following:
your airline: Apache Camel
aircraft companies: Transport mechanisms
your airline's aircraft: Apache Camel's underlying transport mechanism
carry: route
passengers: message;
city: system;
airport: Camel Component;
understanding local languages: Type Conversions;
departing: producing, produced
arriving: consuming, consumed
travel: routed
amenities: provided
After replacing the words, here is what you get:
Purpose of 'Apache Camel' is to route 'messages' from one 'system' to another one in the world. Apache camel uses different transport mechanisms for message routing.
Apache Camel picks up messages using 'Camel based Component' of the 'from' system and drops them using the 'Camel based Component' of the 'to' system. A message may route to multiple systems, but everywhere they have to go through 'Camel based Components' to travel between 'Apache Camel's underlying transport mechanism' and the system.
Note that a message 'produced' from the system is essentially 'consumed' into Apache Camel's underlying transport mechanism'. And a message consumed by a system, is essentially produced by the 'Apache Camel's underlying transport mechanism'.
Since we are attempting to understand Camel, we must think from Camel's perspective here onwards. The meaning of the terms 'consumer message' and 'producer message' are ,thus, reversed from our conventional notions which are based on a system's perspective.
Same 'Camel based Component's ' coding infrastructure is used by 'producer message' and 'consumer message'. A 'Camel based Component' provides a 'producer endpoint' for 'producer message' and a 'consumer endpoint' for 'consumer message'.
Messages can be processed by Camel when they are being routed.
On top of this routing, Camel provides special features like 'Type Conversion' and many more...
This is only true if you're iterating through an array; what if you were iterating through a different kind of collection that has no notion of accessing by index? In the array case, the easiest way to retain the index is to simply use a vanilla for loop.
On the most part, I'd say follow the pattern. I have deviated from it, but very rarely, and for specific reasons. In the case in point, the biggest issue I'd have is that I'd probably still use an Action<SomeObjectType>
, allowing me to add extra properties later, and to use the occasional 2-way property (think Handled
, or other feedback-events where the subscriber needs to to set a property on the event object). And once you've started down that line, you might as well use EventHandler<T>
for some T
.
You should not use gets
since it has no way to stop a buffer overflow. If the user types in more data than can fit in your buffer, you will most likely end up with corruption or worse.
In fact, ISO have actually taken the step of removing gets
from the C standard (as of C11, though it was deprecated in C99) which, given how highly they rate backward compatibility, should be an indication of how bad that function was.
The correct thing to do is to use the fgets
function with the stdin
file handle since you can limit the characters read from the user.
But this also has its problems such as:
To that end, almost every C coder at some point in their career will write a more useful wrapper around fgets
as well. Here's mine:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
with some test code:
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
printf ("No input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long\n");
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
It provides the same protections as fgets
in that it prevents buffer overflows but it also notifies the caller as to what happened and clears out the excess characters so that they do not affect your next input operation.
Feel free to use it as you wish, I hereby release it under the "do what you damn well want to" licence :-)
I haven't actually tried this, but this answer from the web sounds promising:
Wireshark can't actually capture local packets on windows XP due to the nature of the windows TCP stack. When packets are sent and received on the same machine they don't seem to cross the network boundary that wireshark monitors.
However there is a way around this, you can route the local traffic out via your network gateway (router) by setting up a (temporary) static route on your windows XP machine.
Say your XP IP address is 192.168.0.2 and your gateway (router) address is 192.168.0.1 you could run the following command from windows XP command line to force all local traffic out and back across the network boundary, so wireshark could then track the data (note that wireshark will report packets twice in this scenario, once when they leave your pc and once when they return).
route add 192.168.0.2 mask 255.255.255.255 192.168.0.1 metric 1
http://forums.whirlpool.net.au/archive/1037087, accessed just now.
players
is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:
name, score = player
(if the player
list is always a constant length).
There's not much more advice we can give you without knowing what query
is and how it works.
It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError
on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.
I had the same problem by using library wifi
but when i changed my network it worked perfectly.
Change your network connection
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE
.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES()
function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE
syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
This test shows that the string in VBA can be at least 10^8 characters long. But if you change it to 10^9 you will fail.
Sub TestForStringLengthVBA()
Dim text As String
text = Space(10 ^ 8) & "Hello world"
Debug.Print Len(text)
text = Right(text, 5)
Debug.Print text
End Sub
So do not be mislead by Intermediate window editor or MsgBox output.
You probably don't want to do this:
#include "client.cpp"
A *.cpp file will have been compiled by the compiler as part of your build. By including it in other files, it will be compiled again (and again!) in every file in which you include it.
Now here's the thing: You are guarding it with #ifndef SOCKET_CLIENT_CLASS
, however, each file that has #include "client.cpp"
is built independently and as such will find SOCKET_CLIENT_CLASS
not yet defined. Therefore it's contents will be included, not #ifdef'd out.
If it contains any definitions at all (rather than just declarations) then these definitions will be repeated in every file where it's included.
Try writing the properties as a comma separated list, then split the value after the properties file is loaded. For example
a=one,two,three
b=nine,ten,fourteen
You can also use org.apache.commons.configuration and change the value delimiter using the AbstractConfiguration.setListDelimiter(char) method if you're using comma in your values.
Vector and list aren't conceptually tied to C++. Similar structures can be implemented in C, just the syntax (and error handling) would look different. For example LodePNG implements a dynamic array with functionality very similar to that of std::vector. A sample usage looks like:
uivector v = {};
uivector_push_back(&v, 1);
uivector_push_back(&v, 42);
for(size_t i = 0; i < v.size; ++i)
printf("%d\n", v.data[i]);
uivector_cleanup(&v);
As can be seen the usage is somewhat verbose and the code needs to be duplicated to support different types.
nothings/stb gives a simpler implementation that works with any types, but compiles only in C:
double *v = 0;
sb_push(v, 1.0);
sb_push(v, 42.0);
for(int i = 0; i < sb_count(v); ++i)
printf("%g\n", v[i]);
sb_free(v);
A lot of C code, however, resorts to managing the memory directly with realloc:
void* newMem = realloc(oldMem, newSize);
if(!newMem) {
// handle error
}
oldMem = newMem;
Note that realloc
returns null in case of failure, yet the old memory is still valid. In such situation this common (and incorrect) usage leaks memory:
oldMem = realloc(oldMem, newSize);
if(!oldMem) {
// handle error
}
Compared to std::vector
and the C equivalents from above, the simple realloc
method does not provide O(1) amortized guarantee, even though realloc
may sometimes be more efficient if it happens to avoid moving the memory around.
The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:
File > Preferences > Settings > Encoding > Choose your option
This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.
I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.
import numpy as np
import random
import cv2
def sp_noise(image,prob):
'''
Add salt and pepper noise to image
prob: Probability of the noise
'''
output = np.zeros(image.shape,np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = random.random()
if rdn < prob:
output[i][j] = 0
elif rdn > thres:
output[i][j] = 255
else:
output[i][j] = image[i][j]
return output
image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)
I Have faced the same issue.After a lot of struggle I found that the real issue is with the com.amazonaws dependencies.After adding dependencies this error got disappeared.
>>> class A(object): pass
>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>>
what do you mean by convert into a string? you can define your own repr and str_ methods:
>>> class A(object):
def __repr__(self):
return 'hei, i am A or B or whatever'
>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever
or i dont know..please add explainations ;)
The java.sql.Timestamp class has no format. Its toString method generates a String with a format.
Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.
First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.
Instant instant = mySqlDate.toInstant() ;
Lose the fraction of a second you don't want.
instant = instant.truncatedTo( ChronoUnit.Seconds );
Assign the time zone to adjust from UTC used by Instant.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generate a String close to your desired output. Replace its T
in the middle with a SPACE.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );
This could be a one way of doing it. If you know what line of the file you have your grep word and how many lines you have in your file:
grep -A466 'TERMINATE' file
I suggest using Flexbox:
Be sure to add the proper vendor prefixes though!
form {_x000D_
width: 400px;_x000D_
border: 1px solid black;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
input {_x000D_
flex: 2;_x000D_
}_x000D_
_x000D_
input, label {_x000D_
margin: 5px;_x000D_
}
_x000D_
<form method="post">_x000D_
<label for="myInput">Sample label</label>_x000D_
<input type="text" id="myInput" placeholder="Sample Input"/>_x000D_
</form>
_x000D_
Since I cant comment yet im gonna post as an answer the link.. I have found a simple, well organized tutorial on recyclerview http://www.androiddeft.com/2017/10/01/recyclerview-android/
Apart from that when you are going to add a recycler view into you activity what you want to do is as below and how you should do this has been described on the link
As of Socket.IO 1.0 (May 2014), all connections begin with an HTTP polling request (more info here). That means that in addition to forwarding WebSocket traffic, you need to forward any transport=polling
HTTP requests.
The solution below should redirect all socket traffic correctly, without redirecting any other traffic.
Enable the following Apache2 mods:
sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
Use these settings in your *.conf file (e.g. /etc/apache2/sites-available/mysite.com.conf
). I've included comments to explain each piece:
<VirtualHost *:80>
ServerName www.mydomain.com
# Enable the rewrite engine
# Requires: sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
# In the rules/conds, [NC] means case-insensitve, [P] means proxy
RewriteEngine On
# socket.io 1.0+ starts all connections with an HTTP polling request
RewriteCond %{QUERY_STRING} transport=polling [NC]
RewriteRule /(.*) http://localhost:3001/$1 [P]
# When socket.io wants to initiate a WebSocket connection, it sends an
# "upgrade: websocket" request that should be transferred to ws://
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /(.*) ws://localhost:3001/$1 [P]
# OPTIONAL: Route all HTTP traffic at /node to port 3001
ProxyRequests Off
ProxyPass /node http://localhost:3001
ProxyPassReverse /node http://localhost:3001
</VirtualHost>
I've included an extra section for routing /node
traffic that I find handy, see here for more info.
You can easily write one yourself.
given:
int array[]={1,2};
you do:
int temp=array[0];
array[0]=array[1];
array[1]=temp;
And you're done. 3 lines of code.
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.
Also, I don't think you can use NOW()
as default value in OrderDate. Try to use the following:
OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
Use break
.
Unrelated to your question, I see in your code the line:
Violated = !(name.firstname == null) ? false : true;
In this line, you take a boolean value (name.firstname == null)
. Then, you apply the !
operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null)
. Why not use that, as in:
Violated = (name.firstname == null);
I had the same problem, Eclipse would not start. Found this link and it worked like a charm:
Can't click Menu Bar Items in Eclipse
Java is messed-up on Maverick, need to download and install from here: http://support.apple.com/kb/DL1572?viewlocale=en_US&locale=en_US
There is one fatal flaw in this otherwise great and helpful test: As memset is the first instruction, there seems to be some "memory overhead" or so which makes it extremely slow. Moving the timing of memset to second place and something else to first place or simply timing memset twice makes memset the fastest with all compile switches!!!
Python uses and
and or
conditionals.
i.e.
if foo == 'abc' and bar == 'bac' or zoo == '123':
# do something
The following is an example of how to calculate a future date based on date input (membershipssignup_date) + added months (membershipsmonths) via form fields.
The membershipsmonths field has a default value of 0
Trigger link (can be an onchange event attached to membership term field):
<a href="#" onclick="calculateMshipExp()"; return false;">Calculate Expiry Date</a>
function calculateMshipExp() {
var calcval = null;
var start_date = document.getElementById("membershipssignup_date").value;
var term = document.getElementById("membershipsmonths").value; // Is text value
var set_start = start_date.split('/');
var day = set_start[0];
var month = (set_start[1] - 1); // January is 0 so August (8th month) is 7
var year = set_start[2];
var datetime = new Date(year, month, day);
var newmonth = (month + parseInt(term)); // Must convert term to integer
var newdate = datetime.setMonth(newmonth);
newdate = new Date(newdate);
//alert(newdate);
day = newdate.getDate();
month = newdate.getMonth() + 1;
year = newdate.getFullYear();
// This is British date format. See below for US.
calcval = (((day <= 9) ? "0" + day : day) + "/" + ((month <= 9) ? "0" + month : month) + "/" + year);
// mm/dd/yyyy
calcval = (((month <= 9) ? "0" + month : month) + "/" + ((day <= 9) ? "0" + day : day) + "/" + year);
// Displays the new date in a <span id="memexp">[Date]</span> // Note: Must contain a value to replace eg. [Date]
document.getElementById("memexp").firstChild.data = calcval;
// Stores the new date in a <input type="hidden" id="membershipsexpiry_date" value="" name="membershipsexpiry_date"> for submission to database table
document.getElementById("membershipsexpiry_date").value = calcval;
}
If you actually want a C-style array
import array
a = array.array('i', x * [0])
a[3] = 5
try:
[5] = 'a'
except TypeError:
print('integers only allowed')
Note that there's no concept of un-initialized variable in python. A variable is a name that is bound to a value, so that value must have something. In the example above the array is initialized with zeros.
However, this is uncommon in python, unless you actually need it for low-level stuff. In most cases, you are better-off using an empty list or empty numpy array, as other answers suggest.
Just use axes.get_ylim()
, it is very similar to set_ylim
. From the docs:
get_ylim()
Get the y-axis range [bottom, top]
I recently found out by accident that since you have more control on a ImageView that you can set an onclicklistener for an image here is a sample of a dynamically created image button
private int id;
private bitmap bmp;
LinearLayout.LayoutParams familyimagelayout = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT );
final ImageView familyimage = new ImageView(this);
familyimage.setBackground(null);
familyimage.setImageBitmap(bmp);
familyimage.setScaleType(ImageView.ScaleType.FIT_START);
familyimage.setAdjustViewBounds(true);
familyimage.setId(id);
familyimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//what you want to do put here
}
});
i came across the same thing and i figured out what is the issue. When we use the method input, the response we should type should be in double quotes. Like in your line
date=input("Example: March 21 | What is the date? ")
You should type when prompted on console "12/12/2015" - note the "
thing before and after. This way it will take that as a string and process it as expected. I am not sure if this is limitation of this input
method - but it works this way.
Hope it helps
You can use like that:
data
is DataTable
data.DefaultView.ToTable(true, "Id", "Name", "Role", "DC1", "DC2", "DC3", "DC4", "DC5", "DC6", "DC7");
but performance will be down. try to use below code:
data.AsEnumerable().Distinct(System.Data.DataRowComparer.Default).ToList();
For Performance ; http://onerkaya.blogspot.com/2013/01/distinct-dataviewtotable-vs-linq.html
You can use java.util.Scanner
(API):
import java.util.Scanner;
//...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).
You have to escape [
and ]
.
Try this:
$('.button').click(function(){
var fieldID = $(this).prev().attr("id");
fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1");
$('#' + fieldID).val("hello world");
});
Building further on Aydin's and Todd's answers, here is an extension method that also lets you get the name from a resource file
using AppResources;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Resources;
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enumValue)
{
var enumMember= enumValue.GetType()
.GetMember(enumValue.ToString());
DisplayAttribute displayAttrib = null;
if (enumMember.Any()) {
displayAttrib = enumMember
.First()
.GetCustomAttribute<DisplayAttribute>();
}
string name = null;
Type resource = null;
if (displayAttrib != null)
{
name = displayAttrib.Name;
resource = displayAttrib.ResourceType;
}
return String.IsNullOrEmpty(name) ? enumValue.ToString()
: resource == null ? name
: new ResourceManager(resource).GetString(name);
}
}
and use it like
public enum Season
{
[Display(ResourceType = typeof(Resource), Name = Season_Summer")]
Summer
}
In the specific case of react-router
, using context
is a valid case scenario, e.g.
class MyComponent extends React.Component {
props: PropsType;
static contextTypes = {
router: PropTypes.object
};
render () {
this.context.router;
}
}
You can access an instance of the history via the router context, e.g. this.context.router.history
.
Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.
Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value
However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...
Code:
Cells(1, 3).Copy
Cells(1, 1).PasteSpecial (xlPasteFormats)
Application.CutCopyMode = False
What about:
Dynamically grab the #hash
<script>
var urlhash = window.location.hash, //get the hash from url
txthash = urlhash.replace("#", ""); //remove the #
//alert(txthash);
</script>
<?php
$hash = "<script>document.writeln(txthash);</script>";
echo $hash;
?>
To make it more fluent:
Full Example using just Javascript and PHP
<script>
var urlhash = window.location.hash, //get the hash from url
txthash = urlhash.replace("#", ""); //remove the #
function changehash(a,b){
window.location.hash = b; //add hash to url
//alert(b); //alert to test
location.reload(); //reload page to show the current hash
}
</script>
<?php $hash = "<script>document.writeln(txthash);</script>";?>
<a onclick="changehash(this,'#hash1')" style="text-decoration: underline;cursor: pointer;" >Change to #hash1</a><br/>
<a onclick="changehash(this,'#hash2')" style="text-decoration: underline;cursor: pointer;">Change to #hash2</a><br/>
<?php echo "This is the current hash: " . $hash; ?>
If you simply want to reduce your button image:
yourButton.contentMode = UIViewContentModeScaleAspectFit;
yourButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
For anyone who must work with an older version of MySQL (pre-5.0 ish) you are unable to do sub-queries for this type of query. Here is the solution I was able to do and it seemed to work great.
SELECT MAX(d.id), d2.*, CONCAT(title,' ',forename,' ',surname) AS name
FROM customer AS c
LEFT JOIN customer_data as d ON c.customer_id=d.customer_id
LEFT JOIN customer_data as d2 ON d.id=d2.id
WHERE CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
GROUP BY c.customer_id LIMIT 10, 20;
Essentially this is finding the max id of your data table joining it to the customer then joining the data table to the max id found. The reason for this is because selecting the max of a group doesn't guarantee that the rest of the data matches with the id unless you join it back onto itself.
I haven't tested this on newer versions of MySQL but it works on 4.0.30.
Here's how I managed to fix it on my Kali machine:
Locate to the directory:
cd /etc/nginx/sites-enabled/
Edit the 'default' configuration file:
sudo nano default
Add the following lines in the location
block:
location /yourdirectory {
autoindex on;
autoindex_exact_size off;
}
Note that I have activated auto-indexing in a specific directory
/yourdirectory
only. Otherwise, it will be enabled for all of your folders on your computer and you don't want it.
Now restart your server and it should be working now:
sudo service nginx restart
I agree with Darko Z on applying "overflow: hidden" to #sub-title. However, it should be mentioned that the overflow:hidden method of clearing floats does not work with IE6 unless you have a specified width or height. Or, if you don't want to specify a width or height, you can use "zoom: 1":
#sub-title { overflow:hidden; zoom: 1; }
# Function to sample N lines randomly from a file
# Parameter $1: Name of the original file
# Parameter $2: N lines to be sampled
rand_line_sampler() {
N_t=$(awk '{print $1}' $1 | wc -l) # Number of total lines
N_t_m_d=$(( $N_t - $2 - 1 )) # Number oftotal lines minus desired number of lines
N_d_m_1=$(( $2 - 1)) # Number of desired lines minus 1
# vector to have the 0 (fail) with size of N_t_m_d
echo '0' > vector_0.temp
for i in $(seq 1 1 $N_t_m_d); do
echo "0" >> vector_0.temp
done
# vector to have the 1 (success) with size of desired number of lines
echo '1' > vector_1.temp
for i in $(seq 1 1 $N_d_m_1); do
echo "1" >> vector_1.temp
done
cat vector_1.temp vector_0.temp | shuf > rand_vector.temp
paste -d" " rand_vector.temp $1 |
awk '$1 != 0 {$1=""; print}' |
sed 's/^ *//' > sampled_file.txt # file with the sampled lines
rm vector_0.temp vector_1.temp rand_vector.temp
}
rand_line_sampler "parameter_1" "parameter_2"
First, get the date in UTC -- you've already done that so this step would really just be a database call:
$timezone = "UTC";
date_default_timezone_set($timezone);
$utc = gmdate("M d Y h:i:s A");
print "UTC: " . date('r', strtotime($utc)) . "\n";
Next, set your local time zone in PHP:
$timezone = "America/Guayaquil";
date_default_timezone_set($timezone);
And now get the offset in seconds:
$offset = date('Z', strtotime($utc));
print "offset: $offset \n";
Finally, add the offset to the integer timestamp of your original datetime:
print "LOCAL: " . date('r', strtotime($utc) + $offset) . "\n";
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
Its Working Properly
EditText et_mobile= (EditText) findViewById(R.id.edittxt);
et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
if (et_mobile.getText().toString().trim().length() == 0) {
CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
}
}
}
});
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
This can be possible in three steps:
@Autowired
can be used with setters so you could have a setter modifying an static field.
Just one final suggestion... DON'T
Try:
if (_checkbox.addEventListener) {
_checkbox.addEventListener("click", setCheckedValues, false);
}
else {
_checkbox.attachEvent("onclick", setCheckedValues);
}
Update:: For Internet Explorer versions prior to IE9, attachEvent method should be used to register the specified listener to the EventTarget it is called on, for others addEventListener should be used.
Given that I just lost a day trying to figure this out and actually found a solution with the help of a coworker, I thought I should chime in.
We have a large code base and we have to deal with 2 branch heavily being modified at the same time. There is a main branch and a secondary branch if you which.
While I merge the secondary branch into the main branch, work continues in the main branch and by the time i'm done, I can't push my changes because they are incompatible.
I therefore need to "rebase" my "merge".
This is how we finally did it :
1) make note of the SHA. ex.: c4a924d458ea0629c0d694f1b9e9576a3ecf506b
git log -1
2) Create the proper history but this will break the merge.
git rebase -s ours --preserve-merges origin/master
3) make note of the SHA. ex.: 29dd8101d78
git log -1
4) Now reset to where you were before
git reset c4a924d458ea0629c0d694f1b9e9576a3ecf506b --hard
5) Now merge the current master into your working branch
git merge origin/master
git mergetool
git commit -m"correct files
6) Now that you have the right files, but the wrong history, get the right history on top of your change with :
git reset 29dd8101d78 --soft
7) And then --amend the results in your original merge commit
git commit --amend
Voila!
all above fix may not work in android studio .if you are using ANDROID STUDIO...... use this fix
add
xmlns:compat="http://schemas.android.com/tools"
in menu tag instead of
xmlns:compat="http://schemas.android.com/apk/res-auto"
in menu tag.
You don't need to create a new datafile; you can extend your existing tablespace data files.
Execute the following to determine the filename for the existing tablespace:
SELECT * FROM DBA_DATA_FILES;
Then extend the size of the datafile as follows (replace the filename with the one from the previous query):
ALTER DATABASE DATAFILE 'D:\ORACLEXE\ORADATA\XE\SYSTEM.DBF' RESIZE 2048M;
It's actually fairly easy to set the underline color of an EditText programmatically (just one line of code).
To set the color:
editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
To remove the color:
editText.getBackground().clearColorFilter();
Note: when the EditText has focus on, the color you set won't take effect, instead, it has a focus color.
API Reference:
I created the following extension methods based on the answer from rdev5. Pinning the managed string is important as it prevents the garbage collector from moving it around and leaving behind copies that you're unable to erase.
I think the advantage of my solution has is that no unsafe code is needed.
/// <summary>
/// Allows a decrypted secure string to be used whilst minimising the exposure of the
/// unencrypted string.
/// </summary>
/// <typeparam name="T">Generic type returned by Func delegate.</typeparam>
/// <param name="secureString">The string to decrypt.</param>
/// <param name="action">
/// Func delegate which will receive the decrypted password as a string object
/// </param>
/// <returns>Result of Func delegate</returns>
/// <remarks>
/// This method creates an empty managed string and pins it so that the garbage collector
/// cannot move it around and create copies. An unmanaged copy of the the secure string is
/// then created and copied into the managed string. The action is then called using the
/// managed string. Both the managed and unmanaged strings are then zeroed to erase their
/// contents. The managed string is unpinned so that the garbage collector can resume normal
/// behaviour and the unmanaged string is freed.
/// </remarks>
public static T UseDecryptedSecureString<T>(this SecureString secureString, Func<string, T> action)
{
int length = secureString.Length;
IntPtr sourceStringPointer = IntPtr.Zero;
// Create an empty string of the correct size and pin it so that the GC can't move it around.
string insecureString = new string('\0', length);
var insecureStringHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);
IntPtr insecureStringPointer = insecureStringHandler.AddrOfPinnedObject();
try
{
// Create an unmanaged copy of the secure string.
sourceStringPointer = Marshal.SecureStringToBSTR(secureString);
// Use the pointers to copy from the unmanaged to managed string.
for (int i = 0; i < secureString.Length; i++)
{
short unicodeChar = Marshal.ReadInt16(sourceStringPointer, i * 2);
Marshal.WriteInt16(insecureStringPointer, i * 2, unicodeChar);
}
return action(insecureString);
}
finally
{
// Zero the managed string so that the string is erased. Then unpin it to allow the
// GC to take over.
Marshal.Copy(new byte[length], 0, insecureStringPointer, length);
insecureStringHandler.Free();
// Zero and free the unmanaged string.
Marshal.ZeroFreeBSTR(sourceStringPointer);
}
}
/// <summary>
/// Allows a decrypted secure string to be used whilst minimising the exposure of the
/// unencrypted string.
/// </summary>
/// <param name="secureString">The string to decrypt.</param>
/// <param name="action">
/// Func delegate which will receive the decrypted password as a string object
/// </param>
/// <returns>Result of Func delegate</returns>
/// <remarks>
/// This method creates an empty managed string and pins it so that the garbage collector
/// cannot move it around and create copies. An unmanaged copy of the the secure string is
/// then created and copied into the managed string. The action is then called using the
/// managed string. Both the managed and unmanaged strings are then zeroed to erase their
/// contents. The managed string is unpinned so that the garbage collector can resume normal
/// behaviour and the unmanaged string is freed.
/// </remarks>
public static void UseDecryptedSecureString(this SecureString secureString, Action<string> action)
{
UseDecryptedSecureString(secureString, (s) =>
{
action(s);
return 0;
});
}
Test the existence of variavle MyVariable. Returns boolean true or false.
Test-Path variable:\MyVariable
Here's an example that only uses a Left join and I believe is more efficient than any group by method out there: ExchangeCore Blog
SELECT t1.*
FROM TrainTable t1 LEFT JOIN TrainTable t2
ON (t1.Train = t2.Train AND t1.Time < t2.Time)
WHERE t2.Time IS NULL;
For API 11 and later, can use seekbar's XML attributes(android:rotation="270") for vertical effect.
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rotation="270"/>
For older API level (ex API10), only use Selva's answer:
https://github.com/AndroSelva/Vertical-SeekBar-Android
In @dudusan's example, you could also reverse the order of I1, and then sort ascending:
> rum <- read.table(textConnection("P1 P2 P3 T1 T2 T3 I1 I2
+ 2 3 5 52 43 61 6 b
+ 6 4 3 72 NA 59 1 a
+ 1 5 6 55 48 60 6 f
+ 2 4 4 65 64 58 2 b
+ 1 5 6 55 48 60 6 c"), header = TRUE)
> f=factor(rum$I1)
> levels(f) <- sort(levels(f), decreasing = TRUE)
> rum[order(as.character(f), rum$I2), ]
P1 P2 P3 T1 T2 T3 I1 I2
1 2 3 5 52 43 61 6 b
5 1 5 6 55 48 60 6 c
3 1 5 6 55 48 60 6 f
4 2 4 4 65 64 58 2 b
2 6 4 3 72 NA 59 1 a
>
This seems a bit shorter, you don't reverse the order of I2 twice.
this is a basic step for learn:
import os, stat, sys
import time
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'
listdir = os.listdir(dirpath)
for i in listdir:
os.chdir(dirpath)
data_001 = os.path.realpath(i)
listdir_stat1 = os.stat(data_001)
listdir_stat2 = ((os.stat(data_001), data_001))
print time.ctime(listdir_stat1.st_ctime), data_001
In iOS9 Apple finally introduced the possibility to register your app to handle certain http://
URLs: Universal Links.
A very rough explanation of how it works:
http://
URLs for certain domains (web urls) in your app.http://
URLs for a setup as explained above and opens the correct app automatically if installed; without going through Safari first...This is the cleanest way to do deep linking on iOS, unfortunately it works only in iOS9 and newer...
In newer versions of MySQL connectors the default tables are also listed if catalog is not passed
DatabaseMetaData dbMeta = con.getMetaData();
//con.getCatalog() returns database name
ResultSet rs = dbMeta.getTables(con.getCatalog(), "", null, new String[]{"TABLE"});
ArrayList<String> tables = new ArrayList<String>();
while(rs.next()){
String tableName = rs.getString("TABLE_NAME");
tables.add(tableName);
}
return tables;
Size ratio according to iPhone size :
Here's what you can do to have different width and height for cell's regarding the iPhone size :
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = (self.view.frame.size.width - 12 * 3) / 3 //some width
let height = width * 1.5 //ratio
return CGSize(width: width, height: height)
}
And maybe you should also disable your AutoLayout constraints on cell for this answer to work.
Use an extension method:
public static List<string> ColumnList(this IDataReader dataReader)
{
var columns = new List<string>();
for (int i = 0; i < dataReader.FieldCount; i++)
{
columns.Add(dataReader.GetName(i));
}
return columns;
}
it could be a problem with your specific network adapter. I have a Dell 15R and there are no working drivers for ubuntu or ubuntu server; I even tried compiling wireless drivers myself, but to no avail.
However, in virtualbox, I was able to get wireless working by using the default configuration. It automatically bridged my internal wireless adapter and hence used my native OS's wireless connection for wireless.
If you are trying to get a separate wireless connection from within ubuntu in virtualbox, then it would take more configuring. If so, let me know, if not, I will not bother typing up instructions to something you are not looking to do, as it is quite complicated in some instances.
p.s. you should be using Windows 7 if you have any technical inclination. Do you live under a rock? No offense intended.
Assuming that Test is a class with a defined constructor, there's no difference. The latter form makes it a little clearer that Test's constructor is running, but that's about it.
This introduces a new paradigm to HTML/CSS, but using an <input readonly="true">
would allow you to append an input:focus
selector to then alter the background-image
This of course would require applying specific CSS to the input
itself to override browser defaults but it does go to show that click actions can indeed be triggered without the use of Javascript.
You are close, but the parameter you pass to SecureStringToBSTR
must be a SecureString
. You appear to be passing the result of ConvertFrom-SecureString
, which is an encrypted standard string. So call ConvertTo-SecureString
on this before passing to SecureStringToBSTR
.
$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Use of sort
can result in warning message. See github discussion.
So you might wanna use sort_values
, docs here
Then your code can look like this:
df = df.sort_values(by=['c1','c2'], ascending=[False,True])
Overriding only onTouchEvent
and onInterceptTouchEvent
is not sufficient in case you have ViewPager itself inside another ViewPager. Child ViewPager would steal horizontal scroll touch events from parent ViewPager unless it is positioned on its first / last page.
To make this setup work properly you need to override also the canScrollHorizontally
method.
See LockableViewPager
implementation below.
public class LockableViewPager extends ViewPager {
private boolean swipeLocked;
public LockableViewPager(Context context) {
super(context);
}
public LockableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public boolean getSwipeLocked() {
return swipeLocked;
}
public void setSwipeLocked(boolean swipeLocked) {
this.swipeLocked = swipeLocked;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return !swipeLocked && super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return !swipeLocked && super.onInterceptTouchEvent(event);
}
@Override
public boolean canScrollHorizontally(int direction) {
return !swipeLocked && super.canScrollHorizontally(direction);
}
}
To simply combine them you can place them all together like this:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"_AB","_"),"_CD","_"),"_EF","_"),"_40K",""),"_60K",""),"_S_","_"),"_","-")
(note that this may pass the older Excel limit of 7 nested statements. I'm testing in Excel 2010
Another way to do it is by utilizing Left
and Right
functions.
This assumes that the changing data on the end is always present and is 8 characters long
=SUBSTITUTE(LEFT(A2,LEN(A2)-8),"_","-")
This will achieve the same resulting string
If the string doesn't always end with 8 characters that you want to strip off you can search for the "_S" and get the current location. Try this:
=SUBSTITUTE(LEFT(A2,FIND("_S",A2,1)),"_","-")
A bit of improvement on nickf's function for those that don't know the type of the variable coming in:
function dump(v) {
switch (typeof v) {
case "object":
for (var i in v) {
console.log(i+":"+v[i]);
}
break;
default: //number, string, boolean, null, undefined
console.log(typeof v+":"+v);
break;
}
}
Upgrading from 2.2.x to 3.0.x -- reason post method fails. If you are upgrading CI 3.x, need to keep the index_page in config file. Also check the .htaccess file for mod_rewrite. CI_3.x
$config['index_page'] = ''; // ci 2.x
$config['index_page'] = 'index.php'; // ci 3.x
My .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>
I would do it this way:
(function($) {
jQuery.fn.doSomething = function() {
return this.each(function() {
var $this = $(this);
$this.click(function(event) {
event.preventDefault();
// Your function goes here
});
});
};
})(jQuery);
Then on document ready you can do stuff like this:
$(document).ready(function() {
$('#div1').doSomething();
$('#div2').doSomething();
});
Just an update for Mysqli users :
$base= mysqli_connect($dbhost, $dbuser, $dbpass, $dbbase);
if (mysqli_connect_errno())
die('Could not connect: ' . mysql_error());
$return_arr = array();
if ($result = mysqli_query( $base, $sql )){
while ($row = mysqli_fetch_assoc($result)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
}
mysqli_close($base);
echo json_encode($return_arr);
values() method may simply work:
for (Direction d : Direction.values()) {
//whatever you want to do with each of these enum values
}
Use this library org.java_websocket
First thing you should import that library in build.gradle
repositories {
mavenCentral()
}
then add the implementation in dependency{}
implementation "org.java-websocket:Java-WebSocket:1.3.0"
Then you can use this code
In your activity declare object for Websocketclient like
private WebSocketClient mWebSocketClient;
then add this method for callback
private void ConnectToWebSocket() {
URI uri;
try {
uri = new URI("ws://your web socket url");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView)findViewById(R.id.edittext_chatbox);
textView.setText(textView.getText() + "\n" + message);
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
Here is the simple code snippet to upload a single file with additional parameters using requests:
url = 'https://<file_upload_url>'
fp = '/Users/jainik/Desktop/data.csv'
files = {'file': open(fp, 'rb')}
payload = {'file_id': '1234'}
response = requests.put(url, files=files, data=payload, verify=False)
Please note that you don't need to explicitly specify any content type.
NOTE: Wanted to comment on one of the above answers but could not because of low reputation so drafted a new response here.
I think you're asking how to compute the mean of a variable in a data frame, given the name of the column. There are two typical approaches to doing this, one indexing with [[
and the other indexing with [
:
data(iris)
mean(iris[["Petal.Length"]])
# [1] 3.758
mean(iris[,"Petal.Length"])
# [1] 3.758
mean(iris[["Sepal.Width"]])
# [1] 3.057333
mean(iris[,"Sepal.Width"])
# [1] 3.057333
The correct answer is the following:
if [[ -n $var ]] ; then
blah
fi
Note the use of the [[...]]
, which correctly handles quoting the variables for you.
If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.
If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:
Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);
t.Start();
with ThreadProc being a delegate of type ThreadStart.
I've tried both these and still get failure due to conflicts. At the end of my patience, I cloned master in another location, copied everything into the other branch and committed it. which let me continue. The "-X theirs" option should have done this for me, but it did not.
git merge -s recursive -X theirs master
error: 'merge' is not possible because you have unmerged files. hint: Fix them up in the work tree, hint: and then use 'git add/rm ' as hint: appropriate to mark resolution and make a commit, hint: or use 'git commit -a'. fatal: Exiting because of an unresolved conflict.
classname.getResourceAsStream() loads a file via the classloader of classname. If the class came from a jar file, that is where the resource will be loaded from.
FileInputStream is used to read a file from the filesystem.
A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:
public interface Predicate<ARGTYPE>
{
public boolean evaluate(ARGTYPE arg);
}
And then you might have an implementation such as:
public class Tautology<E> implements Predicate<E>
{
public boolean evaluate(E arg){
return true;
}
}
To get a better conceptual understanding, you might want to read about first-order logic.
Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.
Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true
to a function instead of defining a named Tautology subclass like the above.
Exporting each variable from your variables file. Then importing them with * as in your other file and exporting the as a constant from that file will give you a dynamic object with the named exports from the first file being attributes on the object exported from the second.
Variables.js
export const var1 = 'first';
export const var2 = 'second':
...
export const varN = 'nth';
Other.js
import * as vars from './Variables';
export const Variables = vars;
Third.js
import { Variables } from './Other';
Variables.var2 === 'second'
scp -i /home/<user>/.ssh/id_rsa -o "StrictHostKeyChecking=no" -rp /source/directory/path/[!.]* <target_user>@<target_system:/destination/directory/path
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = @"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());
I was facing same issue, used below query to resolve it.
While creating DB you can use utf-8 encoding
eg. create database my_db character set utf8 collate utf8mb4;
EDIT: (Considering suggestions from comments) Changed utf8_bin to utf8mb4
I use the following code which seems to be working fine:
function _bot_detected() {
return (
isset($_SERVER['HTTP_USER_AGENT'])
&& preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT'])
);
}
update 16-06-2017 https://support.google.com/webmasters/answer/1061943?hl=en
added mediapartners
I have a proper solution of this problem, lets try and understand the root cause of this issue. This issue comes when remote servers ssl cannot be verified using root certificates in your system's certificate store or remote ssl is not installed along with chain certificates. If you have a linux system with root ssh access, then in this case you can try updating your certificate store with below command:
update-ca-certificates
If still, it doesn't work then you need to add root and interim certificate of remote server in your cert store. You can download root and intermediate certs and add them in /usr/local/share/ca-certificates directory and then run command update-ca-certificates
. This should do the trick. Similarly for windows you can search how to add root and intermediate cert.
The other way you can solve this problem is by asking remote server team to add ssl certificate as a bundle of domain root cert, intermediate cert and root cert.
Indexes of two types can be added: when you define a primary key, MySQL will take it as index by default.
Explanation
Primary key as index
Consider you have a tbl_student
table and you want student_id
as primary key:
ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)
Above statement adds a primary key, which means that indexed values must be unique and cannot be NULL.
Specify index name
ALTER TABLE `tbl_student` ADD INDEX student_index (`student_id`)
Above statement will create an ordinary index with student_index
name.
Create unique index
ALTER TABLE `tbl_student` ADD UNIQUE student_unique_index (`student_id`)
Here, student_unique_index
is the index name assigned to student_id and creates an index for which values must be unique (here null can be accepted).
Fulltext option
ALTER TABLE `tbl_student` ADD FULLTEXT student_fulltext_index (`student_id`)
Above statement will create the Fulltext index name with student_fulltext_index
, for which you need MyISAM Mysql Engine.
How to remove indexes ?
DROP INDEX `student_index` ON `tbl_student`
How to check available indexes?
SHOW INDEX FROM `tbl_student`
Try: $(date +%F)
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
Try also the old syntax for casting,
SELECT ROUND(AVG(some_column)::numeric,2)
FROM table;
works with any version of PostgreSQL.
There are a lack of overloads in some PostgreSQL functions, why (???): I think "it is a lack" (!), but @CraigRinger, @Catcall and the PostgreSQL team agree about "pg's historic rationale".
PS: another point about rounding is accuracy, check @IanKenney's answer.
You can overload the ROUND function with,
CREATE FUNCTION ROUND(float,int) RETURNS NUMERIC AS $$
SELECT ROUND($1::numeric,$2);
$$ language SQL IMMUTABLE;
Now your instruction will works fine, try (after function creation)
SELECT round(1/3.,4); -- 0.3333 numeric
but it returns a NUMERIC type... To preserve the first commom-usage overload, we can return a FLOAT type when a TEXT parameter is offered,
CREATE FUNCTION ROUND(float, text, int DEFAULT 0)
RETURNS FLOAT AS $$
SELECT CASE WHEN $2='dec'
THEN ROUND($1::numeric,$3)::float
-- ... WHEN $2='hex' THEN ... WHEN $2='bin' THEN... complete!
ELSE 'NaN'::float -- like an error message
END;
$$ language SQL IMMUTABLE;
Try
SELECT round(1/3.,'dec',4); -- 0.3333 float!
SELECT round(2.8+1/3.,'dec',1); -- 3.1 float!
SELECT round(2.8+1/3.,'dec'::text); -- need to cast string? pg bug
PS: checking \df round
after overloadings, will show something like,
Schema | Name | Result data type | Argument data types ------------+-------+------------------+---------------------------- myschema | round | double precision | double precision, text, int myschema | round | numeric | double precision, int pg_catalog | round | double precision | double precision pg_catalog | round | numeric | numeric pg_catalog | round | numeric | numeric, int
The pg_catalog
functions are the default ones, see manual of build-in math functions.
If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
To start the shell-script 'file.sh':
sh file.sh
bash file.sh
Another option is set executable permission using chmod command:
chmod +x file.sh
Now run .sh file as follows:
./file.sh
You can set an background image without any code!
Just press the button you want an image to in Main.storyboard, then, in the utilities bar to the right, press the attributes inspector and set the background to the image you want! Make sure you have the picture you want in the supporting files to the left.
I only use var when it's clear to see what type is used.
For example, I would use var in this case, because you can see immediately that x will be of the type "MyClass":
var x = new MyClass();
I would NOT use var in cases like this, because you have to drag the mouse over the code and look at the tooltip to see what type MyFunction returns:
var x = MyClass.MyFunction();
Especially, I never use var in cases where the right side is not even a method, but only a value:
var x = 5;
(because the compiler can't know if I want a byte, short, int or whatever)
If your looking how to copy an Amazon AWS .pem
keypair into a different
region do the following:
openssl rsa -in .ssh/amazon-aws.pem -pubout > .ssh/amazon-aws.pub
Then
aws ec2 import-key-pair --key-name amazon-aws --public-key-material '$(cat .ssh/amazon-aws.pub)' --region us-west-2
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.
If you use jQuery (hence not jqLite) in conjunction with AngularJS you can iterate with $.each - which allows breaking and continuing based on boolean return value expression.
JSFiddle:
Javascript:
var array = ['foo', 'bar', 'yay'];
$.each(array, function(index, element){
if (element === 'foo') {
return true; // continue
}
console.log(this);
if (element === 'bar') {
return false; // break
}
});
Note:
Though using jQuery is not bad, both native Array.some or Array.every functions are recommended by MDN as you can read at native forEach documentation:
"There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some"
Following examples are provided by MDN:
Array.some:
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true
Array.every:
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
Make sure that you do NOT have a JRE path, if you have delete it.
JAVA_HOME
in the System variable. Variable value: C:\Program Files\Java\jdk-10.0.2
(location of JDK without bin)M2
in the System variable. Variable value: C:\dev\maven\apache-maven-3.5.4\bin
(location of maven with bin)M2_HOME
in the System variable. Variable value: C:\dev\maven\apache-maven-3.5.4
(location of maven without bin)%JAVA_HOME%
and %M2%
in Path System Variable or C:\Program Files\Java\jdk-10.0.2
and C:\dev\maven\apache-maven-3.5.4\bin
--> For windows 10, just add the location. For other version, at the end of the Variable Value field add semicolon then the location Ex: ;%JAVA_HOME%;%M2%
I did not check if the addition or removal of bin changes the result but nonetheless this works for me.
Below code will be helpful for you
public static IUnityContainer Initialise(IUnityContainer container = null)
{
if (container == null)
{
container = new UnityContainer();
}
container.RegisterType<ISettingsManager, SettingsManager>();
container.Resolve<SettingsManager>();
container.RegisterType<SettingsManagerController>(new InjectionProperty("_SettingManagerProvider", new ResolvedParameter<ISettingManager>()));
return container;
}
'-replace' does a regex search and you have special characters in that last one (like +) So you might use the non-regex replace version like this:
$c = $c.replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==')
If you like doing it using ruby:
ruby -e "`gem list`.split(/$/).each { |line| puts `gem uninstall -Iax #{line.split(' ')[0]}` unless line.strip.empty? }"
Cheers
If you used adb root
, you would have got the following message:
C:\>adb root
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
restarting adbd as root
To get out of the root mode, you can use:
C:\>adb unroot
restarting adbd as non root
If you're open to out-of-the-DB solution: You could set up a cron job that runs a script that will itself call the procedure.
Extending @Valeh Hajiyev great and clear answer for mysqli
driver tests:
Debug your database connection using this script at the end of ./config/database.php:
/* Your db config here */
$db['default'] = array(
// ...
'dbdriver' => 'mysqli',
// ...
);
/* Connection test: */
echo '<pre>';
print_r($db['default']);
echo '</pre>';
echo 'Connecting to database: ' .$db['default']['database'];
$mysqli_connection = new MySQLi($db['default']['hostname'],
$db['default']['username'],
$db['default']['password'],
$db['default']['database']);
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else {
echo "Connected.";
}
die( 'file: ' .__FILE__ . ' Line: ' .__LINE__);
By postfixing the URL with ?WSDL
If the URL is for example:
http://webservice.example:1234/foo
You use:
http://webservice.example:1234/foo?WSDL
And the wsdl will be delivered.
There are a couple of things that need to be adjusted in your layout:
You are nesting col
elements within form-group
elements. This should be the other way around (the form-group
should be within the col-sm-xx
element).
You should always use a row
div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12
is still on the same row with the above 3 .col-sm-4
resulting in a total of columns greater than 12, and causing the overlap problem.
Here is a fixed demo.
And an excerpt of what the problematic section HTML should become:
<fieldset>
<legend>Personal Information</legend>
<div class='row'>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_title">Title</label>
<input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_firstname">First name</label>
<input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_lastname">Last name</label>
<input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
</div>
</div>
</div>
<div class='row'>
<div class='col-sm-12'>
<div class='form-group'>
<label for="user_email">Email</label>
<input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
</div>
</div>
</div>
</fieldset>
I came across this, tot it would be nice to share...
What do you guys think?
$(document).ready(function() {
window.mousemove = function(e) {
p = $(e).position(); //remember $(e) - could be any html tag also..
left = e.left; //retrieving the left position of the div...
top = e.top; //get the top position of the div...
}
});
and boom, there we have it..
In ASP.NET Core Razor Pages, you can combine C# and HTML in the function:
@model PagerModel
@{
}
@functions
{
void PagerNumber(int pageNumber, int currentPage)
{
if (pageNumber == currentPage)
{
<span class="page-number-current">@pageNumber</span>
}
else
{
<a class="page-number-other" href="/table/@pageNumber">@pageNumber</a>
}
}
}
<p>@PagerNumber(1,2) @PagerNumber(2,2) @PagerNumber(3,2)</p>
I've required this functionality several times for debugging/analyzing code from others.
For this, I've written a Perl script which generates a class with several overloaded toString
methods. Each toString
method takes an Enum
as an argument and returns const char*
.
Of course, the script doesn't parse C++ for enums itself, but uses ctags for generating symbol table.
The Perl script is here: http://heinitz-it.de/download/enum2string/enum2string.pl.html
You can also use the following code :
package com.agileinfotech.bsviewer.ldap;
import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPLoginAuthentication {
public LDAPLoginAuthentication() {
// TODO Auto-generated constructor
}
ResourceBundle resBundle = ResourceBundle.getBundle("settings");
@SuppressWarnings("unchecked")
public String authenticateUser(String username, String password) {
String strUrl = "success";
Hashtable env = new Hashtable(11);
boolean b = false;
String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Close the context when we're done
b = true;
ctx.close();
} catch (NamingException e) {
b = false;
} finally {
if (b) {
strUrl = "success";
} else {
strUrl = "failer";
}
}
return strUrl;
}
}
See if you like the image resizing quality of this open source ASP.NET module. There's a live demo, so you can mess around with it yourself. It yields results that are (to me) impossible to distinguish from Photoshop output. It also has similar file sizes - MS did a good job on their JPEG encoder.
To open a file or directory use the command:
code /path/to/file/or/directory/you/want/to/open
For macOS users, it needs to be installed manually:
Command + Shift + P
to open the Command Palette.shell command
, to find the Shell Command: Install 'code' command in PATH
and select to install it.Inside of VBS you can access parameters with
Wscript.Arguments(0)
Wscript.Arguments(1)
and so on. The number of parameter:
Wscript.Arguments.Count
I wrote an npm package called 'html-form-enhancer'. By dropping it into your HTML source, it takes over submission of forms with methods aside from GET
and POST
, and also adds application/json
serialization.
<script type=module" src="html-form-enhancer.js"></script>
<form method="PUT">
...
</form>
Other workarounds include using SELECT DISTINCT or LIMIT in the subquery, although these are not as explicit in their effect on materialization. this worked for me
The total used / free memory of a program can be obtained in the program via
java.lang.Runtime.getRuntime();
The runtime has several methods which relate to the memory. The following coding example demonstrates its usage.
public class PerformanceTest {
private static final long MEGABYTE = 1024L * 1024L;
public static long bytesToMegabytes(long bytes) {
return bytes / MEGABYTE;
}
public static void main(String[] args) {
// I assume you will know how to create an object Person yourself...
List <Person> list = new ArrayList <Person> ();
for (int i = 0; i <= 100_000; i++) {
list.add(new Person("Jim", "Knopf"));
}
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory is bytes: " + memory);
System.out.println("Used memory is megabytes: " + bytesToMegabytes(memory));
}
}
There is apex_util.string_to_table
- see my answer to this question.
Also, prior to the existence of the above function, I once posted a solution here on my blog.
In later versions of APEX, apex_util.string_to_table
is deprecated, and a similar function apex_string.split is preferred.
ul {_x000D_
display: table;_x000D_
margin: 0 auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<ul>_x000D_
<li>56456456</li>_x000D_
<li>4564564564564649999999999999999999999999999996</li>_x000D_
<li>45645</li>_x000D_
</ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
As per the documentation provided by PHP manual.
On each iteration, the value of the current element is assigned to $v and the internal
array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).
So as per your first example:
$array = ['foo'=>1];
foreach($array as $k=>&$v)
{
$array['bar']=2;
echo($v);
}
$array
have only single element, so as per the foreach execution, 1 assign to $v
and it don't have any other element to move pointer
But in your second example:
$array = ['foo'=>1, 'bar'=>2];
foreach($array as $k=>&$v)
{
$array['baz']=3;
echo($v);
}
$array
have two element, so now $array evaluate the zero indices and move the pointer by one. For first iteration of loop, added $array['baz']=3;
as pass by reference.
You can use codecs.
import codecs
with open("test.txt",'r') as filehandle:
content = filehandle.read()
if content[:3] == codecs.BOM_UTF8:
content = content[3:]
print content.decode("utf-8")
Simply put a file named favicon.ico
in the webroot.
If you want to know more, please start reading:
in rare cases when you can't use strncat
, strcat
or strcpy
. And you don't have access to <string.h>
so you can't use strlen
. Also you maybe don't even know the size of the char arrays and you still want to concatenate because you got only pointers. Well, you can do old school malloc and count characters yourself like..
char *combineStrings(char* inputA, char* inputB) {
size_t len = 0, lenB = 0;
while(inputA[len] != '\0') len++;
while(inputB[lenB] != '\0') lenB++;
char* output = malloc(len+lenB);
sprintf((char*)output,"%s%s",inputA,inputB);
return output;
}
It just needs #include <stdio.h>
which you will have most likely included already
Throwing in another answer: Try checking your PYTHONPATH
.
First, try to install wheel
again:
pip install wheel
This should tell you where wheel is installed, eg:
Requirement already satisfied: wheel in /usr/local/lib/python3.5/dist-packages
Then add the location of wheel to your PYTHONPATH
:
export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python3.5/dist-packages/wheel
Now building a wheel should work fine.
python setup.py bdist_wheel
Off the top of my head you could do this with a ScrollView. Your top-level container could be a flex container, inside that have a ScrollView at the top and your footer at the bottom. Then inside the ScrollView just put the rest of your app as normal.
Always you can do it manually. Those are the steps:
git clone github_url
node_modules
folder for e.g. node_modules/browser-sync
Now it should work for you. To be sure it will not break in the future when you do npm i
, continue the upcoming two steps:
package.json
file in it's folder.package.json
and set the same version for where it's appear in the dependencies
part of your package.json
While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.
you need to make county_ID
as index for the right frame:
frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
on=[ 'countyid' ], how='left' )
for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.
so you need to verify integrity before joining by , verify_integrity=True
The main difference between the two is where it is stored and how it is accessed.
$.fn.attr
stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.
$.fn.data
stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user
which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.
Data set with attr()
$(element).attr('data-name')
element.getAttribute('data-name')
,data-name
also accessible from $(element).data(name)
and element.dataset['name']
and element.dataset.name
Data set with .data()
.data(name)
.attr()
or anywhere elseYes its possible.
Return a RedirectToAction()
method like this:
return RedirectToAction("ActionOrViewName", "ControllerName");
Since .NET 4.7.1, you can use the side-effect free Prepend()
and Append()
. The output is going to be an IEnumerable.
// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };
// Prepend and Append any value of the same type
var results = ti.Prepend(0).Append(4);
// output is 0, 1, 2, 3, 4
Console.WriteLine(string.Join(", ", results ));
string
is a string, and string[]
is an array of strings
\usepackage{array}
in the preamble
then this:
\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}
note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"