I had same mistake, it was produced because i had disabled the creation of "_jvm" in the InstallAnywhere (project - JVM settings - Installer Settings - Bundled/Downloaded Virtual Machine), then into file "Uninstall $PRODUCT_NAME$.lax" into uninstall folder, the variable "lax.nl.current.vm" is empty.
If you don't need jvm is disabled check "Install Bundled / Downloaded Virtual Machine" option in the checkbox (project - JVM settings - Installer Settings - Bundled/Downloaded Virtual Machine).
If you need jvm is disabled because you create it manually, then you can do the following: create an action "Modify Text File" to append variable with the value of the _jvm folder.
(Existing File)
$USER_INSTALL_DIR$\Uninstall_$PRODUCT_NAME$ \Uninstall $PRODUCT_NAME$.lax
(Append)
lax.nl.current.vm=..\_jvm\bin\java.exe
Nowadays, Java 8 allows for a one-line functional solution that is cleaner, faster, and a whole lot simpler than the accepted solution:
List<String> list = new ArrayList<>();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
List<String> matches = list.stream().filter(it -> it.contains("bea")).collect(Collectors.toList());
System.out.println(matches); // [bear, beat]
And even easier in Kotlin:
val matches = list.filter { it.contains("bea") }
var dataString = "flag=fetchmediaaudio&id="+id;
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
success: function(html)
{
alert(html);
}
});
If you want the actions to be more or less atomic, I would make sure to wrap them in a transaction. That way you can be sure both happened or both didn't happen as needed.
It's not how they work. You "start" a marquee style progress bar by making it visible, you stop it by hiding it. You could change the Style property.
From the matplotlib docs on scatter 1:
cmap is only used if c is an array of floats
So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.
How does this work for you?
import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()
Run this command to browse all constraints:
exec sp_helpconstraint 'mytable' --and look under constraint_name.
It will look something like this: DF__Mytable__Column__[ABC123]
. Then you can just drop the constraint.
use MYSQL as Example: 1) use database connection pools: for Example: Apache Commons DBCP , also, you need basicDataSource jar package in your classpath
@Bean
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/gene");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
2)use JDBC-based Driver it is usually used if you don't consider connection pool:
@Bean
public DataSource dataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/gene");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
$(document).ready(function() {
//calculate the window height & add css properties for height 100%
wh = $( window ).height();
ww = $( window ).width();
$(".targeted-div").css({"height": wh, "width": ww});
});
If you can overlook the height of TextBlock, it's better for you to use this:
<TextBlock Height="{Binding}" Text="Your text"
TextWrapping="Wrap" VerticalAlignment="Center" Width="28"/>
Here is a class I wrote to do this for ASP.NETCore RC2. I use it so I can generate html email using Razor.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using System.IO;
using System.Threading.Tasks;
namespace cloudscribe.Web.Common.Razor
{
/// <summary>
/// the goal of this class is to provide an easy way to produce an html string using
/// Razor templates and models, for use in generating html email.
/// </summary>
public class ViewRenderer
{
public ViewRenderer(
ICompositeViewEngine viewEngine,
ITempDataProvider tempDataProvider,
IHttpContextAccessor contextAccesor)
{
this.viewEngine = viewEngine;
this.tempDataProvider = tempDataProvider;
this.contextAccesor = contextAccesor;
}
private ICompositeViewEngine viewEngine;
private ITempDataProvider tempDataProvider;
private IHttpContextAccessor contextAccesor;
public async Task<string> RenderViewAsString<TModel>(string viewName, TModel model)
{
var viewData = new ViewDataDictionary<TModel>(
metadataProvider: new EmptyModelMetadataProvider(),
modelState: new ModelStateDictionary())
{
Model = model
};
var actionContext = new ActionContext(contextAccesor.HttpContext, new RouteData(), new ActionDescriptor());
var tempData = new TempDataDictionary(contextAccesor.HttpContext, tempDataProvider);
using (StringWriter output = new StringWriter())
{
ViewEngineResult viewResult = viewEngine.FindView(actionContext, viewName, true);
ViewContext viewContext = new ViewContext(
actionContext,
viewResult.View,
viewData,
tempData,
output,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return output.GetStringBuilder().ToString();
}
}
}
}
Here are all the possible problems/solutions I have come across:
$.cookie
is not a standard jQuery function and the plugin needs to be downloaded here. Make sure to include the appropriate <script>
tag where necessary (see next).
When including the cookie script, make sure to include jQuery FIRST, then the cookie plugin.
<script src="~/Scripts/jquery-2.0.3.js" type="text/javascript"></script>
<script src="~/Scripts/jquery_cookie.js" type="text/javascript"></script>
This was my problem. Make sure you aren't including jQuery more than once. If you are, it is possible that:
For anyone using ASP.Net MVC projects, be careful with the default javascript bundle inclusions. My second inclusion of jQuery was within one of my global layout pages under the line @Scripts.Render("~/bundles/jquery")
.
In some rare cases, renaming the file to something that does NOT include ".cookie" has fixed this error, apparently due to web server issues. By default, the downloaded script is titled "jquery.cookie.js" but try renaming it to something like "jquery_cookie.js" as shown above. More details on this problem are here.
It's even easier than everything suggested above. Data attributes in MVC which include dashes (-) are catered for with the use of underscore (_).
<%= Html.ActionLink("« Previous", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new { @class = "prev", data_details = "Some Details" })%>
I see JohnnyO already mentioned this.
Here's a script to do this automatically
# Only allow key based logins
sed -n 'H;${x;s/\#PasswordAuthentication yes/PasswordAuthentication no/;p;}' /etc/ssh/sshd_config > tmp_sshd_config
cat tmp_sshd_config > /etc/ssh/sshd_config
rm tmp_sshd_config
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
By wrapping your comparisons in {}
in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }
. Since the -and
operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true }
which is always true.
Instead of using {}
, use parentheses ()
.
Also you want to use -eq
instead of -match
since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls'
).
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public |
Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}
A better option is to filter the extensions at the Get-ChildItem
command.
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk |
Where-Object {$_.creationtime -ge "06/01/2014"}
}
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
You installed PHP IntelliSense
extension, and this error because of it.
So if you want to fix this problem go to this menu:
File -> Preferences -> Settings
Now you can see 2 window. In the right window add below codes:
{
"php.validate.executablePath": "C:\\wamp64\\bin\\php\\php7.0.4\\php.exe",
"php.executablePath": "C:\\wamp64\\bin\\php\\php7.0.4\\php.exe"
}
Just like below image.
NOTICE: This address C:\\wamp64\\bin\\php\\php7.0.4\\php.exe
is my php7.exe
file address. Replace this address with own php7.exe
.
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
in terminal, type : conda list
to obtain the packages installed using conda.
for the packages that pip
recognizes, type : pip list
There may be some overlap of these lists as pip
may recognize packages installed by conda
(but maybe not the other way around, IDK).
There is a useful source here, including how to update or upgrade packages..
I suspect there are many answers like this on SO but here you go:
if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
...
}
They have nothing to do with each other.
Java is statically typed, compiles, runs on its own VM.
Javascript is dynamically typed, interpreted, and runs in a browser. It also has first-class functions and anonymous functions, which Java does not. It has direct access to web-page elements, which makes it useful for doing client-side processing.
They are also somewhat similar in syntax, but that's about it.
This extension works well when configuring the text of a label with an already set default color.
public extension String {
func setColor(_ color: UIColor, ofSubstring substring: String) -> NSMutableAttributedString {
let range = (self as NSString).range(of: substring)
let attributedString = NSMutableAttributedString(string: self)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
return attributedString
}
}
For example
let text = "Hello World!"
let attributedText = text.setColor(.blue, ofSubstring: "World")
let myLabel = UILabel()
myLabel.textColor = .white
myLabel.attributedText = attributedText
What is the problem here is that you somehow installed into virtualenv using sudo
. Probably by accident. This means root
user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.
You can fix the issue by changing UNIX file permissions pack to your user. Try:
$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip
then pip
should be able to write those files again.
User "portrait"
in your AndroidManifest.xml file might seem like a good solution. But it forces certain devices (that work best in landscape) to go into portrait, not getting the proper orientation. On the latest Android version, you will get wearing an error. So my suggestion it's better to use "nosensor"
.
<activity
...
...
android:screenOrientation="nosensor">
typedef
is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance
typedef int myinteger;
typedef char *mystring;
typedef void (*myfunc)();
using them like
myinteger i; // is equivalent to int i;
mystring s; // is the same as char *s;
myfunc f; // compile equally as void (*f)();
As you can see, you could just replace the typedefed name with its definition given above.
The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef
can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.
The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.
To answer your three questions
Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.
The syntax looks odd (in the pointer to function declaration)
That syntax is not obvious to read, at least when beginning. Using a typedef
declaration instead eases the reading
Is a function pointer created to store the memory address of a function?
Yes, a function pointer stores the address of a function. This has nothing to do with the typedef
construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.
Example:
typedef int (*t_somefunc)(int,int);
int product(int u, int v) {
return u*v;
}
t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456
You could use a @HostListener decorator. Works with Angular 4 and up.
import { HostListener } from '@angular/core';
@HostListener("window:scroll", []) onWindowScroll() {
// do some stuff here when the window is scrolled
const verticalOffset = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop || 0;
}
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate
do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy
:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate
. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Use TCPView: http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
or CurrPorts: https://www.nirsoft.net/utils/cports.html
Alternatively, if you don't want to use EXTERNAL SOFTWARE (these tools don't require an installation by the way), you can simply FIRST run the netstat command (preferably netstat -b ) & then setup Local Security Policy to block the IP address of the user's machine in question, that's what I have been doing with unwanted or even unknown connections - that allows you doing everything WITHOUT ANY EXTERNAL SOFTWARE (everything comes with Windows)...
there is an answer but i did not understand why is not working;
var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);
my solution is like that in this situation;
var duplicates = model.list
.GroupBy(s => s.SAME_ID)
.Where(g => g.Count() > 1).Count() > 0;
if(duplicates) {
doSomething();
}
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
You need the -ExecutionPolicy
parameter:
Powershell.exe -executionpolicy remotesigned -File C:\Users\SE\Desktop\ps.ps1
Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy
is a cmdlet, it has no -File
parameter.
Java documentation is helpful to know the root cause of a particular IOException.
Just have a look at the direct known sub-interfaces of IOException
from the documentation page:
ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException
Most of these exceptions are self-explanatory.
A few IOExceptions
with root causes:
EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.
SocketException: Thrown to indicate that there is an error creating or accessing a Socket.
RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.
UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).
MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
Get hrtime
as single number in one line:
const begin = process.hrtime();
// ... Do the thing you want to measure
const nanoSeconds = process.hrtime(begin).reduce((sec, nano) => sec * 1e9 + nano)
Array.reduce
, when given a single argument, will use the array's first element as the initial accumulator
value. One could use 0
as the initial value and this would work as well, but why do the extra * 0
.
Try @title = "stuff". It worked for me.
I wrote an assembly binding log viewer named Fusion++ and put it on GitHub.
You can get the latest release from here or via chocolatey (choco install fusionplusplus
).
I hope you and some of the visitors in here can save some worthy lifetime minutes with it.
try this
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('.View').html('');
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
}
</script>
To make function to wait for list to be fetched.
getArrayOfData() {
return DataModel.find({}).then(function (storedDataArray) {
return storedDataArray;
}).catch(function(err){
if (err) {
throw new Error(err.message);
}
});
}
Here's what I've found to work:
f_rd = open(path, 'r')
file_lines = f_rd.readlines()
f_rd.close()
matches = [line for line in file_lines if "chars of Interest" in line]
index = file_lines.index(matches[0])
If you're trying to get the integers from the command line args, you'll need something like this:
public static void main(String[] args) {
int[] nums = new int[args.length];
for(int i = 0; i < args.length; i++) {
try {
nums[i] = Integer.parseInt(args[i]);
}
catch(NumberFormatException nfe) {
System.err.println("Invalid argument");
}
}
// averaging code here
}
As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).
Edit: actually it's probably better to just put it inside the above loop and not use the nums
array at all
Configuration.LazyLoadingEnabled = false; Configuration.ProxyCreationEnabled = false;
these are too effect to speed without AutoDetectChangesEnabled = false; and i advise to use different table header from dbo. generally i use like nop,sop,tbl etc..
Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.
Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.
Let's create a chain to log and accept:
iptables -N LOG_ACCEPT
And let's populate its rules:
iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT
Now let's create a chain to log and drop:
iptables -N LOG_DROP
And let's populate its rules:
iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP
Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:
iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP
This works:
<div id="start-element">Click Me</div>
$(document).on("click","#test-element",function() {
alert("click");
});
$(document).on("click","#start-element",function() {
$(this).attr("id", "test-element");
});
Here is the Fiddle
Sure:
try {
throw new Exception('Something bad');
} catch (Exception $e) {
// Do nothing
}
You might want to go have a read of the PHP documentation on Exceptions.
If the string is already within quotes then use another quote to nullify its action.
echo "Insert tablename(col1) Values('""val1""')"
If you want to avoid drawing it yourself, you could use the undocumented class: UINavigationButton with style 1. This could, of course, stop your application from being approved... /John
You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:
In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file"
field, ostensibly for backward compatibility reasons.
So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)
So, listening to popstate
event and sending a popstate
event when using history.pushState()
should be enough to take action on href
change:
window.addEventListener('popstate', listener);
const pushUrl = (href) => {
history.pushState({}, '', href);
window.dispatchEvent(new Event('popstate'));
};
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
Go in the build.gradle and set the version code and name inside the defaultConfig
element
defaultConfig {
minSdkVersion 9
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
100, it will hold the same references. Therefore if you make a change to a specific object in the list
, it will affect the same object in anotherList
.
Adding or removing objects in any of the list will not affect the other.
list
and anotherList
are two different instances, they only hold the same references of the objects "inside" them.
You have to actually call some method to create the directories. Just creating a file
object will not create the corresponding file or directory on the file system.
You can use File#mkdirs()
method to create the directory: -
theFile.mkdirs();
Difference between File#mkdir()
and File#mkdirs()
is that, the later will create any intermediate directory if it does not exist.
My post here is strictly related to Blazor v5 but should work in 3.x as well. Additionally, I'm using these methods with bootstrap 4.5 and 5.0 beta 1 but you could easily adapt it to use style's instead of classes or use your own classes.
To those recommending dynamic, I thank you. The dynamic type seems like it can be very valuable when used correctly. Most of the time you'll probably use an interface but this wasn't plausible for me. I went ahead and updated my project with a dynamic return type and it's working great while being the quickest, cleanest solution.
I previously added the following extension methods to boolean types to help me avoid long ternary operators in razor page code. Here are the 3 main extension methods I use to accomplish it:
public static T Then<T>(this bool value, T result) => value ? result : default;
public static T Then<T>(this bool value, T thenResult, T elseResult) => value ? thenResult : elseResult;
public static T Else<T>(this bool value, T result) => !value ? result : default;
The following are examples of that implementation:
<div class="@Hidden.Then("d-none")">
Hidden content...
</div>
Note: ErrorOrWarning would hide the content if there was no error/warning so I could default it to yellow/italic but this is an example so please use your imagination:
<div class="@ErrorOrWarning.Else("d-none")" style="@Error.Then("color:red;font-weight:bold;","color:yellow;font-style:italic;")">
Error/Warning content...
</div>
This is the typical implementation without the extension methods. It's common to see this technique in Blazor guides/tutorials/videos online. There are cleaner ways to handle it but this is the basic idea:
<div class="@(ErrorOrWarning ? "" : "d-none")" style="@(Error ? "color:red;font-weight:bold;" : "color:yellow;font-style:italic;")">
Error/Warning content...
</div>
While this might not seem like too big a difference, if you have a lot of dynamic content/styles driving your page, it can get really messy. With those 3 lines of code you can enhance the readability and cleanliness and it really does reduce risk of typos. Adding two more extension methods, you can reduce the risk even further Note: Again, this is using bootstrap class "d-none" for the style "display:none!important" but you could just as easily replace with your own usage:
public static string ThenShow(this bool value) => value ? "" : "d-none";
public static string ThenHide(this bool value) => value ? "d-none" : "";
The limitation I previously faced was when using the overloaded Then(thenResult, elseResult), each of the parameters must be of the same type. 99% of the time this is fine. Actually, another 0.5% of the time it's still okay because you can probably solve it quickly with a .ToString() or an explicit cast.
What I ran into, and what took me to this post was: I have a control you can imagine as a button. There is an Enum property allowing the user to select an icon to display. The selected Enum dynamically populates a readonly MarkupString property. As an alternative option, they can use the ChildContent (or IconContent in my example) of type RenderFragment. This will let them manually add anything they want (maybe an iFrame to stackoverflow haha) but my intention is for them to add style, most likely in the form of an icon.
I know I can cast/convert one to the other however my existing extension method is so clean and simple, it would be great to be able to use pass the MarkupString and RenderFragment together as parameters, conditionally output to the razor page. So, thanks to this post, I changed my Then(thenResult, elseResult) extension methods to use unique generic parameter types and return a dynamic type like so:
public static dynamic Then<T,E>(this bool value, T thenResult, E elseResult) => value ? thenResult : elseResult;
Now in my razor page I have a very simple line for the icon output. Note: IconContent is a RenderFragment and IconMarkup is a MarkupString.
@((@IconContent == null).Then(IconMarkup, IconContent))
And because I love extension methods and I'm typing this up, I took it a step further with another extension method:
public static bool IsNull(this RenderFragment value) => value == null;
Which enables the extremely clean and simple:
@IconContent.IsNull().Then(IconMarkup, IconContent)
Here's the extra extension method I mentioned above which converts a string to a MarkupString. It might be overkill but I like it.
public static MarkupString ToMarkup(this string value) => (MarkupString)value;
Let me know if you have a better recommendation or if you think I'm doing something wrong. I'm sure this post makes it seem like I overuse extension methods but I really don't. I keep their use limited to outcomes such as I've outlined in this post.
Not sure if this is efficient or not, but strings in PowerShell can be referred to using array index syntax, in a similar fashion to Python.
It's not completely intuitive because of the fact the first letter is referred to by index = 0
, but it does:
Here are some examples:
PS > 'Hello World'[0..2]
Yields the result (index values included for clarity - not generated in output):
H [0]
e [1]
l [2]
Which can be made more useful by passing -join ''
:
PS > 'Hello World'[0..2] -join ''
Hel
There are some interesting effects you can obtain by using different indices:
Forwards
Use a first index value that is less than the second and the substring will be extracted in the forwards direction as you would expect. This time the second index value is far in excess of the string length but there is no error:
PS > 'Hello World'[3..300] -join ''
lo World
Unlike:
PS > 'Hello World'.Substring(3,300)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within
the string.
Backwards
If you supply a second index value that is lower than the first, the string is returned in reverse:
PS > 'Hello World'[4..0] -join ''
olleH
From End
If you use negative numbers you can refer to a position from the end of the string. To extract 'World'
, the last 5 letters, we use:
PS > 'Hello World'[-5..-1] -join ''
World
Short answer: yes.
Long answer:
In MySQL, the InnoDB storage engine always creates a primary key if you didn't specify it explicitly, thus making an extra column you don't have access to.
Note that a primary key can be composite.
If you have a many-to-many link table, you create the primary key on all fields involved in the link. Thus you ensure that you don't have two or more records describing one link.
Besides the logical consistency issues, most RDBMS engines will benefit from including these fields in a unique index.
And since any primary key involves creating a unique index, you should declare it and get both logical consistency and performance.
See this article in my blog for why you should always create a unique index on unique data:
P.S. There are some very, very special cases where you don't need a primary key.
Mostly they include log tables which don't have any indexes for performance reasons.
Using the arrow function, and sorting by the second string field
var a = [[12, 'CCC'], [58, 'AAA'], [57, 'DDD'], [28, 'CCC'],[18, 'BBB']];_x000D_
a.sort((a, b) => a[1].localeCompare(b[1]));_x000D_
console.log(a)
_x000D_
yourContext.Entry(yourEntity).Reload();
Try this one:
HTML:
<div id="para1"></div>
JavaScript:
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var d = new Date(),
minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}
Result:
Mon Sep 18 2017 12:40pm
Simple. Just change the image orientation flag.
UIImage *oldImage = [UIImage imageNamed:@"whatever.jpg"];
UIImageOrientation newOrientation;
switch (oldImage.imageOrientation) {
case UIImageOrientationUp:
newOrientation = UIImageOrientationLandscapeLeft;
break;
case UIImageOrientationLandscapeLeft:
newOrientation = UIImageOrientationDown;
break;
case UIImageOrientationDown:
newOrientation = UIImageOrientationLandscapeRight;
break;
case UIImageOrientationLandscapeRight:
newOrientation = UIImageOrientationUp;
break;
// you can also handle mirrored orientations similarly ...
}
UIImage *rotatedImage = [UIImage imageWithCGImage:oldImage.CGImage scale:1.0f orientation:newOrientation];
what about a pure css3 solution?
div {
resize: both;
overflow: auto;
}
This was very helpful. I wanted to import this function to a Postgre SQL database. Thought i would share it with anyone who is interested. Will have them a few hours. Note: this function creates a list of SQL statements that can be copied and executed on the Postgre database. Maybe someone smarter then me can get Postgre to create and execute the statements all in one function.
CREATE OR REPLACE FUNCTION SearchAllTables(_search text) RETURNS TABLE( txt text ) as $funct$
DECLARE __COUNT int;
__SQL text;
BEGIN
EXECUTE 'SELECT COUNT(0) FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = ''text''
AND table_schema = ''public'' ' INTO __COUNT;
RETURN QUERY
SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY table_name) < __COUNT THEN
'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "' || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search || '%'' UNION ALL'
ELSE
'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "' || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search || '%'''
END AS txt
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE = 'text'
AND table_schema = 'public';
END
$funct$ LANGUAGE plpgsql;
Other answers have already explained meaning of None beautifully. However, I would still like to throw more light on this using an example.
Example:
def extendList(val, list=[]):
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
Now try to guess output of above list. Well, the answer is surprisingly as below:
list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']
But Why?
Many will mistakenly expect list1 to be equal to [10] and list3 to be equal to ['a'], thinking that the list argument will be set to its default value of [] each time extendList is called.
However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it’s called.
list1 and list3 are therefore operating on the same default list, whereas list2 is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).
'None' the savior: (Modify example above to produce desired behavior)
def extendList(val, list=None):
if list is None:
list = []
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
With this revised implementation, the output would be:
list1 = [10]
list2 = [123]
list3 = ['a']
Note - Example credit to toptal.com
Here is my suggested validation:
var isValid = false;
// Check whether this entered value is numeric.
function checkNumeric() {
var numericVal = document.getElementById("txt_numeric").value;
if(isNaN(numericVal) || numericVal == "" || numericVal == null || numericVal.indexOf(' ') >= 0) {
alert("Please, enter a numeric value!");
isValid = false;
} else {
isValid = true;
}
}
I like overriding jQuery widgets.
(function ($) {
$.widget("sauti.dialog", $.ui.dialog, {
options: {
headerVisible: false
},
_create: function () {
// ready to generate button
this._super("_create"); // for 18 would be $.Widget.prototype._create.call(this);
// decide if header is visible
if(this.options.headerVisible == false)
this.uiDialogTitlebar.hide();
},
_setOption: function (key, value) {
this._super(key, value); // for 1.8 would be $.Widget.prototype._setOption.apply( this, arguments );
if (key === "headerVisible") {
if (key == false)
this.uiDialogTitlebar.hide();
else
this.uiDialogTitlebar.show();
return;
}
}
});
})(jQuery);
So you can now setup if you want to show title bar or not
$('#mydialog').dialog({
headerVisible: false // or true
});
bs := string(body)
should be enough to give you a string.
From there, you can use it as a regular string.
A bit as in this thread:
var client http.Client
resp, err := client.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
log.Info(bodyString)
}
See also GoByExample.
As commented below (and in zzn's answer), this is a conversion (see spec).
See "How expensive is []byte(string)
?" (reverse problem, but the same conclusion apply) where zzzz mentioned:
Some conversions are the same as a cast, like
uint(myIntvar)
, which just reinterprets the bits in place.
Sonia adds:
Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. Thebytes.Buffer
type is often useful.
Make sure you're not sending a '#' at the end of your URL. In my case, that was preventing window.location.href from working.
$users = Get-ADGroupMember -Identity 'Client Services' -Recursive ; $users.count
The above one-liner gives a clean count of recursive members found. Simple, easy, and one line.
DECLARE @seconds AS int = 896434;
SELECT
CONVERT(varchar, (@seconds / 86400)) --Days
+ ':' +
CONVERT(varchar, DATEADD(ss, @seconds, 0), 108); --Hours, Minutes, Seconds
Outputs:
10:09:00:34
I'd recommend looking for something such as Forever to restart Node in the event of a crash, and handle daemonizing this for you.
I used GEOIP db and created a function. You can consume this link directly http://jamhubsoftware.com/geoip/getcountry.php
{"country":["India"],"isoCode":["IN"],"names":[{"de":"Indien","en":"India","es":"India","fr":"Inde","ja":"\u30a4\u30f3\u30c9","pt-BR":"\u00cdndia","ru":"\u0418\u043d\u0434\u0438\u044f","zh-CN":"\u5370\u5ea6"}]}
you can download autoload.php and .mmdb file from https://dev.maxmind.com/geoip/geoip2/geolite2/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ip_address = $_SERVER['REMOTE_ADDR'];
//$ip_address = '3.255.255.255';
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader('/var/www/html/geoip/GeoLite2-City.mmdb');
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $reader->city($ip_address);
//print($record->country->isoCode . "\n"); // 'US'
//print($record->country->name . "\n"); // 'United States'
$rows['country'][] = $record->country->name;
$rows['isoCode'][] = $record->country->isoCode;
$rows['names'][] = $record->country->names;
print json_encode($rows);
//print($record->country->names['zh-CN'] . "\n"); // '??'
//
//print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
//print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
//
//print($record->city->name . "\n"); // 'Minneapolis'
//
//print($record->postal->code . "\n"); // '55455'
//
//print($record->location->latitude . "\n"); // 44.9733
//print($record->location->longitude . "\n"); // -93.2323
?>
To delete the complete contents including the folder structure use
get-childitem $dest -recurse | foreach ($_) {remove-item $_.fullname -recurse}
The -recurse
added to remove-item
ensures interactive prompts are disabled.
I am not sure if this is the best way to use GSON, but works for me. You can use some like this on the MainActivity
:
public void readJson() {
dataArrayList = new ArrayList<>();
String json = "[\n" + IOHelper.getData(this) + "\n]\n";
Log.d(TAG, json);
try{
JSONArray channelSearchEnums = new JSONArray(json);
for(int i=0; i< channelSearchEnums.length(); i++)
{
JSONObject enum = channelSearchEnums.getJSONObject(i);
ChannelSearchEnum channel = new ChannelSearchEnum(
enum.getString("updated_at"), enum.getString("fetched_at"),
enum.getString("description"), enum.getString("language"),
enum.getString("title"), enum.getString("url"),
enum.getString("icon_url"), enum.getString("logo_url"),
enum.getString("id"), enum.getString("modified"))
dataArrayList.add(channel);
}
//The code and place you want to show your data
}catch (Exception e)
{
Log.d(TAG, e.getLocalizedMessage());
}
}
You only have strings, but if you would have doubles or int, you could put getDouble
or getInt
too.
The method of IOHelper
class is the next (Here, the path is save on the internal Storage):
public static String getData(Context context) {
try {
File f = new File(context.getFilesDir().getPath() + "/" + fileName);
//check whether file exists
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
return null;
}
}
If you want more information about this, you can see this video, where I get the code of readJson()
; and this thread where I get the code of getData()
.
You should use hasOwnProperty
. For example:
myObj.hasOwnProperty('myKey');
Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:
Object.prototype.hasOwnProperty.call(myObj, 'myKey');
One special case for this is if you have used a construction like the following in your ~/.muttrc:
# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"
This send-hook will override either of these:
mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"
Your emails will still go out with the header:
From: Real Name <[email protected]>
In this case, the only command line solution I've found is actually overriding the send-hook itself:
mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""
In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).
Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184
Yes surely you can add one, as already mentioned for initialization of Abstract class variables. BUT if you dont explicitly declare one, it anyways has an implicit constructor for "Constructor Chaining" to work.
For not very sharp eyes like mine, I had href
instead of routerLink
, took me a few searches to figure that out #facepalm.
Right. In most, if not all implementations of C, the array identifier can be implicitly casted to a pointer to the first element (i.e. the first element's address). What you're doing here is comparing those addresses, which is obviously wrong.
Instead, you need to iterate over both arrays, checking each element against each other. If you get to the end of both without a failure, they're equal.
I also tried this style for ionic hybrid app background. this is also having style for background blur effect.
.bg-image {
position: absolute;
background: url(../img/bglogin.jpg) no-repeat;
height: 100%;
width: 100%;
background-size: cover;
bottom: 0px;
margin: 0 auto;
background-position: 50%;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:
$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");
You just need to put "group(1)" instead of "group()" in the following line and the return will be the one you expected:
System.out.println("I found the text: " + matcher.group(**1**).toString());
I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:
unordered_map
separately, instead of using the equality comparison operator (operator==
). This might be helpful, for example, if you want to use the latter for comparing all members of two Node
objects to each other, but only some specific members as key of an unordered_map
.All in all, for your Node
class, the code could be written as follows:
using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);
Notes:
$("#form input , select , textarea").keypress(function(e){
if(e.keyCode == 13){
var enter_position = $(this).index();
$("#form input , select , textarea").eq(enter_position+1).focus();
}
});
Android Supports SSL implementation by default except for Android N (API level 24) and below Android 5.1 (API level 22)
I was getting the error when making the API call below API level 22 devices after implementing SSL at the server side; that was while creating OkHttpClient client object, and fixed by adding connectionSpecs() method OkHttpClient.Builder class.
the error received was
response failure: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb8882c00: I/O error during system call, Connection reset by peer
so I fixed this by added the check like
if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
// Do something for below api level 22
List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
if (specsList != null) {
okb.connectionSpecs(specsList);
}
}
Also for the Android N (API level 24); I was getting the error while making the HTTP call like
HTTP FAILED: javax.net.ssl.SSLHandshakeException: Handshake failed
and this is fixed by adding the check for Android 7 particularly, like
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
// Do something for naugat ; 7
okb.connectionSpecs(Collections.singletonList(getSpec()));
}
So my final OkHttpClient object will be like:
OkHttpClient client
HttpLoggingInterceptor httpLoggingInterceptor2 = new
HttpLoggingInterceptor();
httpLoggingInterceptor2.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okb = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor2)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request request2 = request.newBuilder().addHeader(AUTH_KEYWORD, AUTH_TYPE_JW + " " + password).build();
return chain.proceed(request2);
}
}).connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS);
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
// Do something for naugat ; 7
okb.connectionSpecs(Collections.singletonList(getSpec()));
}
if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
if (specsList != null) {
okb.connectionSpecs(specsList);
}
}
//init client
client = okb.build();
getSpecsBelowLollipopMR1 function be like,
private List<ConnectionSpec> getSpecsBelowLollipopMR1(OkHttpClient.Builder okb) {
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
okb.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));
ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
List<ConnectionSpec> specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
return specs;
} catch (Exception exc) {
Timber.e("OkHttpTLSCompat Error while setting TLS 1.2"+ exc);
return null;
}
}
The Tls12SocketFactory class will be found in below link (comment by gotev):
https://github.com/square/okhttp/issues/2372
For more support adding some links below this will help you in detail,
https://developer.android.com/training/articles/security-ssl
If it's about just one property - let's say you want to temporarily change some default, for instance disable CA checking: you can do it with
npm config set ca ""
To come back to the defaults for that setting, simply
npm config delete ca
To verify, use npm config get ca
.
I usually do it the way that you are doing it (i.e. sudo -u username command). But, there is also the 'djb' way to run a daemon with privileges of another user. See: http://thedjbway.b0llix.net/daemontools/uidgid.html
So here is my solution (similar to John Vance's answer):
First go here and get a function to detect mobile browsers.
http://detectmobilebrowsers.com/
They have a lot of different ways to detect if you are on mobile, so find one that works with what you are using.
Your HTML page (pseudo code):
If Mobile Then
<input id="selling-date" type="date" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
else
<input id="selling-date" type="text" class="date-picker" readonly="readonly" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
JQuery:
$( ".date-picker" ).each(function() {
var min = $( this ).attr("min");
var max = $( this ).attr("max");
$( this ).datepicker({
dateFormat: "yy-mm-dd",
minDate: min,
maxDate: max
});
});
This way you can still use native date selectors in mobile while still setting the min and max dates either way.
The field for non mobile should be read only because if a mobile browser like chrome for ios "requests desktop version" then they can get around the mobile check and you still want to prevent the keyboard from showing up.
However if the field is read only it could look to a user like they cant change the field. You could fix this by changing the CSS to make it look like it isn't read only (ie change border-color to black) but unless you are changing the CSS for all input tags you will find it hard to keep the look consistent across browsers.
To get arround that I just add a calendar image button to the date picker. Just change your JQuery code a bit:
$( ".date-picker" ).each(function() {
var min = $( this ).attr("min");
var max = $( this ).attr("max");
$( this ).datepicker({
dateFormat: "yy-mm-dd",
minDate: min,
maxDate: max,
showOn: "both",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
buttonText: "Select date"
});
});
Note: you will have to find a suitable image.
android:editable
If set, specifies that this TextView
has an input method. It will be a textual one unless it has otherwise been specified. For TextView
, this is false by default. For EditText
, it is true by default.
Must be a boolean
value, either true
or false
.
This may also be a reference to a resource (in the form @[package:]type:name
) or theme attribute (in the form ?[package:][type:]name
) containing a value of this type.
This corresponds to the global attribute resource symbol editable.
Related Methods
I've recently made a page loader in vanilla .js
for a project, just wanted to share it as all the other answers are jQuery based. It's a plug and play, one-liner.
It automatically creates a <div>
tag prepended to the <body>
, with a <svg>
loader. If you want to customize the color you just have to update the t
variable at the beginning of the script.
var t="#106CF6",u=document.querySelector("*"),s=document.createElement("style"),a=document.createElement("aside"),m="http://www.w3.org/2000/svg",g=document.createElementNS(m,"svg"),c=document.createElementNS(m,"circle");document.head.appendChild(s),(s.innerHTML="#sailor {background:"+t+";color:"+t+";display:flex;align-items:center;justify-content:center;position:fixed;top:0;height:100vh;width:100vw;z-index:2147483647}@keyframes swell{to{transform:rotate(360deg)}}#sailor svg{animation:.3s swell infinite linear}"),a.setAttribute("id","sailor"),document.body.prepend(a),g.setAttribute("height","50"),g.setAttribute("filter","brightness(175%)"),g.setAttribute("viewBox","0 0 100 100"),a.prepend(g),c.setAttribute("cx","50"),c.setAttribute("cy","50"),c.setAttribute("r","35"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-dasharray","165 57"),c.setAttribute("stroke-width","10"),g.prepend(c),(u.style.pointerEvents="none"),(u.style.userSelect="none"),(u.style.cursor="wait"),window.addEventListener("load",function(){setTimeout(function(){(u.style.pointerEvents=""),(u.style.userSelect=""),(u.style.cursor="");a.remove()},100)})
You can see the full project and documentation on the GitHub
jQuery and console.log
are unrelated entities, although useful when used together.
If you use a browser's built-in dev tools, console.log
will log information about the object being passed to the log
function.
If the console is not active, logging will not work, and may break your script. Be certain to check that the console exists before logging:
if (window.console) console.log('foo');
The shortcut form of this might be seen instead:
window.console&&console.log('foo');
There are other useful debugging functions as well, such as debug
, dir
and error
. Firebug's wiki lists the available functions in the console api.
$(document).ready(function() {
$("#form1").validate({
rules: {
field1: "required"
},
messages: {
field1: "Please specify your name"
}
})
});
<form id="form1" name="form1">
Field 1: <input id="field1" type="text" class="required">
<input id="btn" type="submit" value="Validate">
</form>
You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.
I was crazy to delete node and npm and nodejs from my Ubuntu 14.04 but with this steps you will remove it:
sudo apt-get uninstall nodejs npm node
sudo apt-get remove nodejs npm node
If you uninstall correctly and it is still there, check these links:
You can also try using find
:
find / -name "node"
Although since that is likely to take a long time and return a lot of confusing false positives, you may want to search only PATH locations:
find $(echo $PATH | sed 's/:/ /g') -name "node"
It would probably be in /usr/bin/node
or /usr/local/bin
. After finding it, you can delete it using the correct path, eg:
sudo rm /usr/bin/node
Try following command sequence on Ubuntu terminal:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
String testString = "This is a sentence";
String[] parts = testString.split(" ");
String lastWord = parts[parts.length - 1];
System.out.println(lastWord); // "sentence"
Just right click the Project -- Properties and select Resource on the left side menu.
You can now change the Text-file encoding to whatever you wish.
I thought all of them were great but I had troubles actually getting them to work with javascript and c#. Here is what I did. Hope it helps someone else.
//put this at the top of the page
<script src="https://www.google.com/recaptcha/api.js"></script>
//put this under the script tag
<script>
var isCaptchaValid = false;
function doCaptchaValidate(source, args) {
args.IsValid = isCaptchaValid;
}
var verifyCallback = function (response) {
isCaptchaValid = true;
};
</script>
//retrieved from google and added callback
<div class="g-recaptcha" data-sitekey="sitekey" data-callback="verifyCallback">
//created a custom validator and added error message and ClientValidationFucntion
<asp:CustomValidator runat="server" ID="CustomValidator1" ValidationGroup="Initial" ErrorMessage="Captcha Required" ClientValidationFunction="doCaptchaValidate"/>
You can also try right menu click option to format the selection of the coding document. Take a look at below screen shot
rgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch(i) {
case R.id.type_car:
num=1;
Toast.makeText(getApplicationContext()," Car",Toast.LENGTH_LONG).show();
break;
case R.id.type_bike:
num=2;
Toast.makeText(getApplicationContext()," Bike",Toast.LENGTH_LONG).show();
break;
}
}
});
Finally, it worked. Thank you guys.
I was not getting it to work because i was trying to resize the label in heightForRowAtIndexPath
method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
and (yeah silly me), i was resizing the label to default in cellForRowAtIndexPath
method - i was overlooking the code i had written earlier:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
The problem I faced was in client server environment. The client was trying to connect over http port 80 but wanted the server proxy to redirect the request to some other port and data was https. So basically asking secure information over http. So server should have http port 80 as well as the port client is requesting, let's say urla:1111\subB
.
The issue was server was hosting this on some other port e,g urla:2222\subB
; so the client was trying to access over 1111 was receiving the error. Correcting the port number should fix this issue. In this case to port number 1111.
If you use dplyr
package you can do:
library(dplyr)
filter(df, aged <= laclen)
Here is a simple one liner with O(N)
, no complicated loops necessary.
> Object.keys(['a', 'b', 'a'].reduce((l, r) => l[r] = l, {})).sort()
[ 'a', 'b' ]
Explanation
Original data set, assume its coming in from an external function
const data = ['a', 'b', 'a']
We want to group all the values onto an object as keys as the method of deduplication. So we use reduce with an object as the default value:
[].reduce(fn, {})
The next step is to create a reduce function which will put the values in the array onto the object. The end result is an object with a unique set of keys.
const reduced = data.reduce((l, r) => l[r] = l, {})
We set l[r] = l
because in javascript the value of the assignment expression is returned when an assignment statement is used as an expression. l
is the accumulator object and r
is the key value. You can also use Object.assign(l, { [r]: (l[r] || 0) + 1 })
or something similar to get the count of each value if that was important to you.
Next we want to get the keys of that object
const keys = Object.keys(reduced)
Then simply use the built-in sort
console.log(keys.sort())
Which is the set of unique values of the original array, sorted
['a', 'b']
You can use case class to prepare sample dataset ...
which is optional for ex: you can get DataFrame
from hiveContext.sql
as well..
import org.apache.spark.sql.functions.col
case class Person(name: String, age: Int, personid : Int)
case class Profile(name: String, personid : Int , profileDescription: String)
val df1 = sqlContext.createDataFrame(
Person("Bindu",20, 2)
:: Person("Raphel",25, 5)
:: Person("Ram",40, 9):: Nil)
val df2 = sqlContext.createDataFrame(
Profile("Spark",2, "SparkSQLMaster")
:: Profile("Spark",5, "SparkGuru")
:: Profile("Spark",9, "DevHunter"):: Nil
)
// you can do alias to refer column name with aliases to increase readablity
val df_asPerson = df1.as("dfperson")
val df_asProfile = df2.as("dfprofile")
val joined_df = df_asPerson.join(
df_asProfile
, col("dfperson.personid") === col("dfprofile.personid")
, "inner")
joined_df.select(
col("dfperson.name")
, col("dfperson.age")
, col("dfprofile.name")
, col("dfprofile.profileDescription"))
.show
sample Temp table approach which I don't like personally...
df_asPerson.registerTempTable("dfperson");
df_asProfile.registerTempTable("dfprofile")
sqlContext.sql("""SELECT dfperson.name, dfperson.age, dfprofile.profileDescription
FROM dfperson JOIN dfprofile
ON dfperson.personid == dfprofile.personid""")
Note : 1) As mentioned by @RaphaelRoth ,
val resultDf = PersonDf.join(ProfileDf,Seq("personId"))
is good approach since it doesnt have duplicate columns from both sides if you are using inner join with same table.
2) Spark 2.x example updated in another answer with full set of join operations supported by spark 2.x with examples + result
Also, important thing in joins : broadcast function can help to give hint please see my answer
You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:
1 In Web.config
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
Internet or network address: your proxy address
User name: your user name
Password: you pass
This configuration worked for me, without change the code.
Your sklearn version is too low, model_selection
is imported by 0.18.1, so please update the sklearn version.
I believe the get()
function immediately runs the select query and does not accept ORDER BY
conditions as parameters. I think you'll need to separately declare the conditions, then run the query. Give this a try:
$this->db->from($this->table_name);
$this->db->order_by("name", "asc");
$query = $this->db->get();
return $query->result();
Actually I agree with @odedbreiner but I put the dialog_frame inside the first layer and hide the black background under the white layer.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@android:drawable/dialog_frame"
android:right="2dp" android:left="2dp" android:bottom="2dp" android:top="5dp" >
<shape android:shape="rectangle">
<corners android:radius="5dp"/>
</shape>
</item>
<item>
<shape
android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="5dp"/>
</shape>
</item>
</layer-list>
You can access the Axes instance (ax
) with plt.gca()
. In this case, you can use
plt.gca().legend()
You can do this either by using the label=
keyword in each of your plt.plot()
calls or by assigning your labels as a tuple or list within legend
, as in this working example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()
However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax
with
ax = plt.gca()
and then calling ax
instead of plt.gca()
.
A BufferedReader can be opened and closed but a File is never opened, it just represents a path in the filesystem.
Maybe this is not the answer you needed, but I encountered similar problem, so I decided to put it here.
I needed to convert 500 xml files to UTF8 via Notepad++. Why Notepad++? When I used the option "Encode in UTF8" (many other converters use the same logic) it messed up all special characters, so I had to use "Convert to UTF8" explicitly.
Here some simple steps to convert multiple files via Notepad++ without messing up with special characters (for ex. diacritical marks).
convertToUTF8.py
import os
import sys
from Npp import notepad # import it first!
filePathSrc="C:\\Users\\" # Path to the folder with files to convert
for root, dirs, files in os.walk(filePathSrc):
for fn in files:
if fn[-4:] == '.xml': # Specify type of the files
notepad.open(root + "\\" + fn)
notepad.runMenuCommand("Encoding", "Convert to UTF-8")
# notepad.save()
# if you try to save/replace the file, an annoying confirmation window would popup.
notepad.saveAs("{}{}".format(fn[:-4], '_utf8.xml'))
notepad.close()
After all, run the script
Quickest (drops and creates all tables including data):
./manage.py reset appname | ./manage.py dbshell
Caution:
I got the same problem. This code works well on my case.
// Replace broken images by a default img
$('img').each(function(){
if($(this).attr('src') === ''){
this.src = '/default_feature_image.png';
}
});
Please try this,
SELECT
c.Id,
c.name,
(SELECT pi.price FROM purchase pi WHERE pi.Id = MAX(p.Id)) AS [LastPurchasePrice]
FROM customer c INNER JOIN purchase p
ON c.Id = p.customerId
GROUP BY c.Id,c.name;
If speed is a concern, why not partition off the most commonly used set of inputs and their values to a lookup table and then do whatever optimized magic algorithm you have come up with for the exceptional cases?
Click the line number, and then copy and paste the link from the address bar. To select a range, click the number, and then shift click the later number.
Alternatively, the links are a relatively simple format, just append #L<number>
to the end for that specific line number, using the link to the file. Here's a link to the third line of the git
repository's README
:
There are 3 ways to do this:
Right-click on the Chart and click Select Data then edit the series names directly as shown below.
You can either specify the values directly e.g. Series 1
or specify a range e.g. =A2
Simply select your data range (in similar format as I specified) and create a simple bar chart. The labels should be defined automatically.
Similarly you can define the series names dynamically using VBA. A simple example below:
ActiveChart.ChartArea.Select
ActiveChart.FullSeriesCollection(1).Name = "=""Hello"""
This will redefine the first series name. Just change the index from (1)
to e.g. (2)
and so on to change the following series names. What does the VBA above do? It sets the series name to Hello
as "=""Hello"""
translates to ="Hello"
("
have to be escaped by a preceding "
).
I have come to share an solution. The error happened to me after forcing the notbook to hang up. possible solution clean preject
.
It's rather hacky, but you could use one1
as a Float64Index
to do everything in one go:
df.set_index('one').sort_index().groupby('key1')['two'].plot(style='--o', legend=True)
Note that as of 0.20.3, sorting the index is necessary, and the legend is a bit wonky.
str() is used for creating output for end user while repr() is used for debuggin development.And it's represent the official of object.
Example:
>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2018-04-08 18:00:15.178404'
>>> repr(today)
'datetime.datetime(2018, 4, 8, 18, 3, 21, 167886)'
From output we see that repr() shows the official representation of date object.
The tibble vignette has an updated way to change its default printing behavior:
You can control the default appearance with options:
options(tibble.print_max = n, tibble.print_min = m)
: if there are more than n rows, print only the first m rows. Useoptions(tibble.print_max = Inf)
to always show all rows.
options(tibble.width = Inf)
will always print all columns, regardless of the width of the screen.
examples
This will always print all rows:
options(tibble.print_max = Inf)
This will not actually limit the printing to 50 lines:
options(tibble.print_max = 50)
But this will restrict printing to 50 lines:
options(tibble.print_max = 50, tibble.print_min = 50)
Based on @Dave Syers answer I add the following class to my Spring Boot project:
@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
private static final Logger LOG = LoggerFactory.getLogger(StaticResourceConfiguration.class);
@Value("${static.path}")
private String staticPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(staticPath != null) {
LOG.info("Serving static content from " + staticPath);
registry.addResourceHandler("/**").addResourceLocations("file:" + staticPath);
}
}
// see https://stackoverflow.com/questions/27381781/java-spring-boot-how-to-map-my-my-app-root-to-index-html
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/index.html");
}
}
This allows me to start my spring boot app with the parameter --static.path
like
java -jar spring-app-1.0-SNAPSHOT.jar --static.path=/path/to/my/static-files/
This can be very handy for development and testing.
Why not try something like this?
$('#menu li a').on('click', function(){
$('#menu li a.current').removeClass('current');
$(this).addClass('current');
});
The following method will do the task:
public static int sumOfDigits(int n) {
String digits = new Integer(n).toString();
int sum = 0;
for (char c: digits.toCharArray())
sum += c - '0';
return sum;
}
You can use it like this:
System.out.printf("Sum of digits = %d%n", sumOfDigits(321));
The short answer: the setting needs to be setup when the connection to the MySQL server is established. For example, if using MYSQLi / PHP, it will look something like this:
$ myConn = mysqli_init();
$ myConn->options(MYSQLI_INIT_COMMAND, 'SET SESSION group_concat_max_len = 1000000');
Therefore, if you are using a home-brewed framework, well, you need to look for the place in the code when the connection is establish and provide a sensible value.
I am still using Codeigniter 3 on 2020, so in this framework, the code to add is in the application/system/database/drivers/mysqli/mysqli_driver.php, the function is named db_connect();
public function db_connect($persistent = FALSE)
{
// Do we have a socket path?
if ($this->hostname[0] === '/')
{
$hostname = NULL;
$port = NULL;
$socket = $this->hostname;
}
else
{
$hostname = ($persistent === TRUE)
? 'p:'.$this->hostname : $this->hostname;
$port = empty($this->port) ? NULL : $this->port;
$socket = NULL;
}
$client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0;
$this->_mysqli = mysqli_init();
$this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
$this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION group_concat_max_len = 1000000');
...
}
You need to rebuild your workspace using CTRL+B. I a problem where I'd be able to go to the function declarations but for some I wouldn't. After a rebuild, I could do all. I hope that helps.
If you have any difficulties managing your global CLI version it is better to use NVM: MAC, Windows.
To update the local CLI in your Angular project follow this steps:
Starting from CLI v6 you can just run ng update
in order to get your dependencies updated automatically to a new version.
ng update @angular/cli
With ng update
sometimes you might want to add --force
flag.
You can also pass --all
flag to upgrade all packages at the same time.
ng update --all --force
If you want just to migrate CLI just run this:
ng update @angular/cli --migrateOnly
You can also pass flag --from=from
- version from which to migrate from, e.g --from=1.7.4
. This flag is only available with a single package being updated, and only on migration only.
After update is done make sure that the version of typescript you got installed supported by your current angular version, otherwise you might need to downgrade the typescript version. Also bear in mind that usually the latest version of angular won't support the latest version of the typescript.
Checkout
Angular CLI / Angular / NodeJS / Typescript
compatibility versions here
Also checkout this guide Updating your Angular projects and update.angular.io
OLD ANSWER:
All you need to do is to diff with angular-cli-diff and apply the changes in your current project.
Here is the steps:
File changed
tabnpm install
/ yarn
npm scripts
(more details here: https://stackoverflow.com/a/45431592/415078)args should be tuple.
eg:
args = ('A','B')
args = ('A',) # in case of single
If you want first 2 letters and last 2 letters of a string then you can use the following code:
name = "India"
name[0:2]="In"
names[-2:]="ia"
If you use Iclick pluging, it is as simply as you see below.
$('#radio1').iCheck('uncheck');
I had this warning possibly because of calling setState
from an effect hook (This is discussed in these 3 issues linked together).
Anyway, upgrading the react version removed the warning.
You cannot SELECT .. INTO .. a TABLE VARIABLE. The best you can do is create it first, then insert into it. Your 2nd snippet has to be
DECLARE @TempCustomer TABLE
(
CustomerId uniqueidentifier,
FirstName nvarchar(100),
LastName nvarchar(100),
Email nvarchar(100)
);
INSERT INTO
@TempCustomer
SELECT
CustomerId,
FirstName,
LastName,
Email
FROM
Customer
WHERE
CustomerId = @CustomerId
int min and max values
Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807
i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64
if you always want a to be grater that b why do you need to check it? just set it to be true always
I have been faced with this problem.
The cause is your table doesn't have a primary key field.
And I have a simple solution: Set a field to primary key to specific field that suits your business logic.
For example, I have database thesis_db
and field thesis_id
, I will press button Primary (key icon) to set thesis_id
to become primary key field:
Something important when dealing with outliers is that one should try to use estimators as robust as possible. The mean of a distribution will be biased by outliers but e.g. the median will be much less.
Building on eumiro's answer:
def reject_outliers(data, m = 2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/mdev if mdev else 0.
return data[s<m]
Here I have replace the mean with the more robust median and the standard deviation with the median absolute distance to the median. I then scaled the distances by their (again) median value so that m
is on a reasonable relative scale.
Note that for the data[s<m]
syntax to work, data
must be a numpy array.
There are some good plugins to help comment/uncomment lines. For example The NERD Commenter.
In my case this was actually a symptom of the server, hosted on AWS, lacking an IP for the external network. It would attempt to download namespaces from springframework.org and fail to make a connection.
You can use the Set structure from ES6 to make your code faster and more readable:
// Create Set
this.items = new Set();
add(item) {
this.items.add(item);
// Set to array
console.log([...this.items]);
}
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
if("OK".equals(jsonObject.getString("status"))){
String formatted_address;
JSONArray results = jsonObject.getJSONArray("results");
if(results != null && results.size() > 0){
com.alibaba.fastjson.JSONObject object = results.getJSONObject(0);
String addressComponents = object.getString("address_components");
formatted_address = object.getString("formatted_address");
Log.e("amaya","formatted_address="+formatted_address+"--url="+url);
if(findCity){
boolean finded = false;
JSONArray ac = JSONArray.parseArray(addressComponents);
if(ac != null && ac.size() > 0){
for(int i=0;i<ac.size();i++){
com.alibaba.fastjson.JSONObject jo = ac.getJSONObject(i);
JSONArray types = jo.getJSONArray("types");
if(types != null && types.size() > 0){
for(int j=0;j<ac.size();j++){
String string = types.getString(i);
if("administrative_area_level_1".equals(string)){
finded = true;
break;
}
}
}
if(finded) break;
}
}
Log.e("amaya","city="+formatted_address);
}else{
Log.e("amaya","poiName="+hotspotPoi.getPoi_name()+"--"+hotspotPoi);
}
if(hotspotPoi != null) hotspotPoi.setPoi_name(formatted_address);
EventBus.getDefault().post(new AmayaEvent.GeoEvent(hotspotPoi));
}
}
this is a method to parse google feedback data.
Create:
spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinner setCenter:CGPointMake(kScreenWidth/2.0, kScreenHeight/2.0)]; // I do this because I'm in landscape mode
[self.view addSubview:spinner]; // spinner is not visible until started
Start:
[spinner startAnimating];
Stop:
[spinner stopAnimating];
When you're finally done, remove the spinner from the view and release.
If anyone is still facing this issue, Captor annotation worked for me
@Captor
private ArgumentCaptor<Object> argumentCaptor;
Then I was able to mock the request by:
ResponseEntity<YourTestResponse> testEntity = new ResponseEntity<>(
getTestFactoryResponse(),
HttpStatus.OK);
when(mockRestTemplate.exchange((String) argumentCaptor.capture(),
(HttpMethod) argumentCaptor.capture(),
(HttpEntity<?>) argumentCaptor.capture(),
(Class<YourTestResponse.class>) any())
).thenReturn(testEntity);
SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)
Yes.
new ArrayList<String>(){{
add("A");
add("B");
}}
What this is actually doing is creating a class derived from ArrayList<String>
(the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this
pointer. Not a problem unless you want to serialise it, or you're expecting the outer class to be garbage collected.
I understand that Java 7 will provide additional language constructs to do precisely what you want.
EDIT: recent Java versions provide more usable functions for creating such collections, and are worth investigating over the above (provided at a time prior to these versions)
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
I know this post is old, but what i had to do in the case of the above answers on Linux machine was:
sudo chmod +x directory
In case if you have several Java versions on your machine and you want to choose it dynamically at runtime, i.e, in my case, I have two versions:
ls -la /Library/Java/JavaVirtualMachines
drwxr-xr-x 3 root wheel 96B Nov 16 2014 jdk1.7.0_71.jdk/
drwxr-xr-x 3 root wheel 96B Mar 1 2015 jdk1.8.0_31.jdk/
You can change them by modifying the /etc/profile content. Just add (or modify) the following two lines at the end of the file:
export JAVA_HOME=YOUR_JAVA_PATH/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
In my case, it should be like the following if I want to use:
Java 7:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
Java 8:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
After saving the file, please run source /etc/profile
and it should work. Here are results when I use the first and second option accordingly:
Java 7:
java -version
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java 8:
java -version
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
The process is similar if your java folder is located in different locations.
mydata$sCode == "CA"
will return a boolean array, with a TRUE
value everywhere that the condition is met. To illustrate:
> mydata = data.frame(sCode = c("CA", "CA", "AC"))
> mydata$sCode == "CA"
[1] TRUE TRUE FALSE
There are a couple of ways to deal with this:
sum(mydata$sCode == "CA")
, as suggested in the comments; because
TRUE
is interpreted as 1 and FALSE
as 0, this should return the
numer of TRUE
values in your vector.
length(which(mydata$sCode == "CA"))
; the which()
function
returns a vector of the indices where the condition is met, the
length of which is the count of "CA"
.
Edit to expand upon what's happening in #2:
> which(mydata$sCode == "CA")
[1] 1 2
which()
returns a vector identify each column where the condition is met (in this case, columns 1 and 2 of the dataframe). The length()
of this vector is the number of occurences.
Inspired by the work of Josien, I wondered about a simplification.
Would this also work? Much shorter:
SELECT SUBSTRING(col, CHARINDEX ('/', col) + 1, CHARINDEX ('.', col) - CHARINDEX ('/', col) - 1);
(I can't test right now because of right issues at my company SQL server, which is a problem in its own right)
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
HTTP_REFERER - sent by the browser, stating the last page the browser viewed!
If you trusting [HTTP_REFERER] for any reason that is important, you should not, since it can be faked easily:
Try this firefox extension, you'll be able to set any headers you want:
@Master of Celebration:
Firefox:
extensions: refspoof, refontrol, modify headers, no-referer
Completely disable: the option is available in about:config under "network.http.sendRefererHeader" and you want to set this to 0 to disable referer passing.
Google chrome / Chromium:
extensions: noref, spoofy, external noreferrer
Completely disable: Chnage ~/.config/google-chrome/Default/Preferences or ~/.config/chromium/Default/Preferences and set this:
{
...
"enable_referrers": false,
...
}
Or simply add --no-referrers to shortcut or in cli:
google-chrome --no-referrers
Opera:
Completely disable: Settings > Preferences > Advanced > Network, and uncheck "Send referrer information"
Spoofing web service:
Standalone filtering proxy (spoof any header):
Spoofing http_referer when using wget
‘--referer=url’
Spoofing http_referer when using curl
-e, --referer
Spoofing http_referer wth telnet
telnet www.yoursite.com 80 (press return)
GET /index.html HTTP/1.0 (press return)
Referer: http://www.hah-hah.com (press return)
(press return again)
Although Bootstrap CDN restored glyphicons to bootstrap.min.css, Bootstrap CDN's Bootswatch css files doesn't include glyphicons.
For example Amelia theme: http://bootswatch.com/amelia/
Default Amelia has glyphicons in this file: http://bootswatch.com/amelia/bootstrap.min.css
But Bootstrap CDN's css file doesn't include glyphicons: http://netdna.bootstrapcdn.com/bootswatch/3.0.0/amelia/bootstrap.min.css
So as @edsioufi mentioned, you should include you should include glphicons css, if you use Bootswatch files from the bootstrap CDN. File: http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css
The commands below are for Mac but pretty similar to Linux (see the links below)
#Install pyenv
brew update
brew install pyenv
Let's say you have python 3.6 as your primary version on your mac:
python --version
Output:
Python <your current version>
pyenv install -l
Let's take 3.7.3:
pyenv install 3.7.3
Make sure to run this in the Terminal (add it to ~/.bashrc or ~/.zshrc):
export PATH="/Users/username/.pyenv:$PATH"
eval "$(pyenv init -)"
Now let's run it only on the opened terminal/shell:
pyenv shell 3.7.3
python --version
Output:
Python 3.7.3
And not less important unset it in the opened shell/iTerm:
pyenv shell --unset
Please try CURRENT_TIME()
or now()
functions
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"
OR
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"
OR you could try with PHP date
function here:
$date = date("Y-m-d H:i:s");
In case you want to chain a lot of querysets, try this:
from itertools import chain
result = list(chain(*docs))
where: docs is a list of querysets
Create a C# project and write the following code.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
run_cmd();
}
private void run_cmd()
{
string fileName = @"C:\sample_script.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Console.ReadLine();
}
}
}
print "Python C# Test"
You will see the 'Python C# Test' in the console of C#.
Here's the complete solution if you want to implement the wifi hotspot feature programmatically in your android app.
SOLUTION FOR API < 26:
For devices < API 26. There is no public API by Android for this purpose. So, in order to work with those APIs you've to access private APIs through reflection. It is not recommended but if you've no other options left, then here's a trick.
First of all, you need to have this permission in your manifest,
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Here's how you can ask it on run-time:
private boolean showWritePermissionSettings() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
if (!Settings.System.canWrite(this)) {
Log.v("DANG", " " + !Settings.System.canWrite(this));
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
return false;
}
}
return true; //Permission already given
}
You can then access the setWifiEnabled
method through reflection. This returns true if the action you asked for is being process correctly i.e. enabling/disabling hotspot.
public boolean setWifiEnabled(WifiConfiguration wifiConfig, boolean enabled) {
WifiManager wifiManager;
try {
if (enabled) { //disables wifi hotspot if it's already enabled
wifiManager.setWifiEnabled(false);
}
Method method = wifiManager.getClass()
.getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(wifiManager, wifiConfig, enabled);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return false;
}
}
You can also get the wificonfiguration of your hotspot through reflection. I've answered that method for this question on StackOverflow.
P.S: If you don't want to turn on hotspot programmatically, you can start this intent and open the wifi settings screen for user to turn it on manually.
SOLUTION FOR API >= 26:
Finally, android released an official API for versions >= Oreo. You can just use the public exposed API by android i.e. startLocalOnlyHotspot
It turns on a local hotspot without internet access. Which thus can be used to host a server or transfer files.
It requires Manifest.permission.CHANGE_WIFI_STATE
and ACCESS_FINE_LOCATION
permissions.
Here's a simple example of how you can turn on hotspot using this API.
private WifiManager wifiManager;
WifiConfiguration currentConfig;
WifiManager.LocalOnlyHotspotReservation hotspotReservation;
The method to turn on hotspot:
@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOnHotspot() {
wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
hotspotReservation = reservation;
currentConfig = hotspotReservation.getWifiConfiguration();
Log.v("DANG", "THE PASSWORD IS: "
+ currentConfig.preSharedKey
+ " \n SSID is : "
+ currentConfig.SSID);
hotspotDetailsDialog();
}
@Override
public void onStopped() {
super.onStopped();
Log.v("DANG", "Local Hotspot Stopped");
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
Log.v("DANG", "Local Hotspot failed to start");
}
}, new Handler());
}
`
Here's how you can get details of the locally created hotspot
private void hotspotDetaisDialog()
{
Log.v(TAG, context.getString(R.string.hotspot_details_message) + "\n" + context.getString(
R.string.hotspot_ssid_label) + " " + currentConfig.SSID + "\n" + context.getString(
R.string.hotspot_pass_label) + " " + currentConfig.preSharedKey);
}
If it throws, a security exception even after giving the required permissions then you should try enabling your location using GPS. Here's the solution.
Recently, I've developed a demo app called Spotserve. That turns on wifi hotspot for all devices with API>=15 and hosts a demo server on that hotspot. You can check that for more details. Hope this helps!
It's already 2017, and you can now use Apache Commons Collections4
The usage:
for(Object obj : CollectionUtils.emptyIfNull(list1)){
// Do your stuff
}
You can use T-SQL:
use master
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
I use this as a part of restore from production server to testing machine:
USE master
GO
ALTER DATABASE yourDbName SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE yourDbName FROM DISK = 'd:\DropBox\backup\myDB.bak'
ALTER DATABASE yourDbName SET ONLINE
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
You will need to use localized name of services in case of German or French Windows, see How to create a SQL Server login for a service account on a non-English Windows?
You can try ezxml -- it's a lightweight parser written entirely in C.
For C++ you can check out TinyXML++
As Parag's solution threw an error for me, here's my solution (combining David Hedlund's and Parag's):
if (!$("input[name='name']").is(':checked')) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
This worked fine for me!
Try something like this:
public class test
{
public static void main(String a[])
{
long tmp = 1346524199000;
Date d = new Date(tmp);
System.out.println(d);
}
}
Other problem that might be causing such behavior are build configurations.
I had two projects with configurations set to be built to specific folders.
Like Debug
and Any CPU
and in second it was Debug
and x86
.
What I did I went to Solution->Context menu->Properties->Configuration properties->Configuration
and I set all my projects to use same configurations Debug
and x86
and also checked Build
tick mark.
Then projects started to build correctly and were able to see namespaces.
You can't make modification to the collection being iterated within the ForEach block.
A quick fix is to iterate over a copy of the collection. An easy way to make this copy is through the ArrayList constructor. The DataRowView objects in the copied collection will refer to, and be able to modify, the same underlying data as your code.
For Each item As DataRowView In New System.Collections.ArrayList(lbOrdersNeedToBeVoided.Items)
please read http://social.msdn.microsoft.com/Forums/en-AU/vbgeneral/thread/b4d1f649-d78a-4e5b-8ad8-1940e3379bed
Just use:
assert cmp(dict1, dict2) == 0
pll_current_language
Returns the current language
Usage:
pll_current_language( $value );
- $value => (optional) either name or locale or slug, defaults to slug
returns either the full name, or the WordPress locale (just as the WordPress core function ‘get_locale’ or the slug ( 2-letters code) of the current language.
In my case sleep
created side effect so I used wait
let _ = XCTWaiter.wait(for: [XCTestExpectation(description: "Hello World!")], timeout: 2.0)
I have written a C# method that url-encodes ALL symbols:
/// <summary>
/// !#$345Hf} ? %21%23%24%33%34%35%48%66%7D
/// </summary>
public static string UrlEncodeExtended( string value )
{
char[] chars = value.ToCharArray();
StringBuilder encodedValue = new StringBuilder();
foreach (char c in chars)
{
encodedValue.Append( "%" + ( (int)c ).ToString( "X2" ) );
}
return encodedValue.ToString();
}
Add !important
rule to display: table
of your .v-center
class.
.v-center {
display:table !important;
border:2px solid gray;
height:300px;
}
Your display property is being overridden by bootstrap to display: block
.
Eric Lippert wrote a detailed blog post about this subject a while back (additionally comparing it to VBScript). More accurately, he wrote about JScript, which is Microsoft's own implementation of ECMAScript, although very similar to JavaScript. I would imagine that you can assume the vast majority of behaviour would be the same for the JavaScript engine of Internet Explorer. Of course, the implementation will vary from browser to browser, though I suspect you could take a number of the common principles and apply them to other browsers.
Quoted from that page:
JScript uses a nongenerational mark-and-sweep garbage collector. It works like this:
Every variable which is "in scope" is called a "scavenger". A scavenger may refer to a number, an object, a string, whatever. We maintain a list of scavengers -- variables are moved on to the scav list when they come into scope and off the scav list when they go out of scope.
Every now and then the garbage collector runs. First it puts a "mark" on every object, variable, string, etc – all the memory tracked by the GC. (JScript uses the VARIANT data structure internally and there are plenty of extra unused bits in that structure, so we just set one of them.)
Second, it clears the mark on the scavengers and the transitive closure of scavenger references. So if a scavenger object references a nonscavenger object then we clear the bits on the nonscavenger, and on everything that it refers to. (I am using the word "closure" in a different sense than in my earlier post.)
At this point we know that all the memory still marked is allocated memory which cannot be reached by any path from any in-scope variable. All of those objects are instructed to tear themselves down, which destroys any circular references.
The main purpose of garbage collection is to allow the programmer not to worry about memory management of the objects they create and use, though of course there's no avoiding it sometimes - it is always beneficial to have at least a rough idea of how garbage collection works.
Historical note: an earlier revision of the answer had an incorrect reference to the delete
operator. In JavaScript the delete
operator removes a property from an object, and is wholly different to delete
in C/C++.
If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc
file type
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc
If you need to do the filteration on multiple types, use the below command.
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf
Now $fileNames
variable act as an array from which you can loop and apply your business logic.
Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do:
import requests
r1 = requests.post('http://www.yourapp.com/login')
r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)
You could also use sjmisc::add_rows()
, which uses dplyr::bind_rows()
, but unlike bind_rows()
, add_rows()
preserves attributes and hence is useful for labelled data.
See following example with a labelled dataset. The frq()
-function prints frequency tables with value labels, if the data is labelled.
library(sjmisc)
library(dplyr)
data(efc)
# select two subsets, with some identical and else different columns
x1 <- efc %>% select(1:5) %>% slice(1:10)
x2 <- efc %>% select(3:7) %>% slice(11:20)
str(x1)
#> 'data.frame': 10 obs. of 5 variables:
#> $ c12hour : num 16 148 70 168 168 16 161 110 28 40
#> ..- attr(*, "label")= chr "average number of hours of care per week"
#> $ e15relat: num 2 2 1 1 2 2 1 4 2 2
#> ..- attr(*, "label")= chr "relationship to elder"
#> ..- attr(*, "labels")= Named num 1 2 3 4 5 6 7 8
#> .. ..- attr(*, "names")= chr "spouse/partner" "child" "sibling" "daughter or son -in-law" ...
#> $ e16sex : num 2 2 2 2 2 2 1 2 2 2
#> ..- attr(*, "label")= chr "elder's gender"
#> ..- attr(*, "labels")= Named num 1 2
#> .. ..- attr(*, "names")= chr "male" "female"
#> $ e17age : num 83 88 82 67 84 85 74 87 79 83
#> ..- attr(*, "label")= chr "elder' age"
#> $ e42dep : num 3 3 3 4 4 4 4 4 4 4
#> ..- attr(*, "label")= chr "elder's dependency"
#> ..- attr(*, "labels")= Named num 1 2 3 4
#> .. ..- attr(*, "names")= chr "independent" "slightly dependent" "moderately dependent" "severely dependent"
bind_rows(x1, x1) %>% frq(e42dep)
#>
#> # e42dep <numeric>
#> # total N=20 valid N=20 mean=3.70 sd=0.47
#>
#> val frq raw.prc valid.prc cum.prc
#> 3 6 30 30 30
#> 4 14 70 70 100
#> <NA> 0 0 NA NA
add_rows(x1, x1) %>% frq(e42dep)
#>
#> # elder's dependency (e42dep) <numeric>
#> # total N=20 valid N=20 mean=3.70 sd=0.47
#>
#> val label frq raw.prc valid.prc cum.prc
#> 1 independent 0 0 0 0
#> 2 slightly dependent 0 0 0 0
#> 3 moderately dependent 6 30 30 30
#> 4 severely dependent 14 70 70 100
#> NA NA 0 0 NA NA
below answer worked for me, you can try:
sudo apt-get install python3-lxml
You can write "localhost" or "127.0.0.1" but URL must be the same
Example : Google Domains Add-> localhost URL => localhost/login.php
Example : Google Domains Add-> 127.0.0.1 URL => 127.0.0.1/login.php
NULL
isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef>
or #include <stddef.h>
should be sufficient.
The definition of NULL
is guaranteed to be available if you include cstddef
or stddef.h
. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.
Update 03-Oct-19
new script that displays 10second countdown then launches chrome/chromiumn in fullscreen kiosk mode.
more updates to chrome required script update to allow autoplaying video with audio. Note --overscroll-history-navigation=0 isn't working currently will need to disable this flag by going to chrome://flags/#overscroll-history-navigation in your browser and setting to disabled.
@echo off
echo Countdown to application launch...
timeout /t 10
"C:\Program Files (x86)\chrome-win32\chrome.exe" --chrome --kiosk http://localhost/xxxx --incognito --disable-pinch --no-user-gesture-required --overscroll-history-navigation=0
exit
might need to set chrome://flags/#autoplay-policy if running an older version of chrome (60 below)
Update 11-May-16
There have been many updates to chrome since I posted this and have had to alter the script alot to keep it working as I needed.
Couple of issues with newer versions of chrome:
Because of the restore error switched out to incognito mode as this launches a clear version all the time and does not save what the user was viewing and so if it crashes there is nothing to restore. Also the auto up in newer versions of chrome being a pain to try and disable I switched out to use chromium as it does not auto update and still gives all the modern features of chrome. Note make sure you download the top version of chromium this comes with all audio and video codecs as the basic version of chromium does not support all codecs.
@echo off echo Step 1 of 2: Waiting a few seconds before starting the Kiosk... "C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL echo Step 2 of 5: Waiting a few more seconds before starting the browser... "C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL echo Final 'invisible' step: Starting the browser, Finally... "C:\Program Files (x86)\Google\Chromium\chrome.exe" --chrome --kiosk http://127.0.0.1/xxxx --incognito --disable-pinch --overscroll-history-navigation=0 exit
Outdated
I use this for exhibitions to lock down screens. I think its what your looking for.
Next part is the script that I use to start close and restart chrome again in kiosk mode. The locations is where I have chrome installed so it might be abit different for you depending on your install.
Open your text editor of choice or just notepad and past the below code in, make sure its in the same format/order as below. Save it to your desktop as what ever you like so for this example chrome_startup_script.txt next right click it and rename, remove the txt from the end and put in bat instead. double click this to launch the script to see if its working correctly.
A command line box should appear and run through the script, chrome will start and then close down the reason to do this is to remove any error reports such as if the pc crashed, when chrome starts again without this it would show the yellow error bar at the top saying chrome did not shut down properly would you like to restore it. After a few seconds chrome should start again and in kiosk mode and will point to what ever homepage you have set.
@echo off
echo Step 1 of 5: Waiting a few seconds before starting the Kiosk...
"C:\windows\system32\ping" -n 31 -w 1000 127.0.0.1 >NUL
echo Step 2 of 5: Starting browser as a pre-start to delete error messages...
"C:\google_homepage.url"
echo Step 3 of 5: Waiting a few seconds before killing the browser task...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Step 4 of 5: Killing the browser task gracefully to avoid session restore...
Taskkill /IM chrome.exe
echo Step 5 of 5: Waiting a few seconds before restarting the browser...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Final 'invisible' step: Starting the browser, Finally...
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk --overscroll-history-navigation=0"
exit
Note: The number after the -n of the ping is the amount of seconds (minus one second) to wait before starting the link (or application in the next line)
Finally if this is all working then you can drag and drop the .bat file into the startup folder in windows and this script will launch each time windows starts.
Update:
With recent versions of chrome they have really got into enabling touch gestures, this means that swiping left or right on a touchscreen will cause the browser to go forward or backward in history. To prevent this we need to disable the history navigation on the back and forward buttons to do that add the following --overscroll-history-navigation=0
to the end of the script.
I had the same struggle and I this is what I used:
} public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter the string: ");
String input = scan.next();
System.out.print("Please enter the required symbol: ");
String symbol = scan.next();
char symbolChar = symbol.charAt(0);
This works just fine. The idea is to get from the string the only char in it.
To remove you tube controls
and title
you can do something like this
<iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe>
_x000D_
showinfo=0
is used to remove title and &controls=0
is used for remove controls like volume,play,pause,expend.
Unfortunately reflection to get attributes on enums is quite slow:
See this question: Anyone know a quick way to get to custom attributes on an enum value?
The .ToString()
is quite slow on enums too.
You can write extension methods for enums though:
public static string GetName( this MyEnum input ) {
switch ( input ) {
case MyEnum.WINDOWSAUTHENTICATION:
return "Windows";
//and so on
}
}
This isn't great, but will be quick and not require the reflection for attributes or field name.
C#6 Update
If you can use C#6 then the new nameof
operator works for enums, so nameof(MyEnum.WINDOWSAUTHENTICATION)
will be converted to "WINDOWSAUTHENTICATION"
at compile time, making it the quickest way to get enum names.
Note that this will convert the explicit enum to an inlined constant, so it doesn't work for enums that you have in a variable. So:
nameof(AuthenticationMethod.FORMS) == "FORMS"
But...
var myMethod = AuthenticationMethod.FORMS;
nameof(myMethod) == "myMethod"
Try This
SELECT f.*
FROM first_table f LEFT JOIN second_table s ON f.key=s.key
WHERE s.key is NULL
For more please read this article : Joins in Sql Server
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
For case1:
INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
FROM TAB_TEACHER
WHERE name_teacher = 'Professor Jack'
LIMIT 1
For case2 you just have to do 2 separate insert statements
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
I would suggest to remove the rows from the underlying DataTable, or if you don't need the datatable anymore, set the datasource to null.
The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only
Just try this ..
function handleValueChange() {
var y = document.getElementById('textbox_id').value;
var x = document.getElementById('result');
x.innerHTML = y;
}
function changeTextarea() {
var a = document.getElementById('text-area').value;
var b = document.getElementById('text-area-result');
b.innerHTML = a;
}
_x000D_
input {
padding: 5px;
}
p {
white-space: pre;
}
_x000D_
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>
_x000D_
Use the .IndexOf()
method of the list. Specs for the method can be found on MSDN.
so it's easy)))
Watch this...
var stuff = {};
$('input[type=checkbox]').each(function(i, e) {
stuff[i] = e.checked;
});
And you will have:
Object {0: true, 1: false, 2: false, 3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff['row'+i] = e.checked;
});
You will have:
Object {row0: true, row1: false, row2: false, row3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff[e.className+i] = e.checked;
});
You will have:
Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP
from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
show variables where Variable_name='hostname';
That could help you !!
If you are getting the following error while connecting the mysql (either local or mysql container running the mysql):
java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
Solution: Add the following line in your database service:
command: --default-authentication-plugin=mysql_native_password
sorted
return a new sorted list from the items in iterable.
CODE
import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print sorted(a)
OUTPUT
[1, 2, 3, 6, 8]
newString = yourString.Substring(0, yourString.length -1);
You don't create subfolders of the drawable folder but rather 'sibling' folders next to it under the /res
folder for the different screen densities or screen sizes.
The /drawable
folder (without any dimension) is mostly used for drawables that don't relate to any screen sizes like selector
s.
See this screenshot (use the name drawable-hdpi
instead of mipmap-hdpi
):
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
This memory technic helps me a lot:
[ <RETURNED_VALUE> <OUTER_LOOP1> <INNER_LOOP2> <INNER_LOOP3> ... <OPTIONAL_IF> ]
And now you can think about Return + Outer-loop as the only Right Order
Knowing above, the order in list comprehensive even for 3 loops seem easy:
c=[111, 222, 333]
b=[11, 22, 33]
a=[1, 2, 3]
print(
[
(i, j, k) # <RETURNED_VALUE>
for i in a for j in b for k in c # in order: loop1, loop2, loop3
if i < 2 and j < 20 and k < 200 # <OPTIONAL_IF>
]
)
[(1, 11, 111)]
because the above is just a:
for i in a: # outer loop1 GOES SECOND
for j in b: # inner loop2 GOES THIRD
for k in c: # inner loop3 GOES FOURTH
if i < 2 and j < 20 and k < 200:
print((i, j, k)) # returned value GOES FIRST
for iterating one nested list/structure, technic is the same:
for a
from the question:
a = [[1,2],[3,4]]
[i2 for i1 in a for i2 in i1]
which return [1, 2, 3, 4]
for one another nested level
a = [[[1, 2], [3, 4]], [[5, 6], [7, 8, 9]], [[10]]]
[i3 for i1 in a for i2 in i1 for i3 in i2]
which return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
and so on