Why don't you use ACL's to distinguish traffic? on top of my head:
acl go_sslwebserver path bar
use_backend sslwebserver if go_sslwebserver
This goes on top of what Matthew Brown answered.
See the ha docs , search for things like hdr_dom and below to find more ACL options. There are plenty of choices.
Have you had a look at Enumerable.Union
This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.
List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();
// ulist output : 1, 12, 5, 7, 9
$ch = curl_init();
$data = array(
'client_id' => 'xx',
'client_secret' => 'xx',
'redirect_uri' => $x,
'grant_type' => 'xxx',
'code' => $xx,
);
$data = http_build_query($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
In Linux command shell, I did:
chmod 777 <db_folder>
Where contains the database file.
It works. Now I can access my database and make insert queries.
I really hate forms which don't tell me what input(s) is/are missing. So I improve the Dominic's answer - thanks for this.
In the css file set the "borderR" class to border has red color.
$('#<form_id>').submit(function () {
var allIsOk = true;
// Check if empty of not
$(this).find( 'input[type!="hidden"]' ).each(function () {
if ( ! $(this).val() ) {
$(this).addClass('borderR').focus();
allIsOk = false;
}
});
return allIsOk
});
I think this way also a normal way. But sorry, I can't describe in English ((
submitHandler = e => {_x000D_
e.preventDefault()_x000D_
console.log(this.state)_x000D_
fetch('http://localhost:5000/questions',{_x000D_
method: 'POST',_x000D_
headers: {_x000D_
Accept: 'application/json',_x000D_
'Content-Type': 'application/json',_x000D_
},_x000D_
body: JSON.stringify(this.state)_x000D_
}).then(response => {_x000D_
console.log(response)_x000D_
})_x000D_
.catch(error =>{_x000D_
console.log(error)_x000D_
})_x000D_
_x000D_
}
_x000D_
https://googlechrome.github.io/samples/fetch-api/fetch-post.html
fetch('url/questions',{ method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(this.state) }).then(response => { console.log(response) }) .catch(error =>{ console.log(error) })
You can do this with the hex codec. ie:
>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'
I'm assuming you've got a nice fat USB HD and a good connection to the net. You can use apt-mirror to essentially create your own debian mirror.
If you don't want to use a library, this should cover most/all of the same form element types.
function serialize(form) {
if (!form || !form.elements) return;
var serial = [], i, j, first;
var add = function (name, value) {
serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
}
var elems = form.elements;
for (i = 0; i < elems.length; i += 1, first = false) {
if (elems[i].name.length > 0) { /* don't include unnamed elements */
switch (elems[i].type) {
case 'select-one': first = true;
case 'select-multiple':
for (j = 0; j < elems[i].options.length; j += 1)
if (elems[i].options[j].selected) {
add(elems[i].name, elems[i].options[j].value);
if (first) break; /* stop searching for select-one */
}
break;
case 'checkbox':
case 'radio': if (!elems[i].checked) break; /* else continue */
default: add(elems[i].name, elems[i].value); break;
}
}
}
return serial.join('&');
}
export
in sh
and related shells (such as bash
), marks an environment variable to be exported to child-processes, so that the child inherits them.
The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.
For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:
public boolean compare(String s1, String s2) {
return StringUtils.equals(s1, s2);
}
If you dont want to add the library, just copy the source code of the StringUtils#equals
method and apply it when you need it.
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
MYOTHERBATFILE.BAT sync.bat myprogram.ini
You can use pseudo element to get the effect you want like I did in that Fiddle.
CSS:
.title a {
display: block;
width: 340px;
height: 338px;
color: black;
position: relative;
}
.title a:after {
background: url(https://lh3.googleusercontent.com/-p1nr1fkWKUo/T0zUp5CLO3I/AAAAAAAAAWg/jDiQ0cUBuKA/s800/red-pattern.png) repeat;
content: "";
opacity: 0;
width: inherit;
height: inherit;
position: absolute;
top: 0;
left: 0;
/* TRANSISITION */
transition: opacity 1s ease-in-out;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
}
.title a:hover:after{
opacity: 1;
}
HTML:
<div class="title">
<a href="#">HYPERLINK</a>
</div>
You can also move mounted
out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.
function init() {
// Use `this` normally
}
new Vue({
methods:{
init
},
mounted(){
init.call(this)
}
})
Try RGBA, e.g.
div { background-color: rgba(255, 255, 255, 0.5); }
As always, this won't work in every single browser ever written.
String int2string = Integer.toHexString(INTEGERColor); //to ARGB
String HtmlColor = "#"+ int2string.substring(int2string.length() - 6, int2string.length()); // a stupid way to append your color
For posterity, I have a few NullBooleanField
s and here's what I do:
To check if it's True
:
{% if variable %}True{% endif %}
To check if it's False
(note this works because there's only 3 values -- True/False/None):
{% if variable != None %}False{% endif %}
To check if it's None
:
{% if variable == None %}None{% endif %}
I'm not sure why, but I can't do variable == False
, but I can do variable == None
.
Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")
Your method should work fine on a Mac, but on Windows, two additional steps are necessary.
Saving the id_rsa key in this location should solve the permission error.
Given the following dataframe df
and the function complex_function
,
import pandas as pd
def complex_function(x, y=0):
if x > 5 and x > y:
return 1
else:
return 2
df = pd.DataFrame(data={'col1': [1, 4, 6, 2, 7], 'col2': [6, 7, 1, 2, 8]})
col1 col2
0 1 6
1 4 7
2 6 1
3 2 2
4 7 8
there are several solutions to use apply() on only one column. In the following I will explain them in detail.
The straightforward solution is the one from @Fabio Lamanna:
df['col1'] = df['col1'].apply(complex_function)
Output:
col1 col2
0 2 6
1 2 7
2 1 1
3 2 2
4 1 8
Only the first column is modified, the second column is unchanged. The solution is beautiful. It is just one line of code and it reads almost like english: "Take 'col1' and apply the function complex_function to it."
However, if you need data from another column, e.g. 'col2', it's not working. If you want to pass the values of 'col2' to variable y
of the complex_function
, you need something else.
Alternatively, you could use the whole dataframe as described in this or this SO post:
df['col1'] = df.apply(lambda x: complex_function(x['col1']), axis=1)
or if you prefer (like me) a solution without a lambda function:
def apply_complex_function(x): return complex_function(x['col1'])
df['col1'] = df.apply(apply_complex_function, axis=1)
There is a lot going on in this solution that needs to be explained. The apply() function works on pd.Series and pd.DataFrame. But you cannot use df['col1'] = df.apply(complex_function).loc[:, 'col1']
, because it would throw a ValueError
.
Hence, you need to give the information which column to use. To complicate things, the apply() function does only accept callables. To solve this, you need to define a (lambda) function with the column x['col1']
as argument; i.e. we wrap the column information in another function.
Unfortunately, the default value of the axis parameter is zero (axis=0
), which means it will try executing column-wise and not row-wise. This wasn't a problem in the first solution, because we gave apply() a pd.Series. But now the input is a dataframe and we must be explicit (axis=1
). (I marvel how often I forget this.)
Whether you prefer the version with the lambda function or without is subjective. In my opinion the line of code is complicated enough to read even without a lambda function thrown in. You only need the (lambda) function as a wrapper. It is just boiler code. A reader should not be bothered with it.
Now, you can modify this solution easily to take the second column into account:
def apply_complex_function(x): return complex_function(x['col1'], x['col2'])
df['col1'] = df.apply(apply_complex_function, axis=1)
Output:
col1 col2
0 2 6
1 2 7
2 1 1
3 2 2
4 2 8
At index 4 the value has changed from 1 to 2, because the first condition 7 > 5
is true but the second condition 7 > 8
is false.
Note that you only needed to change the first line of code (i.e. the function) and not the second line.
Never put the column information into your function.
def bad_idea(x):
return x['col1'] ** 2
By doing this, you make a general function dependent on a column name! This is a bad idea, because the next time you want to use this function, you cannot. Worse: Maybe you rename a column in a different dataframe just to make it work with your existing function. (Been there, done that. It is a slippery slope!)
Although the OP specifically asked for a solution with apply(), alternative solutions were suggested. For example, the answer of @George Petrov suggested to use map(), the answer of @Thibaut Dubernet proposed assign().
I fully agree that apply() is seldom the best solution, because apply() is not vectorized. It is an element-wise operation with expensive function calling and overhead from pd.Series.
One reason to use apply() is that you want to use an existing function and performance is not an issue. Or your function is so complex that no vectorized version exists.
Another reason to use apply() is in combination with groupby(). Please note that DataFrame.apply() and GroupBy.apply() are different functions.
So it does make sense to consider some alternatives:
map()
only works on pd.Series, but accepts dict and pd.Series as input. Using map() with a function is almost interchangeable with using apply(). It can be faster than apply(). See this SO post for more details. df['col1'] = df['col1'].map(complex_function)
applymap()
is almost identical for dataframes. It does not support pd.Series and it will always return a dataframe. However, it can be faster. The documentation states: "In the current implementation applymap calls func twice on the first column/row to decide whether it can take a fast or slow code path.". But if performance really counts you should seek an alternative route. df['col1'] = df.applymap(complex_function).loc[:, 'col1']
assign()
is not a feasible replacement for apply(). It has a similar behaviour in only the most basic use cases. It does not work with the complex_function
. You still need apply() as you can see in the example below. The main use case for assign() is method chaining, because it gives back the dataframe without changing the original dataframe. df['col1'] = df.assign(col1=df.col1.apply(complex_function))
I only mention it here because it was suggested by other answers, e.g. @durjoy. The list is not exhaustive:
.loc
. My example complex_function
could be refactored in this way.raw=True
parameter. Theoretically, this should improve the performance of apply() if you are just applying a NumPy reduction function, because the overhead of pd.Series is removed. Of course, your function has to accept an ndarray. You have to refactor your function to NumPy. By doing this, you will have a huge performance boost.If the anonymous type causes trouble for you, you can create a simple data class:
public class PermissionsAndPages
{
public ObjectPermissions Permissions {get;set}
public Pages Pages {get;set}
}
and then in your query:
select new PermissionsAndPages { Permissions = op, Page = pg };
Then you can pass this around:
return queryResult.SingleOrDefault(); // as PermissionsAndPages
This is actually pretty simple
Wrap up your vagrant machine
vagrant package --base [machine name as it shows in virtual box] --output /Users/myuser/Documents/Workspace/my.box
copy the box to your remote
init the box on your remote machine by running
vagrant init [machine name as it shows in virtual box] /Users/myuser/Documents/Workspace/my.box
Run vagrant up
Sure.
.orElseThrow(() -> new MyException(someArgument))
For bootstrap 4.0.0-alph.6
npm install [email protected] jquery tether --save
Then after this is done run:
npm install
Now. Open .angular-cli.json file and import bootstrap, jquery, and tether:
"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
]
And now. You ready to go.
First approach with Windows Service is not easy..
A long time ago, I wrote a C# service.
This is the logic of the Service class (tested, works fine):
namespace MyServiceApp
{
public class MyService : ServiceBase
{
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
this.timer = new System.Timers.Timer(30000D); // 30000 milliseconds = 30 seconds
this.timer.AutoReset = true;
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
this.timer.Start();
}
protected override void OnStop()
{
this.timer.Stop();
this.timer = null;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MyServiceApp.ServiceWork.Main(); // my separate static method for do work
}
public MyService()
{
this.ServiceName = "MyService";
}
// service entry point
static void Main()
{
System.ServiceProcess.ServiceBase.Run(new MyService());
}
}
}
I recommend you write your real service work in a separate static method (why not, in a console application...just add reference to it), to simplify debugging and clean service code.
Make sure the interval is enough, and write in log ONLY in OnStart and OnStop overrides.
Hope this helps!
If you're using jQuery, it's as simple as this:
$('form').attr('action', 'myNewActionTarget.html');
Make left-margin: 2em or so will push the whole text including first line to right 2em. Than add text-indent (applicable to first line) as -2em or so.. This brings first line back to start without margin. I tried it for list tags
<style>
ul li{
margin-left: 2em;
text-indent: -2em;
}
</style>
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
Starting with iOS13, there is an Apple-supported way of querying this by using
#include <os/proc.h>
size_t os_proc_available_memory(void)
Introduced here: https://developer.apple.com/videos/play/wwdc2019/606/
Around min 29-ish.
Edit: Adding link to documentation https://developer.apple.com/documentation/os/3191911-os_proc_available_memory?language=objc
The Lazy
Fetch type is by default selected by Hibernate unless you explicitly mark Eager
Fetch type. To be more accurate and concise, difference can be stated as below.
FetchType.LAZY
= This does not load the relationships unless you invoke it via the getter method.
FetchType.EAGER
= This loads all the relationships.
Pros and Cons of these two fetch types.
Lazy initialization
improves performance by avoiding unnecessary computation and reduce memory requirements.
Eager initialization
takes more memory consumption and processing speed is slow.
Having said that, depends on the situation either one of these initialization can be used.
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps
1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option.
3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.
Above process was to make build manually. If You want android studio to automatically Signing Your App
In Android Studio, you can configure your project to sign your release APK automatically during the build process:
On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. Figure 4. Create a signing configuration in Android Studio.
Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. Figure 5. Select a signing configuration in Android Studio.
4:Most Important thing that make debuggable=false at gradle.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard- android.txt'), 'proguard-rules.txt'
debuggable false
jniDebuggable false
renderscriptDebuggable false
zipAlignEnabled true
}
}
visit for more in info developer.android.com
In angular 8:
//for catch:
import { catchError } from 'rxjs/operators';
//for throw:
import { Observable, throwError } from 'rxjs';
//and code should be written like this.
getEmployees(): Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
}
erroHandler(error: HttpErrorResponse) {
return throwError(error.message || 'server Error');
}
If you're looking to do this XCode 5+, I found this is the easiest method:
Install ios-sim:
npm install -g ios-sim
Then simply execute:
ios-sim launch ./mySample.app --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPhone-6
In which you can switch up your device type. Simple, fast, and it actually works.
ALTER TABLE TABLE_NAME ADD (COLUMN_NAME_NEW varchar2(4000 char));
update TABLE_NAME set COLUMN_NAME_NEW = COLUMN_NAME;
ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
ALTER TABLE TABLE_NAME rename column COLUMN_NAME_NEW to COLUMN_NAME;
The short answer is adb is used via command line. find adb.exe on your machine, add it to the path and use it from cmd on windows.
"adb devices" will give you a list of devices adb can talk to. your emulation platform should be on the list. just type adb to get a list of commands and what they do.
What about using a tabular inside \author{}
, just like in IEEE macros:
\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c}
I. M. Author & M. Y. Coauthor \\
My Department & Coauthor Department \\
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle
\end{document}
This will produce two columns authors with any documentclass
.
Results:
Maybe you can add a step to the generate-sources phase that moves the folder?
Adding my scenario and solution in case it helps someone else. I encountered similar case when using RESTful APIs. My Web server hosting HTML/Script/CSS files and Application Server exposing APIs were hosted on same domain. However the path was different.
web server - mydomain/webpages/abc.html
used abc.js which set cookie named mycookie
app server - mydomain/webapis/servicename.
to which api calls were made
I was expecting the cookie in mydomain/webapis/servicename and tried reading it but it was not being sent. After reading comment from the answer, I checked in browser's development tool that mycookie's path was set to "/webpages" and hence not available in service call to
mydomain/webapis/servicename
So While setting cookie from jquery, this is what I did -
$.cookie("mycookie","mayvalue",{**path:'/'**});
PCDATA
is text that will be parsed by a parser. Tags inside the text
will be treated as markup and entities will be expanded. CDATA
is text that will not be parsed by a parser. Tags inside the text will
not be treated as markup and entities will not be expanded.By default, everything is PCDATA
. In the following example, ignoring the root, <bar>
will be parsed, and it'll have no content, but one child.
<?xml version="1.0"?>
<foo>
<bar><test>content!</test></bar>
</foo>
When we want to specify that an element will only contain text, and no child elements, we use the keyword PCDATA
, because this keyword specifies that the element must contain parsable character data – that is , any text except the characters less-than (<
) , greater-than (>
) , ampersand (&
), quote('
) and double quote ("
).
In the next example, <bar>
contains CDATA
. Its content will not be parsed and is thus <test>content!</test>
.
<?xml version="1.0"?>
<foo>
<bar><![CDATA[<test>content!</test>]]></bar>
</foo>
There are several content models in SGML. The #PCDATA
content model says that an element may contain plain text. The "parsed" part of it means that markup (including PIs, comments and SGML directives) in it is parsed instead of displayed as raw text. It also means that entity references are replaced.
Another type of content model allowing plain text contents is CDATA
. In XML, the element content model may not implicitly be set to CDATA
, but in SGML, it means that markup and entity references are ignored in the contents of the element. In attributes of CDATA
type however, entity references are replaced.
In XML, #PCDATA
is the only plain text content model. You use it if you at all want to allow text contents in the element. The CDATA
content model may be used explicitly through the CDATA
block markup in #PCDATA
, but element contents may not be defined as CDATA
per default.
In a DTD, the type of an attribute that contains text must be CDATA
. The CDATA
keyword in an attribute declaration has a different meaning than the CDATA
section in an XML document. In a CDATA
section all characters are legal (including <
,>
,&
,'
and "
characters), except the ]]>
end tag.
#PCDATA
is not appropriate for the type of an attribute. It is used for the type of "leaf" text.
#PCDATA
is prepended by a hash in the content model to distinguish this keyword from an element named PCDATA
(which would be perfectly legal).
Through SSMS, I created a new schema by:
I found this post to change the schema, but was also getting the same permissions error when trying to change to the new schema. I have several databases listed in my SSMS, so I just tried specifying the database and it worked:
USE (yourservername)
ALTER SCHEMA exe TRANSFER dbo.Employees
If you need to concatenate paths with quotes, you can use =
to replace quotes in a variable. This does not require you to know if the path already contains quotes or not. If there are no quotes, nothing is changed.
@echo off
rem Paths to combine
set DIRECTORY="C:\Directory with spaces"
set FILENAME="sub directory\filename.txt"
rem Combine two paths
set COMBINED="%DIRECTORY:"=%\%FILENAME:"=%"
echo %COMBINED%
rem This is just to illustrate how the = operator works
set DIR_WITHOUT_SPACES=%DIRECTORY:"=%
echo %DIR_WITHOUT_SPACES%
Based in the answer by WhoIsNinja:
This code will output both into the Console and into a Log string that can be saved into a file, either by appending lines to it or by overwriting it.
The default name for the log file is 'Log.txt' and is saved under the Application path.
public static class Logger
{
public static StringBuilder LogString = new StringBuilder();
public static void WriteLine(string str)
{
Console.WriteLine(str);
LogString.Append(str).Append(Environment.NewLine);
}
public static void Write(string str)
{
Console.Write(str);
LogString.Append(str);
}
public static void SaveLog(bool Append = false, string Path = "./Log.txt")
{
if (LogString != null && LogString.Length > 0)
{
if (Append)
{
using (StreamWriter file = System.IO.File.AppendText(Path))
{
file.Write(LogString.ToString());
file.Close();
file.Dispose();
}
}
else
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Path))
{
file.Write(LogString.ToString());
file.Close();
file.Dispose();
}
}
}
}
}
Then you can use it like this:
Logger.WriteLine("==========================================================");
Logger.Write("Loading 'AttendPunch'".PadRight(35, '.'));
Logger.WriteLine("OK.");
Logger.SaveLog(true); //<- default 'false', 'true' Append the log to an existing file.
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];
When you start the app from the GUI, adb logcat
might show you the corresponding action/category/component:
$ adb logcat
[...]
I/ActivityManager( 1607): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.android.browser/.BrowserActivity} from pid 1792
[...]
Try:
function is_numeric(str){
try {
return isFinite(str)
}
catch(err) {
return false
}
}
Aliases can be used only if they were introduced in the preceding step. So aliases in the SELECT
clause can be used in the ORDER BY
but not the GROUP BY
clause.
Reference: Microsoft T-SQL Documentation for further reading.
FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP
Hope this helps.
Create a custom class, e.g. .custom-btn
. Note that to override jQM styles without using !important
, CSS hierarchy should be respected. .ui-btn.custom-class
or .ui-input-btn.custom-class
.
.ui-input-btn.custom-btn {
border:1px solid red;
text-decoration:none;
font-family:helvetica;
color:red;
background:url(img.png) repeat-x;
}
Add a data-wrapper-class
to input
. The custom class will be added to input
wrapping div.
<input type="button" data-wrapper-class="custom-btn">
Input
button is wrapped by a DIV with class ui-btn
. You need to select that div and the input[type="submit"]
. Using !important
is essential to override Jquery Mobile styles.
div.ui-btn, input[type="submit"] {
border:1px solid red !important;
text-decoration:none !important;
font-family:helvetica !important;
color:red !important;
background:url(../images/btn_hover.png) repeat-x !important;
}
I don't think desc
takes an na.rm
argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NA
s, use na.omit
(base) or tidyr::drop_na
:
outcome.df %>%
na.omit() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
library(tidyr)
outcome.df %>%
drop_na() %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
If you only want to remove NA
s from the HeartAttackDeath column, filter with is.na
, or use tidyr::drop_na
:
outcome.df %>%
filter(!is.na(HeartAttackDeath)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
outcome.df %>%
drop_na(HeartAttackDeath) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
As pointed out at the dupe, complete.cases
can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:
outcome.df %>%
filter(complete.cases(.)) %>%
group_by(Hospital, State) %>%
arrange(desc(HeartAttackDeath)) %>%
head()
package test2;
public class main {
public static void main(String[] args) {
vehical vehical1 = new vehical("civic", "black","2012");
System.out.println(vehical1.name+"\n"+vehical1.colour+"\n"+vehical1.model);
}
}
This can be achieved with the writing-mode
property. If you set an element's writing-mode
to a vertical writing mode, such as vertical-lr
, its descendants' percentage values for padding and margin, in both dimensions, become relative to height instead of width.
From the spec:
. . . percentages on the margin and padding properties, which are always calculated with respect to the containing block width in CSS2.1, are calculated with respect to the inline size of the containing block in CSS3.
The definition of inline size:
A measurement in the inline dimension: refers to the physical width (horizontal dimension) in horizontal writing modes, and to the physical height (vertical dimension) in vertical writing modes.
Example, with a resizable element, where horizontal margins are relative to width and vertical margins are relative to height.
.resize {_x000D_
width: 400px;_x000D_
height: 200px;_x000D_
resize: both;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
height: 100%;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.middle {_x000D_
writing-mode: vertical-lr;_x000D_
margin: 0 10%;_x000D_
width: 80%;_x000D_
height: 100%;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
writing-mode: horizontal-tb;_x000D_
margin: 10% 0;_x000D_
width: 100%;_x000D_
height: 80%;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="resize">_x000D_
<div class="outer">_x000D_
<div class="middle">_x000D_
<div class="inner"></div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Using a vertical writing mode can be particularly useful in circumstances where you want the aspect ratio of an element to remain constant, but want its size to scale in correlation to its height instead of width.
Almost everybody answered this. My version of printing any rails exception into logs would be:
begin
some_statement
rescue => e
puts "Exception Occurred #{e}. Message: #{e.message}. Backtrace: \n #{e.backtrace.join("\n")}"
Rails.logger.error "Exception Occurred #{e}. Message: #{e.message}. Backtrace: \n #{e.backtrace.join("\n")}"
end
RUN /bin/sh -c "apk add --no-cache bash"
worked for me.
SELECT * FROM myTable WHERE sign (col1)!=0
ofcourse sign(0) is zero, but then you could restrict you query to...
SELECT * FROM myTable WHERE sign (col1)!=0 or col1=0
UPDATE: This is not 100% reliable, because "1abc" would return sign of 1, but "ab1c" would return zero... so this could only work for text that does not begins with numbers.
from subprocess import Popen
Popen('python filename.py')
You were missing a few important sonar properties, Here is a sample from one of my builds:
sonar.jdbc.dialect=mssql
sonar.projectKey=projectname
sonar.projectName=Project Name
sonar.projectVersion=1.0
sonar.sources=src
sonar.language=java
sonar.binaries=build/classes
sonar.tests=junit
sonar.dynamicAnalysis=reuseReports
sonar.junit.reportsPath=build/test-reports
sonar.java.coveragePlugin=jacoco
sonar.jacoco.reportPath=build/test-reports/jacoco.exec
The error in Jenkins console output can be pretty useful for getting code coverage to work.
Project coverage is set to 0% since there is no directories with classes.
Indicates that you have not set the Sonar.Binaries property correctly
No information about coverage per test
Indicates you have not set the Sonar.Tests property properly
Coverage information was not collected. Perhaps you forget to include debug information into compiled classes? Indicates that the sonar.binaries property was set correctly, but those files were not compiled in debug mode, and they need to be
Localization of date string:
Based on redsonic's post:
private String localizeDate(String inputdate, Locale locale) {
Date date = new Date();
SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd-MMM-yyyy", locale);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
try {
date = dateFormat.parse(inputdate);
} catch (ParseException e) {
log.warn("Input date was not correct. Can not localize it.");
return inputdate;
}
return dateFormatCN.format(date);
}
String localizedDate = localizeDate("05-Sep-2013", new Locale("zh","CN"));
will be like 05-??-2013
Request.Url.PathAndQuery
should work perfectly, especially if you only want the relative Uri (but keeping querystrings)
It's just PHP, not HTML.
It parses all HTML fields with [] into an array.
So you can have
<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />
and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:
echo $_POST['food'][0]; // would output first checkbox selected
or to see all values selected:
foreach( $_POST['food'] as $value ) {
print $value;
}
Anyhow, don't think there is a specific name for it
The reason why it is closing is because the program is not running anymore, simply add any sort of loop or input to fix this (or you could just run it through idle.)
From Java How to Program about abstract classes:
Because they’re used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.
To answer your question "What is the reason to use interfaces?":
An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.
As opposed to an interface:
An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.
So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)
There is no need for jQuery here, regular JavaScript will do:
var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);
Or, the .split()
and .pop()
version:
var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();
Or, the regex version (several variants of this):
var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
Using FETCH FIRST [n] ROWS ONLY
:
SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY
FROM EMP
ORDER BY SALARY DESC
FETCH FIRST 20 ROWS ONLY;
To get ranges, you'd have to use ROW_NUMBER()
(since v5r4) and use that within the WHERE
clause: (stolen from here: http://www.justskins.com/forums/db2-select-how-to-123209.html)
SELECT code, name, address
FROM (
SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address
FROM contacts
WHERE name LIKE '%Bob%'
) AS t
WHERE t.rid BETWEEN 20 AND 25;
<%:
Html.DropDownListFor(
model => model.Color,
new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"}
},
"value",
"text",
Model.Color
)
)
%>
or you can write no classes, put something like this directly to the view.
In Bash, you can use pseudo-device files which can open a TCP connection to the associated socket. The syntax is /dev/$tcp_udp/$host_ip/$port
.
Here is simple example to test whether Memcached is running:
</dev/tcp/localhost/11211 && echo Port open || echo Port closed
Here is another test to see if specific website is accessible:
$ echo "HEAD / HTTP/1.0" > /dev/tcp/example.com/80 && echo Connection successful.
Connection successful.
For more info, check: Advanced Bash-Scripting Guide: Chapter 29. /dev
and /proc
.
Related: Test if a port on a remote system is reachable (without telnet) at SuperUser.
For more examples, see: How to open a TCP/UDP socket in a bash shell (article).
Windows doesn't support SSH/SCP/SFTP
natively. Are you running an SSH server application on that Windows server? If so, one of the configuration options is probably where the root is, and you would specify paths relative to that root. In any case, check the documentation for the SSH server application you are running in Windows.
Alternatively, use smbclient
to push the file to a Windows share.
A stack is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in reverse order of their time of storage, i.e. the latest element stored is the next element to be retrieved. A stack is sometimes referred to as a Last-In-First-Out (LIFO) or First-In-Last-Out (FILO) structure. Elements previously stored cannot be retrieved until the latest element (usually referred to as the 'top' element) has been retrieved.
A queue is a collection of elements, which can be stored and retrieved one at a time. Elements are retrieved in order of their time of storage, i.e. the first element stored is the next element to be retrieved. A queue is sometimes referred to as a First-In-First-Out (FIFO) or Last-In-Last-Out (LILO) structure. Elements subsequently stored cannot be retrieved until the first element (usually referred to as the 'front' element) has been retrieved.
According to the documentation Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. Important
an internal redirect to the uri specified in the last parameter is made.
So in last parameter you should add your page or code if first two parameters returns false.
location / {
try_files $uri $uri/index.html index.html;
}
One option is to create a script file.
Right click on the database -> Tasks -> Generate Scripts
Then you can select all the stored procedures and generate the script with all the sps. So you can find the reference from there.
Or
-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.sql_modules
WHERE definition LIKE '%' + 'CreatedDate' + '%'
GO
-- Search in Stored Procedure Only
SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'CreatedDate' + '%'
GO
Source SQL SERVER – Find Column Used in Stored Procedure – Search Stored Procedure for Column Name
We have various structural/syntactical difference between interface and abstract class. Some more differences are
[1] Scenario based difference:
Abstract classes are used in scenarios when we want to restrict the user to create object of parent class AND we believe there will be more abstract methods will be added in future.
Interface has to be used when we are sure there can be no more abstract method left to be provided. Then only an interface is published.
[2] Conceptual difference:
"Do we need to provide more abstract methods in future" if YES make it abstract class and if NO make it Interface.
(Most appropriate and valid till java 1.7)
In Kotlin you can try this way to handle getActivity() null condition.
activity.let { // activity == getActivity() in java
//your code here
}
It will check activity is null or not and if not null then execute inner code.
Direct value
should work just fine:
var sel = document.getElementsByName('item');
var sv = sel.value;
alert(sv);
The only reason your code might fail is when there is no item selected, then the selectedIndex
returns -1 and the code breaks.
Beside int float string etc., you can put extra data to .second when using diff. types like:
std::map<unsigned long long int, glm::ivec2> voxels_corners;
std::map<unsigned long long int, glm::ivec2>::iterator it_corners;
or
struct voxel_map {
int x,i;
};
std::map<unsigned long long int, voxel_map> voxels_corners;
std::map<unsigned long long int, voxel_map>::iterator it_corners;
when
long long unsigned int index_first=some_key; // llu in this case...
int i=0;
voxels_corners.insert(std::make_pair(index_first,glm::ivec2(1,i++)));
or
long long unsigned int index_first=some_key;
int index_counter=0;
voxel_map one;
one.x=1;
one.i=index_counter++;
voxels_corners.insert(std::make_pair(index_first,one));
with right type || structure you can put anything in the .second including a index number that is incremented when doing an insert.
instead of
it_corners - _corners.begin()
or
std::distance(it_corners.begin(), it_corners)
after
it_corners = voxels_corners.find(index_first+bdif_x+x_z);
the index is simply:
int vertice_index = it_corners->second.y;
when using the glm::ivec2 type
or
int vertice_index = it_corners->second.i;
in case of the structure data type
But for any future bypassers you could mention that df = df[df.line_race != 0]
doesn't do anything when trying to filter for None
/missing values.
Does work:
df = df[df.line_race != 0]
Doesn't do anything:
df = df[df.line_race != None]
Does work:
df = df[df.line_race.notnull()]
If you just want to md5 hash a simple string I found this works for me.
var crypto = require('crypto');
var name = 'braitsch';
var hash = crypto.createHash('md5').update(name).digest('hex');
console.log(hash); // 9b74c9897bac770ffc029102a200c5de
I wrote a short C program that returns the environment variables passed from nginx to the fastCGI application.
#include <stdlib.h>
#include <fcgi_stdio.h>
extern char **environ;
int main(int argc, char **argv) {
char *envvar;
int i;
int count = 0;
while(FCGI_Accept() >= 0) {
printf("Content-type: text/html\n\n"
"<html><head><title>FastCGI Call Debug Tool</title></head>\n"
"<body><h1>FastCGI Call Debugging Tool</h1>\n"
"<p>Request number %d running on host <i>%s</i></p>\n"
"<h2>Environment Variables</h2><p>\n",
++count, getenv("SERVER_NAME"));
i = 0;
envvar = environ[i];
while (envvar != NULL) {
printf("%s<br/>",envvar);
envvar = environ[++i];
}
printf("</p></body></html>\n");
}
return 0;
}
Save this to a file, e.g. fcgi_debug.c
To compile it, first install gcc
and libfcgi-dev
, then run:
gcc -o fcgi_debug fcgi_debug.c -lfcgi
To run it, install spawn-fcgi
, then run:
spawn-fcgi -p 3000 -f /path/to/fcgi_debug
Then, change your nginx fcgi config to point to the debug program:
fastcgi_pass 127.0.0.1:3000;
Restart nginx, refresh the page, and you should see all the parameters appear in your browser for you to debug! :-)
There are no perfect answers provided here except Asaf's answer which doesn't provide any code nor any example, so I would like to contribute mine...
Inorder to make vertical-align: middle;
work, you need to use display: table;
for your ul
element and display: table-cell;
for li
elements and than you can use vertical-align: middle;
for li
elements.
You don't need to provide any explicit margins
, paddings
to make your text vertically middle.
ul.catBlock{
display: table;
width:960px;
height: 270px;
border:1px solid #ccc;
}
ul.catBlock li {
list-style: none;
display: table-cell;
text-align: center;
width:160px;
vertical-align: middle;
}
ul.catBlock li a {
display: block;
}
Sorry to revive a dead thread but i solved this on VS2017 by deleting the project template cache and item template cache folders in
%localappdata%\Microsoft\VisualStudio\[BUILD]
Then resetting the visual studio settings via
Tools>Import and export settings>reset all settings
Also ive heard turning off "Lightweight solution load for all projects" can help.
You can programatically change it by setting the system property:
public class App {
public static void main(String[] args) {
System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);
log.trace("trace");
log.debug("debug");
log.info("info");
log.warn("warning");
log.error("error");
}
}
The log levels are ERROR > WARN > INFO > DEBUG > TRACE.
Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.
Just found base64-arraybuffer, a small npm package with incredibly high usage, 5M downloads last month (2017-08).
https://www.npmjs.com/package/base64-arraybuffer
For anyone looking for something of a best standard solution, this may be it.
I had the same problem, and it turned out I hadn't installed the library.
this link was super usefull.
use this one:
DecimalFormat form = new DecimalFormat("0.00");
etToll.setText(form.format(tvTotalAmount) );
Note: Data must be in decimal format (tvTotalAmount)
isFinite(String(n)) returns true for n=0 or '0', '1.1' or 1.1,
but false for '1 dog' or '1,2,3,4', +- Infinity and any NaN values.
Parse Querystring into a NameValueCollection. Remove an item. And use the toString to convert it back to a querystring.
using System.Collections.Specialized;
NameValueCollection filteredQueryString = System.Web.HttpUtility.ParseQueryString(Request.QueryString.ToString());
filteredQueryString.Remove("appKey");
var queryString = '?'+ filteredQueryString.ToString();
I had the same problem today. I've found this link, where you can try 3 solutions. First solution helped for me.
based on @mister_lucky answer use with jquery:
$('#unobtrusive').on('click',function (e) {
e.preventDefault(); //optional
//some code
});
Html Code:
<a id="unobtrusive" href="http://jquery.com">jquery</a>
Look for them under COM when trying to add the references. You should find the reference below, and possibly Microsoft Outlook 15.0 Object Library, if you need that. There are similar libraries for Word, Excel, etc.:
Update: The Object Library should contain the Interop stuff. Try to add this to a source file, and see if it does not find what you need:
using Microsoft.Office.Interop.Outlook;
You have to use CURL
function does_url_exists($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 200) {
$status = true;
} else {
$status = false;
}
curl_close($ch);
return $status;
}
If you want to find the rows
that have any of the values in a vector, one option is to loop the vector (lapply(v1,..)
), create a logical index of (TRUE/FALSE) with (==
). Use Reduce
and OR (|
) to reduce the list to a single logical matrix by checking the corresponding elements. Sum the rows (rowSums
), double negate (!!
) to get the rows with any matches.
indx1 <- !!rowSums(Reduce(`|`, lapply(v1, `==`, df)), na.rm=TRUE)
Or vectorise and get the row indices with which
with arr.ind=TRUE
indx2 <- unique(which(Vectorize(function(x) x %in% v1)(df),
arr.ind=TRUE)[,1])
I didn't use @kristang's solution as it is giving me errors. Based on a 1000x500
matrix, @konvas's solution is the most efficient (so far). But, this may vary if the number of rows are increased
val <- paste0('M0', 1:1000)
set.seed(24)
df1 <- as.data.frame(matrix(sample(c(val, NA), 1000*500,
replace=TRUE), ncol=500), stringsAsFactors=FALSE)
set.seed(356)
v1 <- sample(val, 200, replace=FALSE)
konvas <- function() {apply(df1, 1, function(r) any(r %in% v1))}
akrun1 <- function() {!!rowSums(Reduce(`|`, lapply(v1, `==`, df1)),
na.rm=TRUE)}
akrun2 <- function() {unique(which(Vectorize(function(x) x %in%
v1)(df1),arr.ind=TRUE)[,1])}
library(microbenchmark)
microbenchmark(konvas(), akrun1(), akrun2(), unit='relative', times=20L)
#Unit: relative
# expr min lq mean median uq max neval
# konvas() 1.00000 1.000000 1.000000 1.000000 1.000000 1.00000 20
# akrun1() 160.08749 147.642721 125.085200 134.491722 151.454441 52.22737 20
# akrun2() 5.85611 5.641451 4.676836 5.330067 5.269937 2.22255 20
# cld
# a
# b
# a
For ncol = 10
, the results are slighjtly different:
expr min lq mean median uq max neval
konvas() 3.116722 3.081584 2.90660 2.983618 2.998343 2.394908 20
akrun1() 27.587827 26.554422 22.91664 23.628950 21.892466 18.305376 20
akrun2() 1.000000 1.000000 1.00000 1.000000 1.000000 1.000000 20
v1 <- c('M017', 'M018')
df <- structure(list(datetime = c("04.10.2009 01:24:51",
"04.10.2009 01:24:53",
"04.10.2009 01:24:54", "04.10.2009 01:25:06", "04.10.2009 01:25:07",
"04.10.2009 01:26:07", "04.10.2009 01:26:27", "04.10.2009 01:27:23",
"04.10.2009 01:27:30", "04.10.2009 01:27:32", "04.10.2009 01:27:34"
), col1 = c("M017", "M018", "M051", "<NA>", "<NA>", "<NA>", "<NA>",
"<NA>", "<NA>", "M017", "M051"), col2 = c("<NA>", "<NA>", "<NA>",
"M016", "M015", "M017", "M017", "M017", "M017", "<NA>", "<NA>"
), col3 = c("<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>",
"<NA>", "<NA>", "<NA>", "<NA>"), col4 = c(NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA)), .Names = c("datetime", "col1", "col2",
"col3", "col4"), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11"))
Here is a refactored and simplified version of the @sasha_gud answer:
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
public static ulong GetDiskFreeSpace(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
ulong dummy = 0;
if (!GetDiskFreeSpaceEx(path, out ulong freeSpace, out dummy, out dummy))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return freeSpace;
}
Copy your source folder to somedir
:
cp -r srcdir
somedir
Remove all unneeded files:
find somedir -name '.svn' -exec rm -rf {} \+
launch scp from somedir
Control Panel >> Windows Firewall >> Turn windows firewall on or off >> Turn off.
Advanced settings >> Domain profile >> Windows firewall properties >> Firewall status >> Off.
When I tried to install a new ionic app, I got the same error as follows, I tried many sources and found the mistake made in User Environment and System Environment unnecessarily included the PROXY value. I removed the ```user variables http://host:port PROXY
system Variables http_proxy http://username:password@host:port ```` and now it is working fine without trouble.
[ERROR] Network connectivity error occurred, are you offline?
If you are behind a firewall and need to configure proxy settings, see: https://ion.link/cli-proxy-docs
Error: getaddrinfo ENOTFOUND host host:80
As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach
function.
var element = $('#childNode').detach();
$('#parentNode').append(element);
Edit:
Igor Mukhin suggested an even shorter version in the comments below:
$("#childNode").detach().appendTo("#parentNode");
If they have error pages enabled, you can go to a non-existent page and look at the bottom of the 404 page.
num < 0 // number is negative
When you want your include to know what file it is in (ie. what script name was actually requested), use:
basename($_SERVER["SCRIPT_FILENAME"], '.php')
Because when you are writing to a file you usually know its name.
Edit: As noted by Alec Teal, if you use symlinks it will show the symlink name instead.
If you really should use Double instead of double you even can get the int Value of Double by calling:
Double d = new Double(1.23);
int i = d.intValue();
Else its already described by Peter Lawreys answer.
Thank you, that worked! But I replaced this
AllowOverride AuthConfig Indexes
with that
AllowOverride All
Otherwise, the .htaccess didn't work: I got problems with the RewriteEngine and the error message "RewriteEngine not allowed here".
extrac Guid values from database functions:
#region GUID
public static Guid GGuid(SqlDataReader reader, string field)
{
try
{
return reader[field] == DBNull.Value ? Guid.Empty : (Guid)reader[field];
}
catch { return Guid.Empty; }
}
public static Guid GGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
return reader[ordinal] == DBNull.Value ? Guid.Empty : (Guid)reader[ordinal];
}
catch { return Guid.Empty; }
}
public static Guid? NGuid(SqlDataReader reader, string field)
{
try
{
if (reader[field] == DBNull.Value) return (Guid?)null; else return (Guid)reader[field];
}
catch { return (Guid?)null; }
}
public static Guid? NGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
if (reader[ordinal] == DBNull.Value) return (Guid?)null; else return (Guid)reader[ordinal];
}
catch { return (Guid?)null; }
}
#endregion
The function move.CompleteMove(events)
that you use within your class probably doesn't contain a return
statement. So nothing is returned to self.values
(==> None). Use return
in move.CompleteMove(events)
to return whatever you want to store in self.values
and it should work. Hope this helps.
Use .valid()
from the jQuery Validation plugin:
$("#form_id").valid();
Checks whether the selected form is valid or whether all selected elements are valid. validate() needs to be called on the form before checking it using this method.
Where the form with id='form_id'
is a form that has already had .validate()
called on it.
To be honest I think that it's really shame that there is no simple checkbox in storyboard to say that you want to resize buttons to accommodate the text. Well... whatever.
Here is the simplest solution using storyboard.
Place UILabel inside UIView. Set constraints to attach it to edges of UIView.
Place your UIButton inside UIView. Set the same constraints to attach it to the edges of UIView.
Set up the outlets.
@IBOutlet var button: UIButton!
@IBOutlet var textOnTheButton: UILabel!
let someTitle = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
override func viewDidLoad() {
super.viewDidLoad()
textOnTheButton.text = someTitle
button.setTitle(someTitle, for: .normal)
button.titleLabel?.numberOfLines = 0
}
Run this command to change .cert
file to .p12
:
openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt
Where server.key
is the server key and server.cert
is a CA issue cert or a self sign cert file.
object count =dtFoo.Compute("count(IsActive)", "IsActive='Y'");
Use numpy.apply_along_axis()
. Assuming your matrix is 2D, you can use like:
import numpy as np
mymatrix = np.matrix([[11,12,13],
[21,22,23],
[31,32,33]])
def myfunction( x ):
return sum(x)
print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]
Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{
@Autowired
MyService service;
...
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException
{
// Do something with the context here
}
}
Solved the issue for me :
Range(Cells(1, 1), Cells(100, 1)).Select
For Each xCell In Selection
xCell.Value = CDate(xCell.Value)
Next xCell
If you're passing literals in code, what's stopping you from simply declaring it ahead of time?
byte b = 0; //Set to desired value.
f(b);
For me, a simple Product -> Clean worked great
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
It seems that the original test case is wrong.
I can confirm that the selector #my_parent_element *
works with unbind()
.
Let's take the following html as an example:
<div id="#my_parent_element">
<div class="div1">
<div class="div2">hello</div>
<div class="div3">my</div>
</div>
<div class="div4">name</div>
<div class="div5">
<div class="div6">is</div>
<div class="div7">
<div class="div8">marco</div>
<div class="div9">(try and click on any word)!</div>
</div>
</div>
</div>
<button class="unbind">Now, click me and try again</button>
And the jquery bit:
$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
alert('hi!');
})
$('button.unbind').click(function() {
$('#my_parent_element *').unbind('click');
})
You can try it here: http://jsfiddle.net/fLvwbazk/7/
If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:
$accounts = Array(
'@jonathansampson',
'@f12devtools',
'@ieanswers'
);
$index = count($accounts);
while($index) {
echo sprintf("<li>%s</li>", $accounts[--$index]);
}
The above sets $index
to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.
You could also leverage the array_reverse
function to invert the values of your array, allowing you to access them in reverse order:
$accounts = Array(
'@jonathansampson',
'@f12devtools',
'@ieanswers'
);
foreach ( array_reverse($accounts) as $account ) {
echo sprintf("<li>%s</li>", $account);
}
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
Also known as Frozen Binaries but not the same as as the output of a true compiler- they run byte code through a virtual machine (PVM). Run the same as a compiled program just larger because the program is being compiled along with the PVM. Py2exe can freeze standalone programs that use the tkinter, PMW, wxPython, and PyGTK GUI libraties; programs that use the pygame game programming toolkit; win32com client programs; and more. The Stackless Python system is a standard CPython implementation variant that does not save state on the C language call stack. This makes Python more easy to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines. Other systems of study that are working on future development: Pyrex is working on the Cython system, the Parrot project, the PyPy is working on replacing the PVM altogether, and of course the founder of Python is working with Google to get Python to run 5 times faster than C with the Unladen Swallow project. In short, py2exe is the easiest and Cython is more efficient for now until these projects improve the Python Virtual Machine (PVM) for standalone files.
This is for Nikola.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
break;
}
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
String text = "{ "key1":{ "key2":{ "key3":{ "key4":[ { "fieldValue":"Empty", "fieldName":"Enter Field Name 1" }, { "fieldValue":"Empty", "fieldName":"Enter Field Name 2" } ] } } } }";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
}
If it's help bro,Do not forget to up for my reputation)))
I tried @Jack's answer above, the logo did appear however the image occupied the whole Navigation Bar. I wanted it to fit.
Swift 4, Xcode 9.2
1.Assign value to navigation controller, UIImage. Adjust size by dividing frame and Image size.
func addNavBarImage() {
let navController = navigationController!
let image = UIImage(named: "logo-signIn6.png") //Your logo url here
let imageView = UIImageView(image: image)
let bannerWidth = navController.navigationBar.frame.size.width
let bannerHeight = navController.navigationBar.frame.size.height
let bannerX = bannerWidth / 2 - (image?.size.width)! / 2
let bannerY = bannerHeight / 2 - (image?.size.height)! / 2
imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
imageView.contentMode = .scaleAspectFit
navigationItem.titleView = imageView
}
Add the function right under viewDidLoad()
addNavBarImage()
Note on the image asset. Before uploading, I adjusted the logo with extra margins rather than cropped at the edges.
Final result:
I guess all other options would be more cryptic. For those who like readable and non-cryptic code:
IF "%ID%"=="0" (
REM do something
) ELSE IF "%ID%"=="1" (
REM do something else
) ELSE IF "%ID%"=="2" (
REM do another thing
) ELSE (
REM default case...
)
It's like an anecdote:
Magician: Put the egg under the hat, do the magic passes ... Remove the hat and ... get the same egg but in the side view ...
The IF
ELSE
solution isn't that bad. It's almost as good as python's if
elif
else
. More cryptic 'eggs' can be found here.
The easiest way is to just use Underscore.js:
keys
_.keys(object) Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3}); => ["one", "two", "three"]
Yes, you need an extra library, but it's so easy!
It's as easy as it looks.
14:27:05 ~$ mkdir gittests
14:27:11 ~$ cd gittests/
14:27:13 ~/gittests$ mkdir localrepo
14:27:20 ~/gittests$ cd localrepo/
14:27:21 ~/gittests/localrepo$ git init
Initialized empty Git repository in /home/andwed/gittests/localrepo/.git/
14:27:22 ~/gittests/localrepo (master #)$ cd ..
14:27:35 ~/gittests$ git clone localrepo copyoflocalrepo
Cloning into 'copyoflocalrepo'...
warning: You appear to have cloned an empty repository.
done.
14:27:42 ~/gittests$ cd copyoflocalrepo/
14:27:46 ~/gittests/copyoflocalrepo (master #)$ git status
On branch master
Initial commit
nothing to commit (create/copy files and use "git add" to track)
14:27:46 ~/gittests/copyoflocalrepo (master #)$
at least pip3 also works without "=", however, instead of "http" you might need "https"
Final command, which worked for me:
sudo pip3 install --proxy https://{proxy}:{port} {BINARY}
>>> a = []
>>> for i in xrange(3):
... a.append([])
... for j in xrange(3):
... a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>
public enum NewEnum {
ONE("test"),
TWO("test");
private String s;
private NewEnum(String s) {
this.s = s);
}
public String getS() {
return this.s;
}
}
Comparator
is a functional interface, and Integer::max
complies with that interface (after autoboxing/unboxing is taken into consideration). It takes two int
values and returns an int
- just as you'd expect a Comparator<Integer>
to (again, squinting to ignore the Integer/int difference).
However, I wouldn't expect it to do the right thing, given that Integer.max
doesn't comply with the semantics of Comparator.compare
. And indeed it doesn't really work in general. For example, make one small change:
for (int i = 1; i <= 20; i++)
list.add(-i);
... and now the max
value is -20 and the min
value is -1.
Instead, both calls should use Integer::compare
:
System.out.println(list.stream().max(Integer::compare).get());
System.out.println(list.stream().min(Integer::compare).get());
If your <option>
elements don't have value
attributes, then you can just use .val
:
$selectElement.val("text_you're_looking_for")
However, if your <option>
elements have value attributes, or might do in future, then this won't work, because whenever possible .val
will select an option by its value
attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value
attributes, so we'll have to add one ourselves with a simple plugin:
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function () {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$options = $selectElement.find('option');
$targetOption = $options.filter(
function () {return jQuery(this).text() == targetText}
);
// We use `.prop` if it's available (which it should be for any jQuery
// versions above and including 1.6), and fall back on `.attr` (which
// was used for changing DOM properties in pre-1.6) otherwise.
if ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
Just include this plugin somewhere after you add jQuery onto the page, and then do
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
to select options.
The plugin method uses filter
to pick out only the option
matching the targetText, and selects it using either .attr
or .prop
, depending upon jQuery version (see .prop() vs .attr() for explanation).
Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/
Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.
To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)
The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:
* ASP.NET * Advanced Windows Communication Foundation (WCF) functionality * .NET Framework Data Provider for Oracle * MSBuild for compiling
I think this one is awesome
ls -1 | awk 'ORS=","'
ORS is the "output record separator" so now your lines will be joined with a comma.
Providing protected access to static html folder using https://github.com/johnsensible/django-sendfile: https://gist.github.com/iutinvg/9907731
There is an unnecessary hashtag; change the code to this:
var e = document.getElementById("ticket_category_clone").value;
To add to James's example, it seems you always have to create an intermediate when performing calculations on NA-containing data frames.
For instance, adding two columns (A and B) together from a data frame dfr
:
temp.df <- data.frame(dfr) # copy the original
temp.df[is.na(temp.df)] <- 0
dfr$C <- temp.df$A + temp.df$B # or any other calculation
remove('temp.df')
When I do this I throw away the intermediate afterwards with remove
/rm
.
Compiling the last answers into one:
If you're on Windows, use chocolatey:
choco install ffmpeg
If you are on Mac, use Brew:
brew install ffmpeg
If you are on a Debian Linux distribution, use apt:
sudo apt-get install ffmpeg
And make sure Youtube-dl is updated:
youtube-dl -U
This answer is late, but I was having the same issue. I found something that works.
In eclipse Project Explorer, right click the project name -> select "Run As" -> "Maven Build..."
In the goals, enter spring-boot:run
then click Run button.
I have the STS plug-in (i.e. SpringSource Tool Suite), so on some projects I will get a "Spring Boot App" option under Run As. But, it doesn't always show up for some reason. I use the above workaround for those.
Here is a reference that explains how to run Spring boot apps:
Spring boot tutorial
I'm on node 10 and child process 1.0.2
. The data from python is a byte array and has to be converted. Just another quick example of making a http request in python.
const process = spawn("python", ["services/request.py", "https://www.google.com"])
return new Promise((resolve, reject) =>{
process.stdout.on("data", data =>{
resolve(data.toString()); // <------------ by default converts to utf-8
})
process.stderr.on("data", reject)
})
import urllib.request
import sys
def karl_morrison_is_a_pedant():
response = urllib.request.urlopen(sys.argv[1])
html = response.read()
print(html)
sys.stdout.flush()
karl_morrison_is_a_pedant()
p.s. not a contrived example since node's http module doesn't load a few requests I need to make
You can call the btnTest_Click just like any other function.
The most basic form would be this:
btnTest_Click(this, null);
You can install packages listed in a text file called requirements file.
For example, if you have a file called req.txt
containing the following text:
Django==1.4
South==0.7.3
and you issue at the command line:
pip install -r req.txt
pip will install packages listed in the file at the specific revisions.
You can set the default "Content-Type" like this:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
About the data
format:
The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. If data is a JavaScript object it will be, by default, converted to a JSON string.
Try to use this variation
function sendData($scope) {
$http({
url: 'request-url',
method: "POST",
data: { 'message' : message }
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
}
This is quite an old question but there's a much simple way of achieving this.
myButton.userInteractionEnabled = false
This will only disable any touch gestures without changing the appearance of the button
Try this:
function funcName() {
alert("test");
}
var run = setInterval(funcName, 10000)
Starting in iOS 6, you can use
-tableView:shouldHighlightRowAtIndexPath:
If you return NO
, it disables both the selection highlighting and the storyboard triggered segues connected to that cell.
The method is called when a touch comes down on a row. Returning NO
to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.
public static void main(String[] args) {
List<String> strlist = new ArrayList<String>();
strlist.add("sdfs1");
strlist.add("sdfs2");
String[] strarray = new String[strlist.size()]
strlist.toArray(strarray );
System.out.println(strarray);
}
As of Visual Studio 2012, Microsoft no longer provides the built-in deployment package. If you wish to use this package, you will need to use VS2010.
In 2013 you have several options:
In my projects I create my own installers from scratch, which, since I do not use Windows Installer, have the advantage of being super fast, even on old machines.
let course = {
name: 'Angular',
};
let newCourse= Object.assign({}, course);
newCourse.name= 'React';
console.log(course.name); // writes Angular
console.log(newCourse.name); // writes React
For Nested Object we can use of 3rd party libraries, for deep copying objects. In case of lodash, use _.cloneDeep()
let newCourse= _.cloneDeep(course);
To get a random number say between 1 and 6, first do:
0.5 + (Math.random() * ((6 - 1) + 1))
This multiplies a random number by 6 and then adds 0.5 to it. Next round the number to a positive integer by doing:
Math.round(0.5 + (Math.random() * ((6 - 1) + 1))
This round the number to the nearest whole number.
Or to make it more understandable do this:
var value = 0.5 + (Math.random() * ((6 - 1) + 1))
var roll = Math.round(value);
return roll;
In general the code for doing this using variables is:
var value = (Min - 0.5) + (Math.random() * ((Max - Min) + 1))
var roll = Math.round(value);
return roll;
The reason for taking away 0.5 from the minimum value is because using the minimum value alone would allow you to get an integer that was one more than your maximum value. By taking away 0.5 from the minimum value you are essentially preventing the maximum value from being rounded up.
Hope that helps.
Your code won't work because you haven't assigned anything to n
before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break
:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input
in Python 2.x reads a line of input and then evaluates it. You want to use raw_input
.
Note: In Python 3.x, raw_input
has been renamed to input
and the old input
method no longer exists.
TypeScript 3.9+ update (May 12, 2020)
Now, TypeScript also supports named tuples. This greatly increases the understandability and maintainability of the code. Check the official TS playground.
So, now instead of unnamed:
const a: [number, string] = [ 1, "message" ];
We can add names:
const b: [id: number, message: string] = [ 1, "message" ];
Note: you need to add all names at once, you can not omit some names, e.g:
type tIncorrect = [id: number, string]; // INCORRECT, 2nd element has no name, compile-time error.
type tCorrect = [id: number, msg: string]; // CORRECT, all have a names.
Tip: if you are not sure in the count of the last elements, you can write it like this:
type t = [msg: string, ...indexes: number];// means first element is a message and there are unknown number of indexes.
FYI you can sometimes use SYSTEM or Trustedinstaller to kill tasks ;)
google quickkill_3_0.bat
sc config TrustedInstaller binPath= "cmd /c TASKKILL /F /IM notepad.exe
sc start "TrustedInstaller"
First Activity
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
Second Activity
val value = getIntent().getStringExtra("key")
Suggestion
Always put keys in constant file for more managed way.
companion object {
val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}
I'm late to the party, but for anyone else who finds this - this article is very useful: http://kilianvalkhof.com/2010/css-xhtml/how-to-use-rgba-in-ie/
It uses the gradient filter to display solid but transparent colour.
I used
and it is working fine. You could try it.
You do not need to use the quotation marks
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);
access arr
like normal int[]
.
Use:
[ngStyle]="{'background-image': 'url(' +1=1 ? ../../assets/img/emp-user.png : ../../assets/img/emp-default.jpg + ')'}"
If you are popping it in the DOM then try wrapping it in
<pre>
<code>{JSON.stringify(REPLACE_WITH_OBJECT, null, 4)}</code>
</pre>
makes a little easier to visually parse.
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
I got this error because I have installed "Eclipse IDE for Enterprise Java Developers", I uninstalled this and installed "Eclipse IDE for Java Developers". Problem solved for me.
I am doing this
Collection.All(c => { c.needsChange = value; return true; });
In most situations, git fetch
should do what you want, which is 'get anything new from the remote repository and put it in your local copy without merging to your local branches'. git fetch --tags
does exactly that, except that it doesn't get anything except new tags.
In that sense, git fetch --tags
is in no way a superset of git fetch
. It is in fact exactly the opposite.
git pull
, of course, is nothing but a wrapper for a git fetch <thisrefspec>; git merge
. It's recommended that you get used to doing manual git fetch
ing and git merge
ing before you make the jump to git pull
simply because it helps you understand what git pull
is doing in the first place.
That being said, the relationship is exactly the same as with git fetch
. git pull
is the superset of git pull --tags
.
You could also write a reusable class for QueryParam-annotated variables
public class DateParam {
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
private Calendar date;
public DateParam(String in) throws WebApplicationException {
try {
date = Calendar.getInstance();
date.setTime(format.parse(in));
}
catch (ParseException exception) {
throw new WebApplicationException(400);
}
}
public Calendar getDate() {
return date;
}
public String format() {
return format.format(value.getTime());
}
}
then use it like this:
private @QueryParam("from") DateParam startDateParam;
private @QueryParam("to") DateParam endDateParam;
// ...
startDateParam.getDate();
Although the error handling is trivial in this case (throwing a 400 response), using this class allows you to factor-out parameter handling in general which might include logging etc.
For swift:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background {
//opened from a push notification when the app was in the background
}
}
First you need to create the Hidden Field properly
<asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>
Then you need to set value to the hidden field
If you aren't using Jquery you should use it:
document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";
If you are using Jquery, this is how it should be:
$("#<%= hdntxtbxTaksit.ClientID %>").val("test");
When you write
String a = "";
It means there is a variable 'a' of type string which points to a object reference in string pool which has a value "". As variable a
is holding a valid string object reference, all the methods of string can be applied here.
Whereas when you write
String b = null;
It means that there is a variable b
of type string which points to an unknown reference. And any operation on unknown reference will result in an NullPointerException
.
Now, let us evaluate the below expressions.
System.out.println(a == b); // false. because a and b both points to different object reference
System.out.println(a.equals(b)); // false, because the values at object reference pointed by a and b do not match.
System.out.println(b.equals(a)); // NullPointerException, because b is pointing to unknown reference and no operation is allowed
The quick and simple answer is No.
Javascript is quite a high level language and does not have access to this sort of information.
Enumerate basically gives you an index to work with in the for loop. So:
for i,a in enumerate([4, 5, 6, 7]):
print i, ": ", a
Would print:
0: 4
1: 5
2: 6
3: 7
Crontab files are simply text files and as such can be treated like any other text file. The purpose of the crontab
command is to make editing crontab files safer. When edited through this command, the file is checked for errors and only saved if there are none.
crontab [path to file]
can be used to specify a crontab stored in a file. Like crontab -e
, this will only install the file if it is error free.
Therefore, a script can either directly write cron tab files, or write them to a temporary file and load them with the crontab [path to temp file]
command. Writing directly saves having to write a temporary file, but it also avoids the safety check.
Scraping it to JSON with Node.js would be fun :)
https://github.com/f1lt3r/bitcoin-scraper
[
[
1419033600, // Timestamp (1 for each minute of entire history)
318.58, // Open
318.58, // High
318.58, // Low
318.58, // Close
0.01719605, // Volume (BTC)
5.478317609, // Volume (Currency)
318.58 // Weighted Price (USD)
]
]
My initial take gave me something like:
public static int CountOccurrences(string original, string substring)
{
if (string.IsNullOrEmpty(substring))
return 0;
if (substring.Length == 1)
return CountOccurrences(original, substring[0]);
if (string.IsNullOrEmpty(original) ||
substring.Length > original.Length)
return 0;
int substringCount = 0;
for (int charIndex = 0; charIndex < original.Length; charIndex++)
{
for (int subCharIndex = 0, secondaryCharIndex = charIndex; subCharIndex < substring.Length && secondaryCharIndex < original.Length; subCharIndex++, secondaryCharIndex++)
{
if (substring[subCharIndex] != original[secondaryCharIndex])
goto continueOuter;
}
if (charIndex + substring.Length > original.Length)
break;
charIndex += substring.Length - 1;
substringCount++;
continueOuter:
;
}
return substringCount;
}
public static int CountOccurrences(string original, char @char)
{
if (string.IsNullOrEmpty(original))
return 0;
int substringCount = 0;
for (int charIndex = 0; charIndex < original.Length; charIndex++)
if (@char == original[charIndex])
substringCount++;
return substringCount;
}
The needle in a haystack approach using replace and division yields 21+ seconds whereas this takes about 15.2.
Edit after adding a bit which would add substring.Length - 1
to the charIndex (like it should), it's at 11.6 seconds.
Edit 2: I used a string which had 26 two-character strings, here are the times updated to the same sample texts:
Needle in a haystack (OP's version): 7.8 Seconds
Suggested mechanism: 4.6 seconds.
Edit 3: Adding the single character corner-case, it went to 1.2 seconds.
Edit 4: For context: 50 million iterations were used.
If you want to display an image file on the phone, you can do this:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));
If you want to display an image from your drawable resources, do this:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);
You'll find the drawable
folder(s) in the project res
folder. You can put your image files there.
I think this is what you're looking for: Microsoft Visual C++ 2008 Redistributable Package (x86)
In Visual Studio project properties ("Build" page, if I recall it right) there is an option saying "generate serialization assembly". Try turning it on for a project that generates [Containing Assembly of MyType].
A join of two tables is best done by a DBMS, so it should be done that way. You could mirror the smaller table or subset of it on one of the databases and then join them. One might get tempted of doing this on an ETL server like informatica but I guess its not advisable if the tables are huge.
OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.
The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.
Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.
See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F
You can run conda install --file requirements.txt
instead of the loop, but there is no target directory in conda install. conda install
installs a list of packages into a specified conda environment.
This is a similar answer to the one Hezi Rasheff provided, but simplified so newer python users understand what's going on (I noticed many new datascience students fetch random samples in the weirdest ways because they don't know what they are doing in python).
You can get a number of random indices from your array by using:
indices = np.random.choice(A.shape[0], amount_of_samples, replace=False)
You can then use fancy indexing with your numpy array to get the samples at those indices:
A[indices]
This will get you the specified number of random samples from your data.
do something like this next time
Criteria crit = (Criteria) session.
createCriteria(SomeClass.class).
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List claz = crit.list();
Working in Rails 5
ActiveModel::Type::Boolean.new.cast('t') # => true
ActiveModel::Type::Boolean.new.cast('true') # => true
ActiveModel::Type::Boolean.new.cast(true) # => true
ActiveModel::Type::Boolean.new.cast('1') # => true
ActiveModel::Type::Boolean.new.cast('f') # => false
ActiveModel::Type::Boolean.new.cast('0') # => false
ActiveModel::Type::Boolean.new.cast('false') # => false
ActiveModel::Type::Boolean.new.cast(false) # => false
ActiveModel::Type::Boolean.new.cast(nil) # => nil
a covering index is the one which gives every required column and in which SQL server don't have hop back to the clustered index to find any column. This is achieved using non-clustered index and using INCLUDE option to cover columns. Non-key columns can be included only in non-clustered indexes. Columns can’t be defined in both the key column and the INCLUDE list. Column names can’t be repeated in the INCLUDE list. Non-key columns can be dropped from a table only after the non-key index is dropped first. Please see details here
A bash solution :
docker history --no-trunc $argv | tac | tr -s ' ' | cut -d " " -f 5- | sed 's,^/bin/sh -c #(nop) ,,g' | sed 's,^/bin/sh -c,RUN,g' | sed 's, && ,\n & ,g' | sed 's,\s*[0-9]*[\.]*[0-9]*\s*[kMG]*B\s*$,,g' | head -n -1
Step by step explanations:
tac : reverse the file
tr -s ' ' trim multiple whitespaces into 1
cut -d " " -f 5- remove the first fields (until X months/years ago)
sed 's,^/bin/sh -c #(nop) ,,g' remove /bin/sh calls for ENV,LABEL...
sed 's,^/bin/sh -c,RUN,g' remove /bin/sh calls for RUN
sed 's, && ,\n & ,g' pretty print multi command lines following Docker best practices
sed 's,\s*[0-9]*[\.]*[0-9]*\s*[kMG]*B\s*$,,g' remove layer size information
head -n -1 remove last line ("SIZE COMMENT" in this case)
Example:
~ ? dih ubuntu:18.04
ADD file:28c0771e44ff530dba3f237024acc38e8ec9293d60f0e44c8c78536c12f13a0b in /
RUN set -xe
&& echo '#!/bin/sh' > /usr/sbin/policy-rc.d
&& echo 'exit 101' >> /usr/sbin/policy-rc.d
&& chmod +x /usr/sbin/policy-rc.d
&& dpkg-divert --local --rename --add /sbin/initctl
&& cp -a /usr/sbin/policy-rc.d /sbin/initctl
&& sed -i 's/^exit.*/exit 0/' /sbin/initctl
&& echo 'force-unsafe-io' > /etc/dpkg/dpkg.cfg.d/docker-apt-speedup
&& echo 'DPkg::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' > /etc/apt/apt.conf.d/docker-clean
&& echo 'APT::Update::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' >> /etc/apt/apt.conf.d/docker-clean
&& echo 'Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache "";' >> /etc/apt/apt.conf.d/docker-clean
&& echo 'Acquire::Languages "none";' > /etc/apt/apt.conf.d/docker-no-languages
&& echo 'Acquire::GzipIndexes "true"; Acquire::CompressionTypes::Order:: "gz";' > /etc/apt/apt.conf.d/docker-gzip-indexes
&& echo 'Apt::AutoRemove::SuggestsImportant "false";' > /etc/apt/apt.conf.d/docker-autoremove-suggests
RUN rm -rf /var/lib/apt/lists/*
RUN sed -i 's/^#\s*\(deb.*universe\)$/\1/g' /etc/apt/sources.list
RUN mkdir -p /run/systemd
&& echo 'docker' > /run/systemd/container
CMD ["/bin/bash"]
There is a built-in Windows tool for that:
dir /s 'FolderName'
This will print a lot of unnecessary information but the end will be the folder size like this:
Total Files Listed:
12468 File(s) 182,236,556 bytes
If you need to include hidden folders add /a
.
Nanda's answer wasn't enough in my setup. What I needed to do is:
Ok, I found a working solution for this, it consists of using the beforeunload
event and then making the handler return null
. This executes the wanted code without a confirmation box popping-up. It goes something like this:
window.onbeforeunload = closingCode;
function closingCode(){
// do something...
return null;
}
If you have supporting indexes, and relatively high counts, something like this may be considerably faster than the solutions suggested:
SELECT name, MAX(Rcount) + MAX(Acount) AS TotalCount
FROM (
SELECT name, COUNT(*) AS Rcount, 0 AS Acount
FROM Results GROUP BY name
UNION ALL
SELECT name, 0, count(*)
FROM Archive_Results
GROUP BY name
) AS Both
GROUP BY name
ORDER BY name;
Thank You All! I am able to to load Select List as per MVC now My Working Code is below:
HTML+MVC Code in View:-
<tr>
<th>@Html.Label("Country")</th>
<td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetCountryList())<span class="required">*</span></td>
</tr>
<tr>
<th>@Html.LabelFor(x=>x.Province)</th>
<td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetProvincesList())<span class="required">*</span></td>
</tr>
Created a Controller under "UTIL" folder: Code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MedAvail.Applications.MedProvision.Web.Util
{
public class SelectListItemHelper
{
public static IEnumerable<SelectListItem> GetProvincesList()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "California", Value = "B"},
new SelectListItem{Text = "Alaska", Value = "B"},
new SelectListItem{Text = "Illinois", Value = "B"},
new SelectListItem{Text = "Texas", Value = "B"},
new SelectListItem{Text = "Washington", Value = "B"}
};
return items;
}
public static IEnumerable<SelectListItem> GetCountryList()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "United States", Value = "B"},
new SelectListItem{Text = "Canada", Value = "B"},
new SelectListItem{Text = "United Kingdom", Value = "B"},
new SelectListItem{Text = "Texas", Value = "B"},
new SelectListItem{Text = "Washington", Value = "B"}
};
return items;
}
}
}
And its working COOL now :-)
Thank you!!
You can check the status of tomcat with the following ways:
ps -ef | grep tomcat
This will return the tomcat path if the tomcat is running
netstat -a | grep 8080
where 8080 is the tomcat port
I feel your pain and I wasted all night/morning trying to figure this out. With sheer brute force I figured out a solution. Call it a workaround - but it's simple.
Add the CssClass property to your Menu Control's declaration like so:
<asp:Menu ID="NavigationMenu" DataSourceID="NavigationSiteMapDataSource"
CssClass="SomeMenuClass"
StaticMenuStyle-CssClass="StaticMenuStyle"
StaticMenuItemStyle-CssClass="StaticMenuItemStyle"
Orientation="Horizontal"
MaximumDynamicDisplayLevels="0"
runat="server">
</asp:Menu>
Just rip out the StaticSelectedStyle-CssClass and StaticHoverStyle-CssClass attributes as they simply don't do jack.
Now create the "SomeMenuClass", doesn't matter what you put in it. It should look something like this:
.SomeMenuClass
{
color:Green;
}
Next add the following two CSS Classes:
For "Hover" Styling add:
.SomeMenuClass a.static.highlighted
{
color:Red !important;
}
For "Selected" Styling add:
.SomeMenuClass a.static.selected
{
color:Blue !important;
}
There, that's it. You're done. Hope this saves some of you the frustration I went through. BTW: You mentioned:
I seem to be the first one to ever report on what seems to be a bug.
You also seemed to think it was a new .NET 4.0 bug. I found this: http://www.velocityreviews.com/forums/t649530-problem-with-staticselectedstyle-and-statichoverstyle.html posted back in 2008 regarding Asp.Net 2.0 . How are we the only 3 people on the planet complaining about this?
How I found the workaround (study the HTML output):
Here is the HTML output when I set StaticHoverStyle-BackColor="Red":
#NavigationMenu a.static.highlighted
{
background-color:Red;
}
This is the HTML output when setting StaticSelectedStyle-BackColor="Blue":
#NavigationMenu a.static.selected
{
background-color:Blue;
text-decoration:none;
}
Therefore, the logical way to override this markup was to create classes for SomeMenuClass a.static.highlighted and SomeMenuClass a.static.selected
Special Notes:
You MUST also use "!important" on ALL the settings in these classes because the HTML output uses "#NavigationMenu", and that means any styles Asp.Net decides to throw in there for you will have inheritance priority over any other styles for the Menu Control with the ID "NavigationMenu". One thing I struggled with was padding, till I figured out Asp.Net was using "#NavigationMenu" to set the left and right padding to 15em. I tacked on "!important" to my SomeMenuClass styles and it worked.
In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.
Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.
Well, in my case, the px
after the width value was missing ... Interestingly, the W3C validator did not even notice this error, just silently ignored the definition.
For android source code with repo, I beleive you should use REPO. if you really want to use git, you should know if the project has .git directory with ls -a. Or you have to enter the sub project directory which should include the .git.
Here is my version to find mount points of a docker compose. In use this to backup the volumes.
# for Id in $(docker-compose -f ~/ida/ida.yml ps -q); do docker inspect -f '{{ (index .Mounts 0).Source }}' $Id; done
/data/volumes/ida_odoo-db-data/_data
/data/volumes/ida_odoo-web-data/_data
This is a combination of previous solutions.
Following position parameter worked for me
position: { my: "right bottom", at: "center center", of: window },
Good luck!
You can use the npm modules jsdom and htmlparser to create and parse a DOM in Node.JS.
Other options include:
Out of all these options, I prefer using the Node.js option, because it uses the standard W3C DOM accessor methods and I can reuse code on both the client and server. I wish BeautifulSoup's methods were more similar to the W3C dom, and I think converting your HTML to XHTML to write XSLT is just plain sadistic.
Try running the entire script through jslint. This may help point you at the cause of the error.
Edit Ok, it's not quite the syntax of the script that's the problem. At least not in a way that jslint can detect.
Having played with your live code at http://ft2.hostei.com/ft.v1/, it looks like there are syntax errors in the generated code that your script puts into an onclick
attribute in the DOM. Most browsers don't do a very good job of reporting errors in JavaScript run via such things (what is the file and line number of a piece of script in the onclick
attribute of a dynamically inserted element?). This is probably why you get a confusing error message in Chrome. The FireFox error message is different, and also doesn't have a useful line number, although FireBug does show the code which causes the problem.
This snippet of code is taken from your edit
function which is in the inline script block of your HTML:
var sub = document.getElementById('submit');
...
sub.setAttribute("onclick", "save(\""+file+"\", document.getElementById('name').value, document.getElementById('text').value");
Note that this sets the onclick
attribute of an element to invalid JavaScript code:
<input type="submit" id="submit" onclick="save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value">
The JS is:
save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value
Note the missing close paren to finish the call to save
.
As an aside, inserting onclick
attributes is not a very modern or clean way of adding event handlers in JavaScript. Why are you not using the DOM's addEventListener
to simply hook up a function to the element? If you were using something like jQuery, this would be simpler still.
AndroidStudio Menu:
Build/Clean Project
Update old dependencies
If you're using express@~3.0.0 change the line below from your example:
app.use(express.staticProvider(__dirname + '/public'));
to something like this:
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
I made it as described on express api page and it works like charm. With that setup you don't have to write additional code so it becomes easy enough to use for your micro production or testing.
Full code listed below:
var express = require('express');
var app = express.createServer();
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.listen(8080, '127.0.0.1')
You can use:
cell.getCellTypeEnum()
Further to compare the cell type, you have to use CellType as follows:-
if(cell.getCellTypeEnum() == CellType.STRING){
.
.
.
}
You can Refer to the documentation. Its pretty helpful:-
https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html
Another method that can be used to copy tables from the source database to the destination one is the SQL Server Export and Import wizard, which is available in SQL Server Management Studio.
You have the choice to export from the source database or import from the destination one in order to transfer the data.
This method is a quick way to copy tables from the source database to the destination one, if you arrange to copy tables having no concern with the tables’ relationships and orders.
When using this method, the tables’ indexes and keys will not be transferred. If you are interested in copying it, you need to generate scripts for these database objects.
If these are Foreign Keys, connecting these tables together, you need to export the data in the correct order, otherwise the export wizard will fail.
Feel free to read more about this method, as well as about some more methods (including generate scripts, SELECT INTO and third party tools) in this article: https://www.sqlshack.com/how-to-copy-tables-from-one-database-to-another-in-sql-server/
I was comparing worldcitiesdatabae.info with www.worldcitiesdatabase.com and it appears the latter one to be more resourceful. However, maxmind has a free database so then why buy a cities database. Just get the free one and there is lot of help available on internet about maxmind db. If you put in extra efforts then you can save those few bucks :)
From Wikipedia:
In computer programming, boilerplate is the term used to describe sections of code that have to be included in many places with little or no alteration. It is more often used when referring to languages that are considered verbose, i.e. the programmer must write a lot of code to do minimal jobs.
So basically you can consider boilerplate code as a text that is needed by a programming language very often all around the programs you write in that language.
Modern languages are trying to reduce it, but also the older language which has specific type-checkers (for example OCaml has a type-inferrer that allows you to avoid so many declarations that would be boilerplate code in a more verbose language like Java)
Either decorate your root entity with the XmlRoot attribute which will be used at compile time.
[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]
Or specify the root attribute when de serializing at runtime.
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "user";
// xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;
XmlSerializer xs = new XmlSerializer(typeof(User),xRoot);