Slightly off topic, but for those of you that want to modify the built-in colors of the Dark/Light themes you can use this little tool I wrote for Visual Studio 2012.
More info here:
I believe it needs to be done in a single query batch. Basically, the GO statements are breaking your commands into multiple batches and that is causing the issue. Change it to this:
SET IDENTITY_INSERT tbl_content ON
/* GO */
...insert command...
SET IDENTITY_INSERT tbl_content OFF
GO
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
Here is a complete AsyncTask
class
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
@Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
To Call this AsyncTask
class
new GetMethodDemo().execute("your web-service url");
The best way to catch the position is by FindIndex
This function is available only for List<>
Example
int id = listMyObject.FindIndex(x => x.Id == 15);
If you have enumerator or array use this way
int id = myEnumerator.ToList().FindIndex(x => x.Id == 15);
or
int id = myArray.ToList().FindIndex(x => x.Id == 15);
You can mark properties with readonly
modifier in your declaration:
export class MyClass {
public static readonly MY_PUBLIC_CONSTANT = 10;
private static readonly myPrivateConstant = 5;
}
For Eclipse version 4.3.0.v20130605-2000. You can use the Java (default) perspective. In this perspective, it provides the Package Explorer view.
To use the Java (default) perspective: Window -> Open Perspective -> Other... -> Java (default) -> Ok
If you already use the Java (default) perspective but accidentally close the Package Explorer view, you can open it by; Window -> Show View -> Package Explorer (Alt+Shift+Q,P)
If the Package Explorer still doesn't appear in the Java (default) perspective, I suggest you to right-click on the Java (default) perspective button that is located in the top-right of the Eclipse IDE and then select Reset. The Java (default) perspective will show the Package Explorer view, Code pane, Outline view, Problems, JavaDoc and Declaration View.
Since unpaidMembers
is a dictionary it always returns two values when called with .items()
- (key, value). You may want to keep your data as a list of tuples [(name, email, lastname), (name, email, lastname)..]
.
It's not possible to do directly in JavaScript. You'll need to embed a short WAV file in the HTML, and then play that via code.
An Example:
<script>
function PlaySound(soundObj) {
var sound = document.getElementById(soundObj);
sound.Play();
}
</script>
<embed src="success.wav" autostart="false" width="0" height="0" id="sound1"
enablejavascript="true">
You would then call it from JavaScript code as such:
PlaySound("sound1");
This should do exactly what you want - you'll just need to find/create the beep sound yourself, which should be trivial.
Everyone explained the topic very well. There is one more point i would like add about .load() method.
As per Load document if you add suffixed selector in data url then it will not execute scripts in loading content.
$(document).ready(function(){
$("#secondPage").load("mySecondHtmlPage.html #content");
})
On the other hand, after removing selector in url, scripts in new content will run. Try this example
after removing #content in url in index.html file
$(document).ready(function(){
$("#secondPage").load("mySecondHtmlPage.html");
})
There is no such in-built feature provided by other methods in discussion.
Use atoi() from <stdlib.h>
http://linux.die.net/man/3/atoi
Or, write your own atoi()
function which will convert char*
to int
int a2i(const char *s)
{
int sign=1;
if(*s == '-'){
sign = -1;
s++;
}
int num=0;
while(*s){
num=((*s)-'0')+num*10;
s++;
}
return num*sign;
}
COUNTIF
function can count cell which specific condition
where as COUNTA
will count all cell which contain any value
Example: Function in A7
: =COUNTA(A1:A6)
Range:
A1| a
A2| b
A3| banana
A4| 42
A5|
A6|
A7| 4 (result)
Just a little addition. If you've only selected 1 row then the code below will select the value of a column (index of 4, but 5th column) for the selected row:
me.lstIssues.Column(4)
This saves having to use the ItemsSelected property.
Kristian
I do this with javascript (no library) and CSS - the table body scrolls with the page, and the table does not have to be fixed width or height, although each column must have a width. You can also keep sorting functionality.
Basically:
In HTML, create container divs to position the table header row and the table body, also create a "mask" div to hide the table body as it scrolls past the header
In CSS, convert the table parts to blocks
In Javascript, get the table width and match the mask's width... get the height of the page content... measure scroll position... manipulate CSS to set the table header row position and the mask height
Here's the javascript and a jsFiddle DEMO.
// get table width and match the mask width
function setMaskWidth() {
if (document.getElementById('mask') !==null) {
var tableWidth = document.getElementById('theTable').offsetWidth;
// match elements to the table width
document.getElementById('mask').style.width = tableWidth + "px";
}
}
function fixTop() {
// get height of page content
function getScrollY() {
var y = 0;
if( typeof ( window.pageYOffset ) == 'number' ) {
y = window.pageYOffset;
} else if ( document.body && ( document.body.scrollTop) ) {
y = document.body.scrollTop;
} else if ( document.documentElement && ( document.documentElement.scrollTop) ) {
y = document.documentElement.scrollTop;
}
return [y];
}
var y = getScrollY();
var y = y[0];
if (document.getElementById('mask') !==null) {
document.getElementById('mask').style.height = y + "px" ;
if (document.all && document.querySelector && !document.addEventListener) {
document.styleSheets[1].rules[0].style.top = y + "px" ;
} else {
document.styleSheets[1].cssRules[0].style.top = y + "px" ;
}
}
}
window.onscroll = function() {
setMaskWidth();
fixTop();
}
If you want to edit that file (or any file in generally), you can't edit it simply writing its name in terminal. You must to use a command to a text editor to do this. For example:
nano ~/.bashrc
or
gedit ~/.bashrc
And in general, for any type of file:
xdg-open ~/.bashrc
Writing only ~/.bashrc
in terminal, this will try to execute that file, but .bashrc
file is not meant to be an executable file. If you want to execute the code inside of it, you can source it like follow:
source ~/.bashrc
or simple:
. ~/.bashrc
You can directly create a Calendar
from a Date
:
Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
catalog_outdated = 1;
}
It's best if you worked with DataSet
s and/or DataTable
s. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:
ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);
.. which will produce a beautiful excelsheet with a nice table!
Now to serve your file, assuming you have an ExcelPackage
object as in your code above called pck
..
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
Here's another way to do it, using a LINQ lambda:
C#:
SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));
VB.NET:
SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))
@media all and (max-width:320px)and(min-width:0px) {
#container {
width: 100%;
}
sty {
height: 50%;
width: 100%;
text-align: center;
margin: 0;
}
}
.username {
margin-bottom: 20px;
margin-top: 10px;
}
.container {
display: inline-block;
padding: 5px; /*included padding to see background when img apacity is 100%*/
background-color: black;
opacity: 1;
}
.container:hover {
background-color: red;
}
img {
opacity: 1;
}
img:hover {
opacity: 0.7;
}
.transition {
transition: all .25s ease-in-out;
-moz-transition: all .25s ease-in-out;
-webkit-transition: all .25s ease-in-out;
}
The best approach to use yum and update your devtoolset is to utilize the CentOS SCLo RH Testing repository.
yum install centos-release-scl-rh
yum --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc devtoolset-7-gcc-c++
Many additional packages are also available, to see them all
yum --enablerepo=centos-sclo-rh-testing list devtoolset-7*
You can use this method to install any dev tool version, just swap the 7 for your desired version. devtoolset-6-gcc, devtoolset-5-gcc etc.
Non of these solutions worked for my case:
notes:
import { keyBy, values } from 'lodash';
interface IStringTMap<T> {
[key: string]: T;
}
type IIdentified = {
id?: string | number;
};
export function mergeArrayById<T extends IIdentified>(
array1: T[],
array2: T[]
): T[] {
const mergedObjectMap: IStringTMap<T> = keyBy(array1, 'id');
const finalArray: T[] = [];
for (const object of array2) {
if (object.id && mergedObjectMap[object.id]) {
mergedObjectMap[object.id] = {
...mergedObjectMap[object.id],
...object,
};
} else {
finalArray.push(object);
}
}
values(mergedObjectMap).forEach(object => {
finalArray.push(object);
});
return finalArray;
}
I answered a virtually identical question just the other day: Save CSV files into mysql database
MySQL has a feature LOAD DATA INFILE
, which allows it to import a CSV file directly in a single SQL query, without needing it to be processed in a loop via your PHP program at all.
Simple example:
<?php
$query = <<<eof
LOAD DATA INFILE '$fileName'
INTO TABLE tableName
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field1,field2,field3,etc)
eof;
$db->query($query);
?>
It's as simple as that.
No loops, no fuss. And much much quicker than parsing it in PHP.
MySQL manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Hope that helps
As I commented above, problem seems to be the conversion from PIL internal list format to a standard python list type. I've found that Image.tostring() is much faster, and depending on your needs it might be enough. In my case, I needed to calculate the CRC32 digest of image data, and it suited fine.
If you need to perform more complex calculations, tom10 response involving numpy might be what you need.
case...when
behaves a bit unexpectedly when handling classes. This is due to the fact that it uses the ===
operator.
That operator works as expected with literals, but not with classes:
1 === 1 # => true
Fixnum === Fixnum # => false
This means that if you want to do a case ... when
over an object's class, this will not work:
obj = 'hello'
case obj.class
when String
print('It is a string')
when Fixnum
print('It is a number')
else
print('It is not a string or number')
end
Will print "It is not a string or number".
Fortunately, this is easily solved. The ===
operator has been defined so that it returns true
if you use it with a class and supply an instance of that class as the second operand:
Fixnum === 1 # => true
In short, the code above can be fixed by removing the .class
:
obj = 'hello'
case obj # was case obj.class
when String
print('It is a string')
when Fixnum
print('It is a number')
else
print('It is not a string or number')
end
I hit this problem today while looking for an answer, and this was the first appearing page, so I figured it would be useful to others in my same situation.
You can use Application.wait now + timevalue("00:00:01") or Application.wait now + timeserial(0,0,1)
Your operator is incorrect. Should be if number >= 10000 and number <= 30000:
. Additionally, Python has a shorthand for this sort of thing, if 10000 <= number <= 30000:
.
Naturally, I would not rest until I have the most convenient solution of all. Combining the very many answers and topics on the vast internet, here is what you can have.
cmd
DOSKEY
for aliasesls=ls --color=auto $*
Note that this is largely based on Argyll's answer and comments, definitely read it to understand the concepts.
mac
macro file with the aliasesbat
/cmd
file to also run other stuff (similar to .bashrc
in linux)cmd
%userprofile%/cmd/aliases.mac
;==============================================================================
;= This file is registered via registry to auto load with each instance of cmd.
;================================ general info ================================
;= https://stackoverflow.com/a/59978163/985454 - how to set it up?
;= https://gist.github.com/postcog/5c8c13f7f66330b493b8 - example doskey macrofile
;========================= loading with cmd shortcut ==========================
;= create a shortcut with the following target :
;= %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"
alias=subl %USERPROFILE%\cmd\aliases.mac
hosts=runas /noprofile /savecred /user:QWERTY-XPS9370\administrator "subl C:\Windows\System32\drivers\etc\hosts" > NUL
p=@echo "~~ powercfg -devicequery wake_armed ~~" && powercfg -devicequery wake_armed && @echo "~~ powercfg -requests ~~ " && powercfg -requests && @echo "~~ powercfg -waketimers ~~"p && powercfg -waketimers
ls=ls --color=auto $*
ll=ls -l --color=auto $*
la=ls -la --color=auto $*
grep=grep --color $*
~=cd %USERPROFILE%
cdr=cd C:\repos
cde=cd C:\repos\esquire
cdd=cd C:\repos\dixons
cds=cd C:\repos\stekkie
cdu=cd C:\repos\uplus
cduo=cd C:\repos\uplus\oxbridge-fe
cdus=cd C:\repos\uplus\stratus
npx=npx --no-install $*
npxi=npx $*
npr=npm run $*
now=vercel $*
;=only in bash
;=alias whereget='_whereget() { A=$1; B=$2; shift 2; eval \"$(where $B | head -$A | tail -1)\" $@; }; _whereget'
history=doskey /history
;= h [SHOW | SAVE | TSAVE ]
h=IF ".$*." == ".." (echo "usage: h [ SHOW | SAVE | TSAVE ]" && doskey/history) ELSE (IF /I "$1" == "SAVE" (doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "TSAVE" (echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "SHOW" (type %USERPROFILE%\cmd\history.log) ELSE (doskey/history))))
loghistory=doskey /history >> %USERPROFILE%\cmd\history.log
;=exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved, exiting & timeout 1 & exit $*
exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & exit $*
;============================= :end ============================
;= rem ******************************************************************
;= rem * EOF - Don't remove the following line. It clears out the ';'
;= rem * macro. We're using it because there is no support for comments
;= rem * in a DOSKEY macro file.
;= rem ******************************************************************
;=
Now you have three options:
a) load manually with shortcut
create a shortcut to
cmd.exe
with the following target :
%comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"
b) register just the aliases.mac
macrofile
c) register a regular cmd/bat
file to also run arbitrary commands
see example cmdrc.cmd
file at the bottom
note: Below, Autorun_
is just a placeholder key which will not do anything. Pick one and rename the other.
Manually edit registry at this path:
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
Autorun REG_SZ doskey /macrofile=%userprofile%\cmd\aliases.mac
Autorun_ REG_SZ %USERPROFILE%\cmd\cmdrc.cmd
Or import reg file:
%userprofile%/cmd/cmd-aliases.reg
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="doskey /macrofile=%userprofile%\\cmd\\aliases.mac"
"Autorun_"="%USERPROFILE%\\cmd\\cmdrc.cmd"
%userprofile%/cmd/cmdrc.cmd
you don't need this file if you decided for b) above
:: This file is registered via registry to auto load with each instance of cmd.
:: https://stackoverflow.com/a/59978163/985454
@echo off
doskey /macrofile=%userprofile%\cmd\aliases.mac
:: put other commands here
document.getElementById('mybox').style.display = "block";
This will work.
USE INFORMATION_SCHEMA;
SELECT TABLE_SCHEMA, TABLE_NAME
FROM information_schema.tables
WHERE TABLE_TYPE LIKE 'VIEW';
If you're working in a virtual environment (virtualenv), you'll definitely need to update the python.lintint.pylintPath
setting (and probably the python.pythonPath
setting, as well, if you haven't already) if you want linting to work, like this:
// File "settings.json" (workspace-specific one is probably best)
{
// ...
"python.linting.pylintPath": "C:/myproject/venv/Scripts/pylint.exe",
"python.pythonPath": "C:/myproject/venv/Scripts/python.exe",
// ...
}
That's for Windows, but other OSs are similar. The .exe
extension was necessary for it to work for me on Windows, even though it's not required when actually running it in the console.
If you just want to disable it, then use the python.linting.pylintEnabled": false
setting as mentioned in Ben Delaney's answer.
Just to provide a complete set, here's a version of Chase's answer using lattice
:
dat <- data.frame(dens = c(rnorm(100), rnorm(100, 10, 5))
, lines = rep(c("a", "b"), each = 100))
densityplot(~dens,data=dat,groups = lines,
plot.points = FALSE, ref = TRUE,
auto.key = list(space = "right"))
which produces a plot like this:
Style sheets are, effectively, concatenated into a single style sheet in the order in which they appear in the HTML source.
The normal rules for applying rulesets then apply (i.e. by specificity with the last ruleset that defines a given property winning in the event of a tie and !important throwing a spanner into the works)
Sometimes we developer stuck in small designing part of any UI screen. One of the most irritating requirement is under line text. Don’t worry here is the solution.
Underlining a text in a UILabel using Objective C
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
label.backgroundColor=[UIColor lightGrayColor];
NSMutableAttributedString *attributedString;
attributedString = [[NSMutableAttributedString alloc] initWithString:@"Apply Underlining"];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@1 range:NSMakeRange(0,
[attributedString length])];
[label setAttributedText:attributedString];
Underlining a text in UILabel using Swift
label.backgroundColor = .lightGray
let attributedString = NSMutableAttributedString.init(string: "Apply UnderLining")
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: 1, range:
NSRange.init(location: 0, length: attributedString.length))
label.attributedText = attributedString
Since you already had a running version of WAMP and it stopped working, you probably had VCRUNTIME140.dll already installed. In that case:
This did the trick for me.
Anything after Application.Run( ) will only be executed when the main form closes.
What you could do is handle the VisibleChanged
event as follows:
static Form1 form1;
static Form2 form2;
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form2 = new Form2();
form1 = new Form1();
form2.Hide();
form1.VisibleChanged += OnForm1Changed;
Application.Run(form1);
}
static void OnForm1Changed( object sender, EventArgs args )
{
if ( !form1.Visible )
{
form2.Show( );
}
}
I use SourceTree git client, and I see that their initial commit/push command is:
git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master
Took me a while to read through the above. This was the answer for me:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=False
)
plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)
Reference this for more arguments: matplotlib.pyplot.legend
From the JavaDocs for ResourceBundle.getBundle(String baseName)
:
baseName
- the base name of the resource bundle, a fully qualified class name
What this means in plain English is that the resource bundle must be on the classpath and that baseName
should be the package containing the bundle plus the bundle name, mybundle
in your case.
Leave off the extension and any locale that forms part of the bundle name, the JVM will sort that for you according to default locale - see the docs on java.util.ResourceBundle for more info.
Assuming you alredy tried to "Add Reference..." as explained above and did not succeed, you can have a look here. They say you have to meet some prerequisites: - .NET 3.5 SP1 - Windows Installer 4.5
EDIT: According to this post it is a known issue.
And this could be the solution you're looking for :)
I did
brew install mongodb
on 2018-02-01 and that gave me mongodb
version 3.6.2.
Prompted by the answer from orluke above, I tried just
$ brew services restart mongodb
and everything sprang into life. My mongoose.createConnection()
call did what I wanted. The GUI MongoDB Compass, the community version, would connect. I used Compass to look at the local.startup_log
collection. That had one document in, the log of me just starting the mongoDB service, and that had
cmdLine:Object
config:"/usr/local/etc/mongod.conf"
and indeed there was such a file:
$ more /usr/local/etc/mongod.conf
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
storage:
dbPath: /usr/local/var/mongodb
net:
bindIp: 127.0.0.1
and there was a /usr/local/var/mongodb
directory with lots of obscure files. So that seems to be how the installation works now.
I'm not sure if brew services restart
sets the service to run at login. So I did
brew services stop mongodb
brew services start mongodb
and hoped that starts it again after reboot. And, indeed, it did. In fact, now, I think the right thing to do after the initial installation is
brew services start mongodb
and that should start the service and restart it after reboot.
Simply use:
select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid
ViewBag is a dynamic type that allow you to dynamically set or get values and allow you to add any number of additional fields without a strongly-typed class They allow you to pass data from controller to view. In controller......
public ActionResult Index()
{
ViewBag.victor = "My name is Victor";
return View();
}
In view
@foreach(string a in ViewBag.victor)
{
.........
}
What I have learnt is that both should have the save dynamic name property ie ViewBag.victor
I'm using Debian, and I was unable to use tilde for the path. Originally I was using
curl -c "~/cookie" http://localhost:5000/login -d username=myname password=mypassword
I had to change this to:
curl -c "/tmp/cookie" http://localhost:5000/login -d username=myname password=mypassword
-c
creates the cookie, -b
uses the cookie
so then I'd use for instance:
curl -b "/tmp/cookie" http://localhost:5000/getData
Want to format it automatically when you save the file???
then Goto Window > Preferences > Java > Editor > Save Actions
and configure your save actions.
Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc
Yes. Try the following in your python interpreter:
and
>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero
or
>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero
According the W3Schools you might use JavaScript for disabled checkbox.
<!-- Checkbox who determine if the other checkbox must be disabled -->
<input type="checkbox" id="checkboxDetermine">
<!-- The other checkbox conditionned by the first checkbox -->
<input type="checkbox" id="checkboxConditioned">
<!-- JS Script -->
<script type="text/javascript">
// Get your checkbox who determine the condition
var determine = document.getElementById("checkboxDetermine");
// Make a function who disabled or enabled your conditioned checkbox
var disableCheckboxConditioned = function () {
if(determine.checked) {
document.getElementById("checkboxConditioned").disabled = true;
}
else {
document.getElementById("checkboxConditioned").disabled = false;
}
}
// On click active your function
determine.onclick = disableCheckboxConditioned;
disableCheckboxConditioned();
</script>
You can see the demo working here : http://jsfiddle.net/antoinesubit/vptk0nh6/
Here is a side-by-side comparison of several application starters/generators and other technologies including MEAN.js, MEAN.io, and cleverstack. I keep adding alternatives as I find time and as that happens, the list of potentially provided benefits keeps growing too. Today it's up to around 1600. If anyone wants to help improve its accuracy or completeness, click the next link and do a questionnaire about something you know.
Compare app technologies project
From this database, the system generates reports like the following:
I was facing this issue in a web application hosted on a shared hosting server. So obviously did not have direct access to IIS, so could not apply many solution proposed here.
On the hosting provider's control panel I enabled error logging for IIS and ASP.Net. And then got to know that error actually lied in a missing cshtml.
This is a pretty old feature request: Allow webdriver to attach to a running browser . So it's officially not supported.
However, there is some working code which claims to support this: https://web.archive.org/web/20171214043703/http://tarunlalwani.com/post/reusing-existing-browser-session-selenium-java/.
Kbrose's guidance on finding which logger was generating log messages was immensely useful. For my Django project, I had to sort through 120 different loggers until I found that it was the elasticsearch
Python library that was causing issues for me. As per the guidance in most of the questions, I disabled it by adding this to my loggers:
...
'elasticsearch': {
'handlers': ['console'],
'level': logging.WARNING,
},
...
Posting here in case someone else is seeing the unhelpful log messages come through whenever they run an Elasticsearch query.
As the thread mentioned in the comment, get-command
in powershell can also work it out. For example, you can type get-command npm
and the output is as below:
You can use .attr() as a part of however you plan to toggle it:
$("button").attr("aria-expanded","true");
The problem is by the time you pass the element from Javascript to Java back to Javascript it can have left the DOM.
Try doing the whole thing in Javascript:
driver.executeScript("document.querySelector('#my_id').click()")
I would suggest checking the drivers and updating them if required.
Try the "-o StrictHostKeyChecking=no" option to ssh("-o" being the flag that tells ssh that your are going to use an option). This accepts any incoming RSA key from your ssh connection, even if the key is not in the "known host" list.
sshpass -p 'password' ssh -o StrictHostKeyChecking=no user@host 'command'
Please excuse the length of this post.
This is a working example using ASP.NET Core version 2.5.
Something of note is that the project.json is obsolete (see here) in favor of .csproj. An issue with .csproj. file is the large amount of features and the fact there is no central location for its documentation (see here).
One more thing, this example is running ASP.NET core in a Docker Linux (alpine 3.9) container; so the paths will reflect that. It also uses gulp ^4.0. However, with some modification, it should work with older versions of ASP.NET Core, Gulp, NodeJS, and also without Docker.
But here's an answer:
gulpfile.js see the real working exmple here
// ROOT and OUT_DIR are defined in the file above. The OUT_DIR value comes from .NET Core when ASP.net us built.
const paths = {
styles: {
src: `${ROOT}/scss/**/*.scss`,
dest: `${OUT_DIR}/css`
},
bootstrap: {
src: [
`${ROOT}/node_modules/bootstrap/dist/css/bootstrap.min.css`,
`${ROOT}/node_modules/startbootstrap-creative/css/creative.min.css`
],
dest: `${OUT_DIR}/css`
},
fonts: {// enter correct paths for font-awsome here.
src: [
`${ROOT}/node_modules/fontawesome/...`,
],
dest: `${OUT_DIR}/fonts`
},
js: {
src: `${ROOT}/js/**/*.js`,
dest: `${OUT_DIR}/js`
},
vendorJs: {
src: [
`${ROOT}/node_modules/jquery/dist/jquery.min.js`
`${ROOT}/node_modules/bootstrap/dist/js/bootstrap.min.js`
],
dest: `${OUT_DIR}/js`
}
};
// Copy files from node_modules folder to the OUT_DIR.
let fonts = () => {
return gulp
.src(paths.styles.src)
.pipe(gulp.dest(paths.styles.dest));
};
// This compiles all the vendor JS files into one, jsut remove the concat to keep them seperate.
let vendorJs = () => {
return gulp
.src(paths.vendorJs.src)
.pipe(concat('vendor.js'))
.pipe(gulp.dest(paths.vendorJs.dest));
}
// Build vendorJs before my other files, then build all other files in parallel to save time.
let build = gulp.series(vendorJs, gulp.parallel(js, styles, bootstrap));
module.exports = {// Only add what we intend to use externally.
default: build,
watch
};
Add a Target in .csproj file. Notice we also added a Watch to watch
and exclude if we take advantage of dotnet run watch
command.
<ItemGroup>
<Watch Include="gulpfile.js;js/**/*.js;scss/**/*.scss" Exclude="node_modules/**/*;bin/**/*;obj/**/*" />
</ItemGroup>
<Target Name="BuildFrontend" BeforeTargets="Build">
<Exec Command="yarn install" />
<Exec Command="yarn run build -o $(OutputPath)" />
</Target>
Now when dotnet run build
is run it will also install and build node modules.
i was having the same issue while generating the classes from wsimport goal. Instead of using jaxws:wsimport goal in eclipse Maven Build i was using clean compile install that was not able to generate code from wsdl file. Thanks to above example. Run jaxws:wsimport goal from Eclipse ide and it will work
Simple solution if your are using express and doing
const router = express.Router();
make sure to
module.exports = router ;
at the end of your page
I see you try to set ylim
but you give bad values. This will change the scale of the plot (like a zoom). For example see this:
par(mfrow=c(2,1))
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN, col = rainbow(20),ylim=c(0,50),main='long y-axis')
r <- barplot(tN, col = rainbow(20),main='short y axis')
Another option is to plot without axes and set them manually using axis
and usr
:
require(grDevices) # for colours
par(mfrow=c(1,1))
r <- barplot(tN, col = rainbow(20),main='short y axis',ann=FALSE,axes=FALSE)
usr <- par("usr")
par(usr=c(usr[1:2], 0, 20))
axis(2,at=seq(0,20,5))
I settled on a solution inspired by the EqualBytesLongUnrolled method posted by ArekBulski with an additional optimization. In my instance, array differences in arrays tend to be near the tail of the arrays. In testing, I found that when this is the case for large arrays, being able to compare array elements in reverse order gives this solution a huge performance gain over the memcmp based solution. Here is that solution:
public enum CompareDirection { Forward, Backward }
private static unsafe bool UnsafeEquals(byte[] a, byte[] b, CompareDirection direction = CompareDirection.Forward)
{
// returns when a and b are same array or both null
if (a == b) return true;
// if either is null or different lengths, can't be equal
if (a == null || b == null || a.Length != b.Length)
return false;
const int UNROLLED = 16; // count of longs 'unrolled' in optimization
int size = sizeof(long) * UNROLLED; // 128 bytes (min size for 'unrolled' optimization)
int len = a.Length;
int n = len / size; // count of full 128 byte segments
int r = len % size; // count of remaining 'unoptimized' bytes
// pin the arrays and access them via pointers
fixed (byte* pb_a = a, pb_b = b)
{
if (r > 0 && direction == CompareDirection.Backward)
{
byte* pa = pb_a + len - 1;
byte* pb = pb_b + len - 1;
byte* phead = pb_a + len - r;
while(pa >= phead)
{
if (*pa != *pb) return false;
pa--;
pb--;
}
}
if (n > 0)
{
int nOffset = n * size;
if (direction == CompareDirection.Forward)
{
long* pa = (long*)pb_a;
long* pb = (long*)pb_b;
long* ptail = (long*)(pb_a + nOffset);
while (pa < ptail)
{
if (*(pa + 0) != *(pb + 0) || *(pa + 1) != *(pb + 1) ||
*(pa + 2) != *(pb + 2) || *(pa + 3) != *(pb + 3) ||
*(pa + 4) != *(pb + 4) || *(pa + 5) != *(pb + 5) ||
*(pa + 6) != *(pb + 6) || *(pa + 7) != *(pb + 7) ||
*(pa + 8) != *(pb + 8) || *(pa + 9) != *(pb + 9) ||
*(pa + 10) != *(pb + 10) || *(pa + 11) != *(pb + 11) ||
*(pa + 12) != *(pb + 12) || *(pa + 13) != *(pb + 13) ||
*(pa + 14) != *(pb + 14) || *(pa + 15) != *(pb + 15)
)
{
return false;
}
pa += UNROLLED;
pb += UNROLLED;
}
}
else
{
long* pa = (long*)(pb_a + nOffset);
long* pb = (long*)(pb_b + nOffset);
long* phead = (long*)pb_a;
while (phead < pa)
{
if (*(pa - 1) != *(pb - 1) || *(pa - 2) != *(pb - 2) ||
*(pa - 3) != *(pb - 3) || *(pa - 4) != *(pb - 4) ||
*(pa - 5) != *(pb - 5) || *(pa - 6) != *(pb - 6) ||
*(pa - 7) != *(pb - 7) || *(pa - 8) != *(pb - 8) ||
*(pa - 9) != *(pb - 9) || *(pa - 10) != *(pb - 10) ||
*(pa - 11) != *(pb - 11) || *(pa - 12) != *(pb - 12) ||
*(pa - 13) != *(pb - 13) || *(pa - 14) != *(pb - 14) ||
*(pa - 15) != *(pb - 15) || *(pa - 16) != *(pb - 16)
)
{
return false;
}
pa -= UNROLLED;
pb -= UNROLLED;
}
}
}
if (r > 0 && direction == CompareDirection.Forward)
{
byte* pa = pb_a + len - r;
byte* pb = pb_b + len - r;
byte* ptail = pb_a + len;
while(pa < ptail)
{
if (*pa != *pb) return false;
pa++;
pb++;
}
}
}
return true;
}
Try this code
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn"> </div>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
The jquery form plugin offers an easy way to iterate over your form elements and put them in a query string. It might also be useful for whatever else you need to do with these values.
var queryString = $('#myFormId').formSerialize();
From http://malsup.com/jquery/form
Or using straight jquery:
var queryString = $('#myFormId').serialize();
I found this;
from here;
vba- Can a combobox present more then one column on it's textbox part?
and this may help;
I added a sort of demo here;
In RStudio you can write directly in a cell.
Suppose your data.frame is called myDataFrame
and the row and column are called columnName
and rowName
.
Then the code would look like:
myDataFrame["rowName", "columnName"] <- value
Hope that helps!
I was looking into this issue a bit for my own purposes; I had a slice of structs (including some pointers) and I wanted to make sure I got it right; ended up on this thread, and wanted to share my results.
To practice, I did a little go playground: https://play.golang.org/p/9i4gPx3lnY
which evals to this:
package main
import "fmt"
type Blah struct {
babyKitten int
kittenSays *string
}
func main() {
meow := "meow"
Blahs := []Blah{}
fmt.Printf("Blahs: %v\n", Blahs)
Blahs = append(Blahs, Blah{1, &meow})
fmt.Printf("Blahs: %v\n", Blahs)
Blahs = append(Blahs, Blah{2, &meow})
fmt.Printf("Blahs: %v\n", Blahs)
//fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
Blahs = nil
meow2 := "nyan"
fmt.Printf("Blahs: %v\n", Blahs)
Blahs = append(Blahs, Blah{1, &meow2})
fmt.Printf("Blahs: %v\n", Blahs)
fmt.Printf("kittenSays: %v\n", *Blahs[0].kittenSays)
}
Running that code as-is will show the same memory address for both "meow" and "meow2" variables as being the same:
Blahs: []
Blahs: [{1 0x1030e0c0}]
Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
Blahs: []
Blahs: [{1 0x1030e0f0}]
kittenSays: nyan
which I think confirms that the struct is garbage collected. Oddly enough, uncommenting the commented print line, will yield different memory addresses for the meows:
Blahs: []
Blahs: [{1 0x1030e0c0}]
Blahs: [{1 0x1030e0c0} {2 0x1030e0c0}]
kittenSays: meow
Blahs: []
Blahs: [{1 0x1030e0f8}]
kittenSays: nyan
I think this may be due to the print being deferred in some way (?), but interesting illustration of some memory mgmt behavior, and one more vote for:
[]MyStruct = nil
Using React with Typescript you get an error as the function must return a react element, not void
. So I did it this way using the Route render method (and using React router v4):
redirectToHomePage = (): null => {
window.location.reload();
return null;
};
<Route exact path={'/'} render={this.redirectToHomePage} />
Where you could instead also use window.location.assign()
, window.location.replace()
etc
JFrame
is the window; it can have one or more JPanel
instances inside it. JPanel
is not the window.
You need a Swing tutorial:
In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:
declare
myname varchar2(20) := 'tom';
begin
for result_cursor in (select * from mytable where first_name = myname) loop
dbms_output.put_line(result_cursor.first_name);
dbms_output.put_line(result_cursor.other_field);
end loop;
end;
If you have a query that returns exactly one row, then you can use the select...into...
syntax, e.g.:
declare
myname varchar2(20);
begin
select first_name into myname
from mytable
where person_id = 123;
end;
To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.
I solved this issue by going into Properties -> Java Build Path and reordering my source folder so it was above the JRE System Library.
In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:
user = UniversityDetails.objects.get(email=email)
is email a str
, or a None
? or an int
?
As per Ammoq and kupa's answers, We use number(1) with default of 0 and don't allow nulls.
here's an add column to demonstrate:
ALTER TABLE YourSchema.YourTable ADD (ColumnName NUMBER(1) DEFAULT 0 NOT NULL);
Hope this helps someone.
I took the following approach, which uses a simple modal progress indicator widget that wraps whatever you want to make modal during an async call.
The example in the package also addresses how to handle form validation while making async calls to validate the form (see flutter/issues/9688 for details of this problem). For example, without leaving the form, this async form validation method can be used to validate a new user name against existing names in a database while signing up.
https://pub.dartlang.org/packages/modal_progress_hud
Here is the demo of the example provided with the package (with source code):
Example could be adapted to other modal progress indicator behaviour (like different animations, additional text in modal, etc..).
[<-
with mapply
is a bit faster than sapply
.
> dat[mapply(is.infinite, dat)] <- NA
With mnel's data, the timing is
> system.time(dat[mapply(is.infinite, dat)] <- NA)
# user system elapsed
# 15.281 0.000 13.750
As everybody above has explained about the difference between binary tree and binary search tree, i am just adding how to test whether the given binary tree is binary search tree.
boolean b = new Sample().isBinarySearchTree(n1, Integer.MIN_VALUE, Integer.MAX_VALUE);
.......
.......
.......
public boolean isBinarySearchTree(TreeNode node, int min, int max)
{
if(node == null)
{
return true;
}
boolean left = isBinarySearchTree(node.getLeft(), min, node.getValue());
boolean right = isBinarySearchTree(node.getRight(), node.getValue(), max);
return left && right && (node.getValue()<max) && (node.getValue()>=min);
}
Hope it will help you. Sorry if i am diverting from the topic as i felt it's worth mentioning this here.
I got the answer to my own question, ant this is:
select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))
Where N is the number of characters to remove. This avoids to write the complex column/string twice
Just a follow-up to dbb's accepted answer: Rather than adding the immediate cell on the right to the selection, why not select a cell way off the working range (i.e. a dummy cell that you know the user will never need). In the following code cell ZZ1
is the dummy cell
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.EnableEvents = False
Union(Target, Me.Range("ZZ1")).Select
Application.EnableEvents = True
' Respond to click/selection-change here
End Sub
You can use below query to create table and insert distinct values into this table:
Select Distinct Column1, Column2, Column3 into New_Users from Old_Users
Thank you for everyone's assistance and pushing to get rid of the eval statement. Variables needed to be in brackets, not dot notation. This works and is clean, proper code.
Each of these are variables: appChoice, underI, underObstr.
if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
//enter code here
}
What about this:
with open("your_csv_file.csv", "w") as f:
f.write("\n".join(text))
str.join() Return a string which is the concatenation of the strings in iterable. The separator between elements is the string providing this method.
Try this. I've use the Large Object Binary (LOB) format for storing generated PDF documents, some of which were 10+ MB in size, in a database and it worked wonderfully.
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
And most important!!!
When you change a namespace in your code, also make sure you change it in web.config!
If you want the column as string values, then:
SELECT id, name, CASE WHEN hide = 0 THEN 'false' ELSE 'true' END AS hide
FROM anonymous_table
If the DBMS supports BOOLEAN, you can use instead:
SELECT id, name, CASE WHEN hide = 0 THEN false ELSE true END AS hide
FROM anonymous_table
That's the same except that the quotes around the names false
and true
were removed.
Only adding the "Library Search Paths" (in Build Settings of 'MyProject') to "Pods/build/Debug-iphonesimulator" worked for me (when using the simulator).
Got it from here: https://github.com/CocoaPods/CocoaPods/issues/121#issuecomment-5452473
Working with profiles is little tricky. Documentation can be found at: https://docs.aws.amazon.com/cli/latest/topic/config-vars.html (But you need to pay attention on env variables like AWS_PROFILE)
Using profile with aws cli requires a config file (default at ~/.aws/config
or set using AWS_CONFIG_FILE
).
A sample config file for reference:
`
[profile PROFILE_NAME]
output=json
region=us-west-1
aws_access_key_id=foo
aws_secret_access_key=bar
`
Env variable AWS_PROFILE
informs AWS cli about the profile to use from AWS config. It is not an alternate of config file like AWS_ACCESS_KEY_ID
/AWS_SECRET_ACCESS_KEY
are for ~/.aws/credentials
.
Another interesting fact is if AWS_PROFILE
is set and the AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
environment variables are set, then the credentials provided by AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
will override the credentials located in the profile provided by AWS_PROFILE
.
CREATE VIEW MyView AS
SELECT Column, Value FROM Table;
SELECT Column FROM MyView WHERE Value = 1;
Is the proper solution in MySQL, some other SQLs let you define Views more exactly.
Note: Unless the View is very complicated, MySQL will optimize this just fine.
it finally worked for me after I did sudo npm i cjs-loader (and make sure to install express, not just express-http-proxy)
Obfuscation can never really work. For anyone who really wants to get at your code, it's just a speed bump. Worse, it keeps your users from fixing bugs (and shipping the fixes back to you), and makes it harder for you to diagnose problems in the field. Its a waste of your time and money.
Talk to a lawyer about intellectual property law and what your legal options are. "Open Source" does not mean "people can read the source". Instead, Open Source is a particular licensing model granting permission to freely use and modify your code. If you don't grant such a license then people copying your code are in violation and (in most of the world) you have legal options to stop them.
The only way you can really protect your code is to not ship it. Move the important code server-side and have your public Javascript code do Ajax calls to it.
gitweb will allow you to browse through the code (and changes) via a browser.
http://git.or.cz/gitwiki/Gitweb
(Don't know if someone has already setup a public gitweb for Android, but it's probably not too hard.)
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
$(function () {
$("#txtSearch").keyup(function (event) {
var txt = $("#txtSearch").val()
if (txt.length > 3) {
$("span.hilightable").each(function (i, v) {
v.innerHTML = v.innerText.replace(txt, "<hilight>" + txt + "</hilight>");
});
}
});
});
Jfiddle here
$ cat x.mak all: echo $(OPTION) $ make -f x.mak 'OPTION=-DPASSTOC=42' echo -DPASSTOC=42 -DPASSTOC=42
If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:
First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.
package financialdocuments;
import java.lang.*;
import java.util.HashMap;
/**
*
* @author Administrator
*/
public class Document {
private int document_number;
private boolean document_type;
private boolean document_status;
private StringBuilder document_date;
private StringBuilder document_statement;
private int document_code_number;
private int document_employee_number;
private int document_client_number;
private String document_employee_name;
private String document_client_name;
private long document_amount;
private long document_payment_amount;
HashMap<Integer,Activity> document_activity_hashmap;
public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){
document_date = new StringBuilder(dd);
document_date.setLength(10);
document_date.setCharAt(4, '.');
document_date.setCharAt(7, '.');
document_statement = new StringBuilder(dst);
document_statement.setLength(50);
document_number = dn;
document_type = dt;
document_status = ds;
document_code_number = dcon;
document_employee_number = den;
document_client_number = dcln;
document_amount = da;
document_employee_name = dena;
document_client_name = dcna;
document_payment_amount = 0;
document_activity_hashmap = new HashMap<>();
}
public Document(int dn,boolean dt,boolean ds, long dpa){
document_number = dn;
document_type = dt;
document_status = ds;
document_payment_amount = dpa;
document_activity_hashmap = new HashMap<>();
}
// Print document information
public void printDocumentInformation (){
System.out.println("Document Number:" + document_number);
System.out.println("Document Date:" + document_date);
System.out.println("Document Type:" + document_type);
System.out.println("Document Status:" + document_status);
System.out.println("Document Statement:" + document_statement);
System.out.println("Document Code Number:" + document_code_number);
System.out.println("Document Client Number:" + document_client_number);
System.out.println("Document Employee Number:" + document_employee_number);
System.out.println("Document Amount:" + document_amount);
System.out.println("Document Payment Amount:" + document_payment_amount);
System.out.println("Document Employee Name:" + document_employee_name);
System.out.println("Document Client Name:" + document_client_name);
}
}
Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.
package financialdocuments;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class DataBase {
/**
*
* Defining parameters and strings that are going to be used
*
*/
//Connection connect;
// Tables which their datas are extracted at the beginning
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;
// Resultset Returned by queries
private ResultSet result;
// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
public DataBase(){
code_table = new HashMap<>();
activity_table = new HashMap<>();
client_table = new HashMap<>();
employee_table = new HashMap<>();
Initialize();
}
/**
* Set variables and objects for this class.
*/
private void Initialize(){
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Get tables' information
selectCodeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printCodeTableQueryArray();
selectActivityTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printActivityTableQueryArray();
selectClientTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printClientTableQueryArray();
selectEmployeeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printEmployeeTableQueryArray();
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
/**
* Write Queries
* @param s
* @return
*/
public boolean insertQuery(String s){
boolean ret = false;
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Set tables' information
try {
Statement st = connect.createStatement();
int val = st.executeUpdate(s);
if(val==1){
System.out.print("Successfully inserted value");
ret = true;
}
else{
System.out.print("Unsuccessful insertion");
ret = false;
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
return ret;
}
/**
* Query needed to get code table's data
* @param c
* @return
*/
private void selectCodeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM code;");
while (res.next()) {
int id = res.getInt("code_number");
String msg = res.getString("code_statement");
code_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printCodeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectActivityTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM activity;");
while (res.next()) {
int id = res.getInt("activity_number");
String msg = res.getString("activity_statement");
activity_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printActivityTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get client table's data
* @param c
* @return
*/
private void selectClientTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM client;");
while (res.next()) {
int id = res.getInt("client_number");
String msg = res.getString("client_full_name");
client_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printClientTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectEmployeeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee;");
while (res.next()) {
int id = res.getInt("employee_number");
String msg = res.getString("employee_full_name");
employee_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printEmployeeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
}
I hope this could be a little help.
For 2.3 seconds you should do:
System.Threading.Thread.Sleep(2300);
var resident_array = ["RC_FRONT", "RC_BACK", "RC_BACK"];
var remove_item = "RC_FRONT";
resident_array = $.grep(resident_array, function(value) {
return value != remove_item;
});
resident_array = ["RC_BACK", "RC_BACK"];
Instead of
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;
which is not correct, use
background-repeat: no-repeat;
import codecs
f=codecs.open("test.html", 'r')
print f.read()
Try something like this.
Just use these command lines:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
If needed, you can also follow this Ubuntu tutorial.
This seems quick for me :
comm -1 -3 <(sort file1.txt) <(sort file2.txt) > output.txt
Putting each of your top-level windows into it's own separate class gives you code re-use and better code organization. Any buttons and relevant methods that are present in the window should be defined inside this class. Here's an example (taken from here):
import tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Demo2(self.newWindow)
class Demo2:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
Also see:
Hope that helps.
use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>
In an RPM-based Linux, you can check presence of MySQL like this:
rpm -qa | grep mysql
For debian or other dpkg-based systems, check like this: *
*
Either the parameter supplied for ZIP_CODE
is larger (in length) than ZIP_CODE
s column width or the parameter supplied for CITY
is larger (in length) than CITY
s column width.
It would be interesting to know the values supplied for the two ?
placeholders.
Skip reading the html and use curl
to POST whatever form data you want to submit to the server.
// Try this may help
DateTime myDate = new DateTime();
string us = myDate.Now.Date.ToString("MM/dd/yyyy",new CultureInfo("en-US"));
or
DateTime myDate = new DateTime();
string us = myDate.Now.Date.ToString("dd/MM/yyyy",new CultureInfo("en-GB"));
Pelo Hyper-V:
private PerformanceCounter theMemCounter = new PerformanceCounter(
"Hyper-v Dynamic Memory VM",
"Physical Memory",
Process.GetCurrentProcess().ProcessName);
for quick one time use this works, npm install --python="c:\python27"
You can reference those remote tracking branches ~(listed with git branch -r
) with the name of their remote.
You need to fetch the remote branch:
git fetch origin aRemoteBranch
If you want to merge one of those remote branches on your local branch:
git checkout master
git merge origin/aRemoteBranch
Note 1: For a large repo with a long history, you will want to add the --depth=1
option when you use git fetch
.
Note 2: These commands also work with other remote repos so you can setup an origin
and an upstream
if you are working on a fork.
Note 3: user3265569 suggests the following alias in the comments:
From
aLocalBranch
, rungit combine remoteBranch
Alias:combine = !git fetch origin ${1} && git merge origin/${1}
Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:
git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch
The idea here, is to merge "one of your local branch" (here anotherLocalBranch
) to a remote branch (origin/aBranch
).
For that, you create first "myBranch
" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch
part.
And then you can merge anotherLocalBranch
to it (to myBranch
).
You can't. IEnumerable<T>
can only be iterated.
In your second example, you can remove from original collection by iterating over a copy of it
foreach(var u in users.ToArray()) // ToArray creates a copy
{
if(u.userId != 1233)
{
users.Remove(u);
}
}
In order to get the value of the selected item you can do the following:
this.options[this.selectedIndex].text
Here the different options
of the select are accessed, and the SelectedIndex
is used to choose the selected one, then its text
is being accessed.
Read more about the select DOM here.
you have multiple elements with the same id. That is a big no-no. Make sure your inputs have unique ids.
<td id="pass"><label>Password</label></td>
<tr>
<td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>
see, both the td
and the input
share the id value pass
.
You are typing the command wrong. It is "\" before "!" and not after. The command ctrl+L will not work for windows. To clear mysql console screen, type following command.
mysql> \! cls
This will do the job for windows. "\!" is used to execute system shell command. "cls" is command to clear windows command prompt screen. Similarly if you are on linux, you will type "ctrl+L" or following,
mysql> \! clear
source: https://dev.mysql.com/doc/refman/8.0/en/mysql-commands.html
Trevor Sullivan has a write-up on how to add a command called Copy-ItemWithProgress to PowerShell on Robocopy.
You can use following class as service class to run your application in background
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
private GPSTracker gpsTracker;
private Handler handler= new Handler();
private Timer timer = new Timer();
private Distance pastDistance = new Distance();
private Distance currentDistance = new Distance();
public static double DISTANCE;
boolean flag = true ;
private double totalDistance ;
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
if(flag){
pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
flag = false;
}else{
currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
flag = comapre_LatitudeLongitude();
}
Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();
}
});
}
};
timer.schedule(timerTask,0, 5000);
}
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("--------------------------------onDestroy -stop service ");
timer.cancel();
DISTANCE = totalDistance ;
}
public boolean comapre_LatitudeLongitude(){
if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
return false;
}else{
final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
System.out.println("Distance in mile :"+distance);
handler.post(new Runnable() {
@Override
public void run() {
float kilometer=1.609344f;
totalDistance = totalDistance + distance * kilometer;
DISTANCE = totalDistance;
//Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();
}
});
return true;
}
}
}
Add One another class to get location
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSTracker implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
private Location m_Location;
public GPSTracker(Context context) {
this.mContext = context;
m_Location = getLocation();
System.out.println("location Latitude:"+m_Location.getLatitude());
System.out.println("location Longitude:"+m_Location.getLongitude());
System.out.println("getLocation():"+getLocation());
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
}
else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
// --------------Distance.java
public class Distance {
private double latitude ;
private double longitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
<?php //-- Very simple variant
$useragent = $_SERVER['HTTP_USER_AGENT'];
$iPod = stripos($useragent, "iPod");
$iPad = stripos($useragent, "iPad");
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android");
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices
$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS||$webOS||$Blackberry||$IEMobile||$OperaMini);
if ($DEVICE !=true) {?>
<!-- What you want for all non-mobile devices. Anything with all HTML codes-->
<?php }else{ ?>
<!-- What you want for all mobile devices. Anything with all HTML codes -->
<?php } ?>
According to:
Fixing Node Mysql "Error: Cannot enqueue Handshake after invoking quit.":
http://codetheory.in/fixing-node-mysql-error-cannot-enqueue-handshake-after-invoking-quit/
TL;DR You need to establish a new connection by calling the
createConnection
method after every disconnection.
and
Note: If you're serving web requests, then you shouldn't be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.
From:
Readme.md - Server disconnects:
It says:
Server disconnects
You may lose the connection to a MySQL server due to network problems, the server timing you out, or the server crashing. All of these events are considered fatal errors, and will have the
err.code = 'PROTOCOL_CONNECTION_LOST'
. See the Error Handling section for more information.The best way to handle such unexpected disconnects is shown below:
function handleDisconnect(connection) { connection.on('error', function(err) { if (!err.fatal) { return; } if (err.code !== 'PROTOCOL_CONNECTION_LOST') { throw err; } console.log('Re-connecting lost connection: ' + err.stack); connection = mysql.createConnection(connection.config); handleDisconnect(connection); connection.connect(); }); } handleDisconnect(connection);
As you can see in the example above, re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design.
With Pool, disconnected connections will be removed from the pool freeing up space for a new connection to be created on the next getConnection call.
I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:
function initializeConnection(config) {
function addDisconnectHandler(connection) {
connection.on("error", function (error) {
if (error instanceof Error) {
if (error.code === "PROTOCOL_CONNECTION_LOST") {
console.error(error.stack);
console.log("Lost connection. Reconnecting...");
initializeConnection(connection.config);
} else if (error.fatal) {
throw error;
}
}
});
}
var connection = mysql.createConnection(config);
// Add handlers.
addDisconnectHandler(connection);
connection.connect();
return connection;
}
Initializing a connection:
var connection = initializeConnection({
host: "localhost",
user: "user",
password: "password"
});
Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection
, which was var connection = mysql.createConnection(config);
to simply just
connection = mysql.createConnection(config);
The reason being that if connection
is a global variable in your program, then the issue before was that you were making a new connection
variable when handling an error signal. But in my nodejs code, I kept using the same global connection
variable to run queries on, so the new connection
would be lost in the local scope of the initalizeConnection
method. But in the modification, it ensures that the global connection
variable is reset This may be relevant if you're experiencing an issue known as
Cannot enqueue Query after fatal error
after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.
Replace [ with nothing, then ] with nothing.
import java.io.FileInputStream; import java.io.ByteArrayOutputStream;
public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream
public static byte[] read(InputStream is) throws Exception
{
String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */;
// must need a Byte buffer
byte[] buf = new byte[1024 * 16]
// we will use 16 kilobytes
int len = 0;
// we need a new input stream
FileInputStream is = new FileInputStream(path);
// use the buffer to update our "MessageDigest" instance
while(true)
{
len = is.read(buf);
if(len < 0) break;
md.update(buf, 0, len);
}
// close the input stream
is.close();
// call the "digest" method for obtaining the final hash-result
byte[] ret = md.digest();
System.out.println("Length of Hash: " + ret.length);
for(byte b : ret)
{
System.out.println(b + ", ");
}
String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
String verification = Hex.encodeHexString(ret);
System.out.println();
System.out.println("===")
System.out.println(verification);
System.out.println("Equals? " + verification.equals(compare));
}
}
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?
Require all granted
is only in 2.4, but Allow all ...
stops working in 2.4, and we want to be able to rollout a config that works in both.
The only solution I found, which I am not sure is the proper one, is to use:
# backwards compatibility with apache 2.2
Order allow,deny
Allow from all
# forward compatibility with apache 2.4
Require all granted
Satisfy Any
This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...
See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.
With Modernizr you can target your hovers specifically for no-touch devices:
(Note: this doesn't run on StackOverflow's snippet system, check the jsfiddle instead)
/* this one is sticky */
#regular:hover, #regular:active {
opacity: 0.5;
}
/* this one isn't */
html.no-touch #no-touch:hover, #no-touch:active {
opacity: 0.5;
}
Note that :active
doesn't need to be targeted with .no-touch
because it works as expected on both mobile and desktop.
You can use $addToSet with the aggregation framework to count distinct objects.
For example:
db.collectionName.aggregate([{
$group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])
I am not sure I understood your question, but if you write:
mask_data[:3, :3] = 1
mask_data[3:, 3:] = 0
This will make all values of mask data whose x and y indexes are less than 3 to be equal to 1 and all rest to be equal to 0
$sql = file_get_contents("sql.sql");
Seems to be the simplest answer
Add in activity
requestWindowFeature(Window.FEATURE_NO_TITLE);
and add your style.xml
file with the following two lines:
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
Swift 3:
extension Dictionary {
mutating func merge(with dictionary: Dictionary) {
dictionary.forEach { updateValue($1, forKey: $0) }
}
func merged(with dictionary: Dictionary) -> Dictionary {
var dict = self
dict.merge(with: dictionary)
return dict
}
}
let a = ["a":"b"]
let b = ["1":"2"]
let c = a.merged(with: b)
print(c) //["a": "b", "1": "2"]
You've almost got it...
MY_TYPE a = { true,15,0.123 };
Today 2020.05.16 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6
arr[arr.length-1]
(D) is recommended as fastest cross-browser solutionarr.pop()
(A) and immutable _.last(arr)
(L) are fastI test two cases for solutions:
for two cases
function A(arr) {
return arr.pop();
}
function B(arr) {
return arr.splice(-1,1);
}
function C(arr) {
return arr.reverse()[0]
}
function D(arr) {
return arr[arr.length - 1];
}
function E(arr) {
return arr.slice(-1)[0] ;
}
function F(arr) {
let [last] = arr.slice(-1);
return last;
}
function G(arr) {
return arr.slice(-1).pop();
}
function H(arr) {
return [...arr].pop();
}
function I(arr) {
return arr.reduceRight(a => a);
}
function J(arr) {
return arr.find((e,i,a)=> a.length==i+1);
}
function K(arr) {
return $(arr).get(-1);
}
function L(arr) {
return _.last(arr);
}
function M(arr) {
return _.nth(arr, -1);
}
// ----------
// TEST
// ----------
let loc_array=["domain","a","b","c","d","e","f","g","h","file"];
log = (f)=> console.log(`${f.name}: ${f([...loc_array])}`);
[A,B,C,D,E,F,G,H,I,J,K,L,M].forEach(f=> log(f));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
_x000D_
Example results for Chrome for short string
select charindex( 'Express',@@version)
if this value is 0 is not a express edition
Your Manifest
Must Change like this Activity name must Specified like ".YourActivityname"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" android:targetSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainTabPanel"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyBookActivity" >
</activity>
</application>
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history
object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState
. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState
to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
this worked for me:
$data=DB::table('table_name')->select(.......)->get();
$data=array_map(function($item){
return (array) $item;
},$data);
or
$data=array_map(function($item){
return (array) $item;
},DB::table('table_name')->select(.......)->get());
def rounding(float,precision)
return ((float * 10**precision).round.to_f) / (10**precision)
end
Using jQuery:
$('#Button').click(function(){
$(this).addClass("active");
});
This way, you don't have to pollute your HTML markup with onclick
handlers.
You want to utilize the renameTo method on a File object.
First, create a File object to represent the destination. Check to see if that file exists. If it doesn't exist, create a new File object for the file to be moved. call the renameTo method on the file to be moved, and check the returned value from renameTo to see if the call was successful.
If you want to append the contents of one file to another, there are a number of writers available. Based on the extension, it sounds like it's plain text, so I would look at the FileWriter.
There is an option to disable cross-origin restrictions in Safari 9, different from local file restrictions as mentioned above.
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
Restarting Android Studio helped me.
Ultimately, we are trying to get to this.
<div style="display: flex; justify-content: center;">
<button ion-button>Login</button>
</div>
The underlying XMLHttpRequest object (used by jQuery to make the request) supports the asynchronous property. Set it to false. Like
async: false
See numpy.clip:
index = numpy.clip(index, 0, len(my_list) - 1)
After the docker installation you have 3 networks by default:
docker network ls
NETWORK ID NAME DRIVER SCOPE
f3be8b1ef7ce bridge bridge local
fbff927877c1 host host local
023bb5940080 none null local
I'm trying to keep this simple. So if you start a container by default it will be created inside the bridge (docker0) network.
$ docker run -d jenkins
1498e581cdba jenkins "/bin/tini -- /usr..." 3 minutes ago Up 3 minutes 8080/tcp, 50000/tcp friendly_bell
In the dockerfile of jenkins the ports 8080
and 50000
are exposed. Those ports are opened for the container on its bridge network. So everything inside that bridge network can access the container on port 8080
and 50000
. Everything in the bridge network is in the private range of "Subnet": "172.17.0.0/16",
If you want to access them from the outside you have to map the ports with -p 8080:8080
. This will map the port of your container to the port of your real server (the host network). So accessing your server on 8080
will route to your bridgenetwork on port 8080
.
Now you also have your host network. Which does not containerize the containers networking. So if you start a container in the host network it will look like this (it's the first one):
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1efd834949b2 jenkins "/bin/tini -- /usr..." 6 minutes ago Up 6 minutes eloquent_panini
1498e581cdba jenkins "/bin/tini -- /usr..." 10 minutes ago Up 10 minutes 8080/tcp, 50000/tcp friendly_bell
The difference is with the ports. Your container is now inside your host network. So if you open port 8080
on your host you will acces the container immediately.
$ sudo iptables -I INPUT 5 -p tcp -m tcp --dport 8080 -j ACCEPT
I've opened port 8080
in my firewall and when I'm now accesing my server on port 8080
I'm accessing my jenkins. I think this blog is also useful to understand it better.
Just use the size attribute:
<select name="sometext" size="5">
<option>text1</option>
<option>text2</option>
<option>text3</option>
<option>text4</option>
<option>text5</option>
</select>
To clarify, adding the size attribute did not remove the multiple selection.
The single selection works because you removed the multiple="multiple" attribute.
Adding the size="5" attribute is still a good idea, it means that at least 5 lines must be displayed. See the full reference here
This will help you.
debugger;
var today = new Date();
document.getElementById('date').innerHTML = today
It depends upon lower_case_table_names
system variable:
show variables where Variable_name='lower_case_table_names'
There are three possible values for this:
0
- lettercase specified in the CREATE TABLE
or CREATE DATABASE
statement. Name comparisons are case sensitive. 1
- Table names are stored in lowercase on disk and name comparisons are not case sensitive. 2
- lettercase specified in the CREATE TABLE
or CREATE DATABASE
statement, but MySQL converts them to lowercase on lookup.
Name comparisons are not case sensitive.By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.
(\s|\(|\.|,|^)bqr(\s|,|\)|$)
Update: As of SQL Server 2016 parsing JSON in TSQL is now possible.
Natively, there is no support. You'll have to use CLR. It is as simple as that, unless you have a huge masochistic streak and want to write a JSON parser in SQL
Normally, folk ask for JSON output from the DB and there are examples on the internet. But into a DB?
The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.
You can access web references via the advanced options in add service reference (if I recall correctly).
I'd use service reference because as I understand it, it's the newer mechanism of the two.
I realise this is an older question, but I recently came across this need and came up with the following solution using jQuery and CSS:
jQuery('select[name*="lstDestinations"] option').hover(
function() {
jQuery(this).addClass('highlight');
}, function() {
jQuery(this).removeClass('highlight');
}
);
and the css:
.highlight {
background-color:#333;
cursor:pointer;
}
Perhaps this helps someone else.
Here is a demo react_hooks_debug_print.html
in react hooks that is based on Chris's answer. The json data example is from https://json.org/example.html.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script src="https://raw.githubusercontent.com/cassiozen/React-autobind/master/src/autoBind.js"></script>
<script type="text/babel">
let styles = {
root: { backgroundColor: '#1f4662', color: '#fff', fontSize: '12px', },
header: { backgroundColor: '#193549', padding: '5px 10px', fontFamily: 'monospace', color: '#ffc600', },
pre: { display: 'block', padding: '10px 30px', margin: '0', overflow: 'scroll', }
}
let data = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}
const DebugPrint = () => {
const [show, setShow] = React.useState(false);
return (
<div key={1} style={styles.root}>
<div style={styles.header} onClick={ ()=>{setShow(!show)} }>
<strong>Debug</strong>
</div>
{ show
? (
<pre style={styles.pre}>
{JSON.stringify(data, null, 2) }
</pre>
)
: null
}
</div>
)
}
ReactDOM.render(
<DebugPrint data={data} />,
document.getElementById('root')
);
</script>
</body>
</html>
Or in the following way, add the style into header:
<style>
.root { background-color: #1f4662; color: #fff; fontSize: 12px; }
.header { background-color: #193549; padding: 5px 10px; fontFamily: monospace; color: #ffc600; }
.pre { display: block; padding: 10px 30px; margin: 0; overflow: scroll; }
</style>
And replace DebugPrint
with the follows:
const DebugPrint = () => {
// https://stackoverflow.com/questions/30765163/pretty-printing-json-with-react
const [show, setShow] = React.useState(false);
return (
<div key={1} className='root'>
<div className='header' onClick={ ()=>{setShow(!show)} }>
<strong>Debug</strong>
</div>
{ show
? (
<pre className='pre'>
{JSON.stringify(data, null, 2) }
</pre>
)
: null
}
</div>
)
}
I wrote a function to handle this using regular expressions. The in parameters are: 1) the listagg call itself 2) A repeat of the delimiter
create or replace function distinct_listagg
(listagg_in varchar2,
delimiter_in varchar2)
return varchar2
as
hold_result varchar2(4000);
begin
select rtrim( regexp_replace( (listagg_in)
, '([^'||delimiter_in||']*)('||
delimiter_in||'\1)+($|'||delimiter_in||')', '\1\3'), ',')
into hold_result
from dual;
return hold_result;
end;
Now you don't have to repeat the regular expression every time you do this, simply say:
select distinct_listagg(
listagg(myfield,', ') within group (order by 1),
', '
)
from mytable;
The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.
Your criticism is entirely justified.
I discuss this problem in detail here:
Closing over the loop variable considered harmful
Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.
I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.
The for
loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.
You cannot simply add a link using CSS. CSS is used for styling.
You can style your using CSS.
If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.
You can accomplish that very easily using jQuery.
I have done a sample for you. You can refer that.
$('#link').attr('href','http://www.google.com');
This single line will do the trick.
I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job. I would suggest using a "naive" way.
Define some global boolean:
std::atomic_bool stop_thread_1 = false;
Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:
if (stop_thread_1)
return;
Then to stop the thread from another (main) thread:
stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)
To solve CLR20r3 problem set - Local User Policy \ Computer Configuration \ Windows Settings \ Security Settings \ Local Policies \ Security Options - System cryptography
: Use FIPS 140 compliant cryptographic algorithms, including encryption, hashing and signing - Disable
There is a new official BottomNavigationView in version 25 of the Design Support Library
https://developer.android.com/reference/android/support/design/widget/BottomNavigationView.html
add in gradle
compile 'com.android.support:design:25.0.0'
XML
<android.support.design.widget.BottomNavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:design="http://schema.android.com/apk/res/android.support.design"
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
design:menu="@menu/my_navigation_items" />
Try to uncheck the CheckBox “Use Managed Compatibility Mode” in
Tools => Options => Debugging => General
It worked for me.
Here's a method which allows you to register a Runnable
to be executed once a particular web address has finished loading. We associate each Runnable
with a corresponding URL String
in a Map
, and we use the WebView
's getOriginalUrl()
method to choose the appropriate callback.
package io.github.cawfree.webviewcallback;
/**
* Created by Alex Thomas (@Cawfree), 30/03/2017.
**/
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.HashMap;
import java.util.Map;
/** An Activity demonstrating how to introduce a callback mechanism into Android's WebView. */
public class MainActivity extends AppCompatActivity {
/* Member Variables. */
private WebView mWebView;
private Map<String, Runnable> mCallbackMap;
/** Create the Activity. */
@Override protected final void onCreate(final Bundle pSavedInstanceState) {
// Initialize the parent definition.
super.onCreate(pSavedInstanceState);
// Set the Content View.
this.setContentView(R.layout.activity_main);
// Fetch the WebView.
this.mWebView = (WebView)this.findViewById(R.id.webView);
this.mCallbackMap = new HashMap<>();
// Define the custom WebClient. (Here I'm just suppressing security errors, since older Android devices struggle with TLS.)
this.getWebView().setWebViewClient(new WebViewClient() {
/** Handle when a request has been launched. */
@Override public final void onPageFinished(final WebView pWebView, final String pUrl) {
// Determine whether we're allowed to process the Runnable; if the page hadn't been redirected, or if we've finished redirection.
if(pUrl.equals(pWebView.getOriginalUrl())) {
// Fetch the Runnable for the OriginalUrl.
final Runnable lRunnable = getCallbackMap().get(pWebView.getOriginalUrl());
// Is it valid?
if(lRunnable != null) { lRunnable.run(); }
}
// Handle as usual.
super.onPageFinished(pWebView, pUrl);
}
/** Ensure we handle SSL state properly. */
@Override public final void onReceivedSslError(final WebView pWebView, final SslErrorHandler pSslErrorHandler, final SslError pSslError) { pSslErrorHandler.proceed(); }
});
// Assert that we wish to visit Zonal's website.
this.getWebView().loadUrl("http://www.zonal.co.uk/");
// Align a Callback for Zonal; this will be serviced once the page has loaded.
this.getCallbackMap().put("http://www.zonal.co.uk/", new Runnable() { @Override public void run() { /* Do something. */ } });
}
/* Getters. */
public final WebView getWebView() {
return this.mWebView;
}
private final Map<String, Runnable> getCallbackMap() {
return this.mCallbackMap;
}
}
I think the matter is your tables engine. I guess you are using InnoDB for your table. So you can not copy files easily to make a copy.
Take a look at these links:
http://dev.mysql.com/doc/refman/5.0/en/innodb-backup.html
http://dev.mysql.com/doc/refman/5.0/en/innodb-migration.html
Also I recommend you to use something like phpMyAdmin for creating your backup file and then restore the backup file on the next machine using the same IDE.
Steps for Android Wifi debugging with ADB:
$> adb devices // check all usb debuggable devices connected.
$> adb -d shell // Access device shell.
shell> ifconfig // Check and copy wifi ip-address eg:192.168.1.90
shell> exit // Exit from android device shell.
$> adb tcpip 5000 // open TCP port 5000 (or any available)
$> adb connect 192.168.1.90:5000 // connect to device via wifi ip over specific TCP port.
$> adb devices // you will get debuggabled android device over wifi.
Required: Connect your android device to computer via USB with developer mode enabled. Also connect your android device and computer to same wifi router (or use tethering).
https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
For MySQL 8
alter table creditReportXml_temp change column applicationID applicantID int(11);
Use this to create your images and put them in specific resource folder.
http://download.eclipse.org/webtools/updates/ - This is an old URL and doesn't work any more. If you want to install WTP (i.e. J2EE plugins) use the following URLs depending upon the version of the eclipse you are using:
More information can be found here.
you must write single quotes then double quotes then dot before name of field and after like that
mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");
I prefer:
config/initializers/string.rb
class String
def number?
Integer(self).is_a?(Integer)
rescue ArgumentError, TypeError
false
end
end
and then:
[218] pry(main)> "123123123".number?
=> true
[220] pry(main)> "123 123 123".gsub(/ /, '').number?
=> true
[222] pry(main)> "123 123 123".number?
=> false
or check phone number:
"+34 123 456 789 2".gsub(/ /, '').number?
BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);
I came across the same problem. I properly installed the MYSQL Workbench 6.x, but faced the connection as below:
I did a bit R&D on this and found that MySQL service in service.msc is not present. To achieve this I created a new connection in MySQL Workbench then manually configured the MySQL Database Server in "System Profile" (see the below picture).
You also need to install MySQL Database Server and set a configuration file path for my.ini
. Now at last test the connection (make sure MySQL service is running in services.msc).
https://github.com/bkdotcom/PHPDebugConsole
Support for all the javascript console methods:
assert, clear, count, error, group, groupCollapsed, groupEnd, info, log, table, trace, time, timeEnd, warn
plus a few more:
alert, groupSummary, groupUncollapse, timeGet
$debug = new \bdk\Debug(array(
'collect' => true,
'output' => true,
'outputAs' => 'script',
));
$debug->log('hello world');
$debug->info('all of the javascript console methods are supported');
\bdk\Debug::_log('can use static methods');
$debug->trace();
$list = array(
array('userId'=>1, 'name'=>'Bob', 'sex'=>'M', 'naughty'=>false),
array('userId'=>10, 'naughty'=>true, 'name'=>'Sally', 'extracol' => 'yes', 'sex'=>'F'),
array('userId'=>2, 'name'=>'Fred', 'sex'=>'M', 'naughty'=>false),
);
$debug->table('people', $list);
this will output the appropriate <script>
tag upon script shutdown
alternatively, you can output as html, chromeLogger, FirePHP, file, plaintext, websockets, etc
upcomming release includes a psr-3 (logger) implementation
It can, because a
is a variable allocated temporarily for the lifetime of its scope (foo
function). After you return from foo
the memory is free and can be overwritten.
What you're doing is described as undefined behavior. The result cannot be predicted.
Let me clarify two points here :
(a = 'b',c)
in function.
The correct order of defining parameter in function are :(a,b,c)
(a = 'b',r= 'j')
(*args)
(**kwargs)
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b)
are positional parameter
(c=none)
is optional parameter
(r="w")
is keyword parameter
(d=[])
is list parameter
(*ae)
is keyword-only
(*ab)
is var-keyword parameter
so first re-arrange your parameters
so second remove this "len1 = hgt"
it's not allowed in python.
keep in mind the difference between argument and parameters.
I configured the app.config
with the tool for EntLib configuration and set up my LoggingConfiguration
block. Then I copied this into the DotNetConfig.xsd
. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.
<xs:element name="loggingConfiguration">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:attribute name="fileName" type="xs:string" use="required" />
<xs:attribute name="footer" type="xs:string" use="required" />
<xs:attribute name="formatter" type="xs:string" use="required" />
<xs:attribute name="header" type="xs:string" use="required" />
<xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
<xs:attribute name="rollInterval" type="xs:string" use="required" />
<xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
<xs:attribute name="timeStampPattern" type="xs:string" use="required" />
<xs:attribute name="listenerDataType" type="xs:string" use="required" />
<xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
<xs:attribute name="filter" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="formatters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="template" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="logFilters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="enabled" type="xs:boolean" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="categorySources">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="specialSources">
<xs:complexType>
<xs:sequence>
<xs:element name="allEvents">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="notProcessed">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="errors">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
<xs:attribute name="defaultCategory" type="xs:string" use="required" />
<xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
</xs:complexType>
</xs:element>
In order to use word-wrap: break-word
, you need to set a width (in px). For example:
div {
width: 250px;
word-wrap: break-word;
}
word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.
//Fields
String myID;
int myversion = 0;
myversion = Integer.valueOf(android.os.Build.VERSION.SDK);
if (myversion < 23) {
TelephonyManager mngr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
myID= mngr.getDeviceId();
}
else
{
myID =
Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
}
Yes, Secure.ANDROID_ID is unique for each device.
<a href="#!">1) Link With Non-directed url</a><br><br>_x000D_
_x000D_
<a href="#!" disabled >2) Link With with disable url</a><br><br>
_x000D_
Working off the answer above, in API 23 you need to add "dangerous" permissions checks as well as checking the system's itself:
public static boolean isLocationServicesAvailable(Context context) {
int locationMode = 0;
String locationProviders;
boolean isAvailable = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
isAvailable = (locationMode != Settings.Secure.LOCATION_MODE_OFF);
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
isAvailable = !TextUtils.isEmpty(locationProviders);
}
boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED);
boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
return isAvailable && (coarsePermissionCheck || finePermissionCheck);
}
The usual way is to use uuencode
for the attachments and echo
for the body:
(uuencode output.txt output.txt; echo "Body of text") | mailx -s 'Subject' [email protected]
For Solaris and AIX, you may need to put the echo
statement first:
(echo "Body of text"; uuencode output.txt output.txt) | mailx -s 'Subject' [email protected]
I fought with this one for a while. My goal was to have a table with headers where the widths of the each header column was the the same as the corresponding body column and was the minimum size necessary to fit the data. also the body data was scrollable underneath header.
I solved this by using divs and not tables. Each "table" was a div with the header being a div of divs and the body being a div of divs. I used the style as indicated by @sushil above. I added a bit of javascript/jQuery to balance the columns. Maybe 20-30 lines.
Unfortunately I lost the code and have to rebuild it. I know this is a bit old, but maybe it will help someone else.
----- 2016-07-04 MariaDB 10.2.1 -- Release Note -- -----
Support for DEFAULT with expressions (MDEV-10134).
----- 2018-10-22 8.0.13 General Availability -- -- -----
MySQL now supports use of expressions as default values in data type specifications. This includes the use of expressions as default values for the BLOB, TEXT, GEOMETRY, and JSON data types, which previously could not be assigned default values at all. For details, see Data Type Default Values.
Solution that worked for me was to create custom Edittext and override following method:
public class MyEditText extends EditText {
private int mPreviousCursorPosition;
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
CharSequence text = getText();
if (text != null) {
if (selStart != selEnd) {
setSelection(mPreviousCursorPosition, mPreviousCursorPosition);
return;
}
}
mPreviousCursorPosition = selStart;
super.onSelectionChanged(selStart, selEnd);
}
}
Just use a onchnage Event
for select box.
<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
<option value="https://www.yahoo.com/" selected>Option1</option>
<option value="https://www.google.co.in/">Option2</option>
<option value="https://www.gmail.com/">Option3</option>
</select>
And if selected option to be loaded at the page load then add some javascript code
<script type="text/javascript">
window.onload = function(){
location.href=document.getElementById("selectbox").value;
}
</script>
for jQuery: Remove the onchange event from <select>
tag
jQuery(function () {
// remove the below comment in case you need chnage on document ready
// location.href=jQuery("#selectbox").val();
jQuery("#selectbox").change(function () {
location.href = jQuery(this).val();
})
})
You can use the relationLoaded method on the model object. This saved my bacon so hopefully it helps someone else. I was given this suggestion when I asked the same question on Laracasts.
If you are using EventBus, it as a method called hasSubscriberForEvent
which can be used to check if an Activity
is focused.
Change the last line to
q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:
The image above is from this blog post.
Some extend
functions in third party libraries are more complex than others. Knockout.js for instance contains a minimally simple one that doesn't have some of the checks that jQuery's does:
function extend(target, source) {
if (source) {
for(var prop in source) {
if(source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
}
return target;
}
Thanks for the research FIRESTICK is a solution for non Android based but there's another one Im using if you guys want to try it let me know...
LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP, PHILCO and TOSHIBA.
Of course.
That is normal and sane behaviour.
Instead of closing and re-opening, you could rewind
the file.
If you use the following code based on @Siddharth Rout's code, you rename the just copied sheet, no matter, if it is activated or not.
Sub Sample()
ThisWorkbook.Sheets(1).Copy After:=Sheets(Sheets.Count)
ThisWorkbook.Sheets(Sheets.Count).Name = "copied sheet!"
End Sub
Another way (although it is a longer code) but it is faster than the above codes. Check it using %timeit function:
df[df.index.isin([1,3])]
PS: You figure out the reason
One more validation without re:
def validip(ip):
return ip.count('.') == 3 and all(0<=int(num)<256 for num in ip.rstrip().split('.'))
for i in ('123.233.42.12','3234.23.453.353','-2.23.24.234','1.2.3.4'):
print i,validip(i)
I have achieved this by a http API node
request which returns required object from node object for HTML
page at client ,
for eg: API: localhost:3000/username
returns logged in user from cache by node App object .
node route file,
app.get('/username', function(req, res) {
res.json({ udata: req.session.user });
});
In modern-day JS, you can get your JSON data by calling ES6's fetch()
on your URL and then using ES7's async/await
to "unpack" the Response object from the fetch to get the JSON data like so:
const getJSON = async url => {
try {
const response = await fetch(url);
if(!response.ok) // check if response worked (no 404 errors etc...)
throw new Error(response.statusText);
const data = await response.json(); // get JSON from the response
return data; // returns a promise, which resolves to this data value
} catch(error) {
return error;
}
}
console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json").then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
_x000D_
The above method can be simplified down to a few lines if you ignore the exception/error handling (usually not recommended as this can lead to unwanted errors):
const getJSON = async url => {
const response = await fetch(url);
return response.json(); // get JSON from the response
}
console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json")
.then(data => console.log(data));
_x000D_
Your syntax is invalid.
string[] arr = new string[5];
That will create arr
, a referenced array of strings, where all elements of this array are null
. (Since strings are reference types)
This array contains the elements from arr[0]
to arr[4]
. The new
operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to null
.
File: logdate.aspx
<%@ Page Language="c#" %>
<%@ Import namespace="System.IO"%>
<%
StreamWriter tsw = File.AppendText(@Server.MapPath("./test.txt"));
tsw.WriteLine("--------------------------------");
tsw.WriteLine(DateTime.Now.ToString());
tsw.Close();
%>
Done
Error : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I solved the issue by passing Extra Args parameter as PutObjectAcl is disabled by company policy.
s3_client.upload_file('./local_file.csv', 'bucket-name', 'path', ExtraArgs={'ServerSideEncryption': 'AES256'})
After a lot of trial and error, I found the pattern UQ(rlang::sym("some string here")))
really useful for working with strings and dplyr verbs. It seems to work in a lot of surprising situations.
Here's an example with mutate
. We want to create a function that adds together two columns, where you pass the function both column names as strings. We can use this pattern, together with the assignment operator :=
, to do this.
## Take column `name1`, add it to column `name2`, and call the result `new_name`
mutate_values <- function(new_name, name1, name2){
mtcars %>%
mutate(UQ(rlang::sym(new_name)) := UQ(rlang::sym(name1)) + UQ(rlang::sym(name2)))
}
mutate_values('test', 'mpg', 'cyl')
The pattern works with other dplyr
functions as well. Here's filter
:
## filter a column by a value
filter_values <- function(name, value){
mtcars %>%
filter(UQ(rlang::sym(name)) != value)
}
filter_values('gear', 4)
Or arrange
:
## transform a variable and then sort by it
arrange_values <- function(name, transform){
mtcars %>%
arrange(UQ(rlang::sym(name)) %>% UQ(rlang::sym(transform)))
}
arrange_values('mpg', 'sin')
For select
, you don't need to use the pattern. Instead you can use !!
:
## select a column
select_name <- function(name){
mtcars %>%
select(!!name)
}
select_name('mpg')
Replace checked="checked"
with checked={true}
. Or you could even shorten it to just checked
.
This is because the expected value type of the checked
prop is a boolean. not a string.
var Klass = function Klass() {
var thus = this;
var somePublicVariable = x
, somePublicVariable2 = x
;
var somePrivateVariable = x
, somePrivateVariable2 = x
;
var privateMethod = (function p() {...}).bind(this);
function publicMethod() {...}
// export precepts
this.var1 = somePublicVariable;
this.method = publicMethod;
return this;
};
First, you may change your preference of adding methods to the instance instead of the constructor's prototype
object. I almost always declare methods inside of the constructor because I use Constructor Hijacking very often for purposes regarding Inheritance & Decorators.
Here's how I decide where which declarations are writ:
this
)var
declarations take precedence over function
declarations{}
and []
)public
declarations take precedence over private
declarationsFunction.prototype.bind
over thus
, self
, vm
, etc
this
from within the Lexical Scope of the Closure Space.Here's why these help:
Constructor Hijackingvar Super = function Super() {
...
this.inherited = true;
...
};
var Klass = function Klass() {
...
// export precepts
Super.apply(this); // extends this with property `inherited`
...
};
Model Design
var Model = function Model(options) {
var options = options || {};
this.id = options.id || this.id || -1;
this.string = options.string || this.string || "";
// ...
return this;
};
var model = new Model({...});
var updated = Model.call(model, { string: 'modified' });
(model === updated === true); // > true
Design Patterns
var Singleton = new (function Singleton() {
var INSTANCE = null;
return function Klass() {
...
// export precepts
...
if (!INSTANCE) INSTANCE = this;
return INSTANCE;
};
})();
var a = new Singleton();
var b = new Singleton();
(a === b === true); // > true
As you can see, I really have no need for thus
since I prefer Function.prototype.bind
(or .call
or .apply
) over thus
. In our Singleton
class, we don't even name it thus
because INSTANCE
conveys more information. For Model
, we return this
so that we can invoke the Constructor using .call
to return the instance we passed into it. Redundantly, we assigned it to the variable updated
, though it is useful in other scenarios.
Alongside, I prefer constructing object-literals using the new
keyword over {brackets}:
var klass = new (function Klass(Base) {
...
// export precepts
Base.apply(this); //
this.override = x;
...
})(Super);
Not Preferred
var klass = Super.apply({
override: x
});
As you can see, the latter has no ability to override its Superclass's "override" property.
If I do add methods to the Class's prototype
object, I prefer an object literal -- with or without using the new
keyword:
Klass.prototype = new Super();
// OR
Klass.prototype = new (function Base() {
...
// export precepts
Base.apply(this);
...
})(Super);
// OR
Klass.prototype = Super.apply({...});
// OR
Klass.prototype = {
method: function m() {...}
};
Not Preferred
Klass.prototype.method = function m() {...};