What is the meaning of "Failed building wheel for X" in pip install?
On Ubuntu 18.04, I ran into this issue because the apt
package for wheel
does not include the wheel
command. I think pip tries to import the wheel
python package, and if that succeeds assumes that the wheel
command is also available. Ubuntu breaks that assumption.
The apt python3 code package is named python3-wheel
. This is installed automatically because python3-pip
recommends it.
The apt python3 wheel command package is named python-wheel-common
. Installing this too fixes the "failed building wheel" errors for me.
I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?
I had the same issue but solved it by using Ubuntu.
python -m pip install pyaudio
- Install sudo, apt-get and then install homebrew &/ linuxbrew on your linux subsystem using Ubuntu.
- The latest version supports ubuntu.
brew install portaudio
- Make sure you have python/python3 installed on the terminal
- Make sure the current location is added as path in your virtual computer's path in environment Variable.
brew link portaudio
You must add a reference to assembly 'netstandard, Version=2.0.0.0
I am facing Same Problem i do following Setup Now Application Work fine
1-
<compilation debug="true" targetFramework="4.7.1">
<assemblies>
<add assembly="netstandard, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=cc7b13ffcd2ddd51"/>
</assemblies>
</compilation>
2- Add Reference
**C:\Program Files (x86)\Microsoft Visual
Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\ADL
Tools\2.4.0000.0\ASALocalRun\netstandard.dll**
3-
Copy Above Path Dll to Application Bin Folder on web server
Set cookies for cross origin requests
For express, upgrade your express library to 4.17.1
which is the latest stable version. Then;
In CorsOption: Set origin
to your localhost url or your frontend production url and credentials
to true
e.g
const corsOptions = {
origin: config.get("origin"),
credentials: true,
};
I set my origin dynamically using config npm module.
Then , in res.cookie:
For localhost: you do not need to set sameSite and secure option at all, you can set httpOnly
to true
for http cookie to prevent XSS attack and other useful options depending on your use case.
For production environment, you need to set sameSite
to none
for cross-origin request and secure
to true
. Remember sameSite
works with express latest version only as at now and latest chrome version only set cookie over https
, thus the need for secure option.
Here is how I made mine dynamic
res
.cookie("access_token", token, {
httpOnly: true,
sameSite: app.get("env") === "development" ? true : "none",
secure: app.get("env") === "development" ? false : true,
})
Cordova app not displaying correctly on iPhone X (Simulator)
There is 3 steps you have to do
for iOs 11 status bar & iPhone X header problems
1. Viewport fit cover
Add viewport-fit=cover
to your viewport's meta in <header>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0,viewport-fit=cover">
Demo: https://jsfiddle.net/gq5pt509 (index.html)
- Add more splash images to your
config.xml
inside <platform name="ios">
Dont skip this step, this required for getting screen fit for iPhone X work
<splash src="your_path/Default@2x~ipad~anyany.png" /> <!-- 2732x2732 -->
<splash src="your_path/Default@2x~ipad~comany.png" /> <!-- 1278x2732 -->
<splash src="your_path/Default@2x~iphone~anyany.png" /> <!-- 1334x1334 -->
<splash src="your_path/Default@2x~iphone~comany.png" /> <!-- 750x1334 -->
<splash src="your_path/Default@2x~iphone~comcom.png" /> <!-- 1334x750 -->
<splash src="your_path/Default@3x~iphone~anyany.png" /> <!-- 2208x2208 -->
<splash src="your_path/Default@3x~iphone~anycom.png" /> <!-- 2208x1242 -->
<splash src="your_path/Default@3x~iphone~comany.png" /> <!-- 1242x2208 -->
Demo: https://jsfiddle.net/mmy885q4 (config.xml)
- Fix your style on CSS
Use safe-area-inset-left
, safe-area-inset-right
, safe-area-inset-top
, or safe-area-inset-bottom
Example: (Use in your case!)
#header {
position: fixed;
top: 1.25rem; // iOs 10 or lower
top: constant(safe-area-inset-top); // iOs 11
top: env(safe-area-inset-top); // iOs 11+ (feature)
// or use calc()
top: calc(constant(safe-area-inset-top) + 1rem);
top: env(constant(safe-area-inset-top) + 1rem);
// or SCSS calc()
$nav-height: 1.25rem;
top: calc(constant(safe-area-inset-top) + #{$nav-height});
top: calc(env(safe-area-inset-top) + #{$nav-height});
}
Bonus: You can add body class like is-android
or is-ios
on deviceready
var platformId = window.cordova.platformId;
if (platformId) {
document.body.classList.add('is-' + platformId);
}
So you can do something like this on CSS
.is-ios #header {
// Properties
}
How to enable CORS in ASP.net Core WebAPI
Here is how I did this.
I see that in some answers they are setting app.UserCors("xxxPloicy")
and putting [EnableCors("xxxPloicy")]
in controllers. You do not need to do both.
Here are the steps.
In Startup.cs inside the ConfigureServices add the following code.
services.AddCors(c=>c.AddPolicy("xxxPolicy",builder => {
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
If you want to apply all over the project then add the following code in Configure method in Startup.cs
app.UseCors("xxxPolicy");
Or
If you want to add it to the specific controllers then add enable cors code as shown below.
[EnableCors("xxxPolicy")]
[Route("api/[controller]")]
[ApiController]
public class TutorialController : ControllerBase {}
For more info: see this
Can Windows Containers be hosted on linux?
You can use Windows Containers inside a virtual machine (the guest OS should match the requirements - Windows 10 Pro or Windows 2016).
For example you can use VirtualBox, just enable Hyper-V inside System / Acceleration / Paravirtualization Interface.
After that if Docker doesn't start up because of an error, use the "Switch to Windows containers..." in the settings.
(this could be moved as a comment to the accepted answer, but I don't have enough reputation to do so)
.NET Core vs Mono
In a nutshell:
Mono = Compiler for C#
Mono Develop = Compiler+IDE
.Net Core = ASP Compiler
Current case for .Net Core is web only as soon as it adopts some open winform standard and wider language adoption, it could finally be the Microsoft killer dev powerhouse. Considering Oracle's recent Java licensing move, Microsoft have a huge time to shine.
How to specify the port an ASP.NET Core application is hosted on?
In ASP.NET Core 3.1, there are 4 main ways to specify a custom port:
- Using command line arguments, by starting your .NET application with
--urls=[url]
:
dotnet run --urls=http://localhost:5001/
- Using
appsettings.json
, by adding a Urls
node:
{
"Urls": "http://localhost:5001"
}
- Using environment variables, with
ASPNETCORE_URLS=http://localhost:5001/
.
- Using
UseUrls()
, if you prefer doing it programmatically:
public static class Program
{
public static void Main(string[] args) =>
CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(builder =>
{
builder.UseStartup<Startup>();
builder.UseUrls("http://localhost:5001/");
});
}
Or, if you're still using the web host builder instead of the generic host builder:
public class Program
{
public static void Main(string[] args) =>
new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://localhost:5001/")
.Build()
.Run();
}
How can I install Visual Studio Code extensions offline?
I've stored a script in my gist to download an extension from the marketplace using a PowerShell script.
Feel free to comment of share it.
https://gist.github.com/azurekid/ca641c47981cf8074aeaf6218bb9eb58
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[string] $Publisher,
[Parameter(Mandatory = $true)]
[string] $ExtensionName,
[Parameter(Mandatory = $true)]
[ValidateScript( {
If ($_ -match "^([0-9].[0-9].[0-9])") {
$True
}
else {
Throw "$_ is not a valid version number. Version can only contain digits"
}
})]
[string] $Version,
[Parameter(Mandatory = $true)]
[string] $OutputLocation
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
Write-Output "Publisher: $($Publisher)"
Write-Output "Extension name: $($ExtensionName)"
Write-Output "Version: $($Version)"
Write-Output "Output location $($OutputLocation)"
$baseUrl = "https://$($Publisher).gallery.vsassets.io/_apis/public/gallery/publisher/$($Publisher)/extension/$($ExtensionName)/$($Version)/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage"
$outputFile = "$($Publisher)-$($ExtensionName)-$($Version).visx"
if (Test-Path $OutputLocation) {
try {
Write-Output "Retrieving extension..."
[uri]::EscapeUriString($baseUrl) | Out-Null
Invoke-WebRequest -Uri $baseUrl -OutFile "$OutputLocation\$outputFile"
}
catch {
Write-Error "Unable to find the extension in the marketplace"
}
}
else {
Write-Output "The Path $($OutputLocation) does not exist"
}
How to extract text from a PDF file?
I recommend to use pymupdf or pdfminer.six
.
Those packages are not maintained:
- PyPDF2, PyPDF3, PyPDF4
pdfminer
(without .six)
How to read pure text with pymupdf
There are different options which will give different results, but the most basic one is:
import fitz # this is pymupdf
with fitz.open("my.pdf") as doc:
text = ""
for page in doc:
text += page.getText()
print(text)
Generate PDF from Swagger API documentation
I created a web site https://www.swdoc.org/ that specifically addresses the problem. So it automates swagger.json -> Asciidoc, Asciidoc -> pdf
transformation as suggested in the answers. Benefit of this is that you dont need to go through the installation procedures. It accepts a spec document in form of url or just a raw json. Project is written in C# and its page is https://github.com/Irdis/SwDoc
EDIT
It might be a good idea to validate your json specs here: http://editor.swagger.io/ if you are having any problems with SwDoc, like the pdf being generated incomplete.
#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel
I had the same issue as all of our servers run older versions of MySQL. This can be solved by running a PHP script. Save this code to a file and run it entering the database name, user and password and it'll change the collation from utf8mb4/utf8mb4_unicode_ci
to utf8/utf8_general_ci
<!DOCTYPE html>
<html>
<head>
<title>DB-Convert</title>
<style>
body { font-family:"Courier New", Courier, monospace; }
</style>
</head>
<body>
<h1>Convert your Database to utf8_general_ci!</h1>
<form action="db-convert.php" method="post">
dbname: <input type="text" name="dbname"><br>
dbuser: <input type="text" name="dbuser"><br>
dbpass: <input type="text" name="dbpassword"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_POST) {
$dbname = $_POST['dbname'];
$dbuser = $_POST['dbuser'];
$dbpassword = $_POST['dbpassword'];
$con = mysql_connect('localhost',$dbuser,$dbpassword);
if(!$con) { echo "Cannot connect to the database ";die();}
mysql_select_db($dbname);
$result=mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
foreach ($tables as $key => $value) {
mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "<script>alert('The collation of your database has been successfully changed!');</script>";
}
?>
From inside of a Docker container, how do I connect to the localhost of the machine?
Edit: If you are using Docker-for-mac or Docker-for-Windows 18.03+, just connect to your mysql service using the host host.docker.internal
(instead of the 127.0.0.1
in your connection string).
As of Docker 18.09.3, this does not work on Docker-for-Linux. A fix has been submitted on March the 8th, 2019 and will hopefully be merged to the code base. Until then, a workaround is to use a container as described in qoomon's answer.
2020-01: some progress has been made. If all goes well, this should land in Docker 20.04
Docker 20.10-beta1 has been reported to implement host.docker.internal
:
$ docker run --rm --add-host host.docker.internal:host-gateway alpine ping host.docker.internal
PING host.docker.internal (172.17.0.1): 56 data bytes
64 bytes from 172.17.0.1: seq=0 ttl=64 time=0.534 ms
64 bytes from 172.17.0.1: seq=1 ttl=64 time=0.176 ms
...
TLDR
Use --network="host"
in your docker run
command, then 127.0.0.1
in your docker container will point to your docker host.
Note: This mode only works on Docker for Linux, per the documentation.
Note on docker container networking modes
Docker offers different networking modes when running containers. Depending on the mode you choose you would connect to your MySQL database running on the docker host differently.
docker run --network="bridge" (default)
Docker creates a bridge named docker0
by default. Both the docker host and the docker containers have an IP address on that bridge.
on the Docker host, type sudo ip addr show docker0
you will have an output looking like:
[vagrant@docker:~] $ sudo ip addr show docker0
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::5484:7aff:fefe:9799/64 scope link
valid_lft forever preferred_lft forever
So here my docker host has the IP address 172.17.42.1
on the docker0
network interface.
Now start a new container and get a shell on it: docker run --rm -it ubuntu:trusty bash
and within the container type ip addr show eth0
to discover how its main network interface is set up:
root@e77f6a1b3740:/# ip addr show eth0
863: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 66:32:13:f0:f1:e3 brd ff:ff:ff:ff:ff:ff
inet 172.17.1.192/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::6432:13ff:fef0:f1e3/64 scope link
valid_lft forever preferred_lft forever
Here my container has the IP address 172.17.1.192
. Now look at the routing table:
root@e77f6a1b3740:/# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.17.42.1 0.0.0.0 UG 0 0 0 eth0
172.17.0.0 * 255.255.0.0 U 0 0 0 eth0
So the IP Address of the docker host 172.17.42.1
is set as the default route and is accessible from your container.
root@e77f6a1b3740:/# ping 172.17.42.1
PING 172.17.42.1 (172.17.42.1) 56(84) bytes of data.
64 bytes from 172.17.42.1: icmp_seq=1 ttl=64 time=0.070 ms
64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.201 ms
64 bytes from 172.17.42.1: icmp_seq=3 ttl=64 time=0.116 ms
docker run --network="host"
Alternatively you can run a docker container with network settings set to host
. Such a container will share the network stack with the docker host and from the container point of view, localhost
(or 127.0.0.1
) will refer to the docker host.
Be aware that any port opened in your docker container would be opened on the docker host. And this without requiring the -p
or -P
docker run
option.
IP config on my docker host:
[vagrant@docker:~] $ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
valid_lft forever preferred_lft forever
and from a docker container in host mode:
[vagrant@docker:~] $ docker run --rm -it --network=host ubuntu:trusty ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
valid_lft forever preferred_lft forever
As you can see both the docker host and docker container share the exact same network interface and as such have the same IP address.
Connecting to MySQL from containers
bridge mode
To access MySQL running on the docker host from containers in bridge mode, you need to make sure the MySQL service is listening for connections on the 172.17.42.1
IP address.
To do so, make sure you have either bind-address = 172.17.42.1
or bind-address = 0.0.0.0
in your MySQL config file (my.cnf).
If you need to set an environment variable with the IP address of the gateway, you can run the following code in a container :
export DOCKER_HOST_IP=$(route -n | awk '/UG[ \t]/{print $2}')
then in your application, use the DOCKER_HOST_IP
environment variable to open the connection to MySQL.
Note: if you use bind-address = 0.0.0.0
your MySQL server will listen for connections on all network interfaces. That means your MySQL server could be reached from the Internet ; make sure to setup firewall rules accordingly.
Note 2: if you use bind-address = 172.17.42.1
your MySQL server won't listen for connections made to 127.0.0.1
. Processes running on the docker host that would want to connect to MySQL would have to use the 172.17.42.1
IP address.
host mode
To access MySQL running on the docker host from containers in host mode, you can keep bind-address = 127.0.0.1
in your MySQL configuration and all you need to do is to connect to 127.0.0.1
from your containers:
[vagrant@docker:~] $ docker run --rm -it --network=host mysql mysql -h 127.0.0.1 -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.5.41-0ubuntu0.14.04.1 (Ubuntu)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
note: Do use mysql -h 127.0.0.1
and not mysql -h localhost
; otherwise the MySQL client would try to connect using a unix socket.
How to find when a web page was last updated
This is a Pythonic way to do it:
import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
print "Hmmm, no last-modified data was returned from the URL."
print "Returned header:"
print yaml.dump(dict(r.getheaders()), default_flow_style=False)
The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.
Download and install an ipa from self hosted url on iOS
It won't be possible if you like to directly download and install the app from your website. There is a different way for enterprise to deploy and install app over the air. Your URL should point to a web service that hosts a manifest plist file in predefined format required by Apple. This service should return the url of manifest file which can then be used as below:
NSString *urlString = // url string where your manifest.plist is deployed on your server.
NSURL *installationURL = [NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@",[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[[UIApplication sharedApplication] openURL];
Hope this answers your question.
Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery
If you are using require.js
than need to add
window.$ = window.jQuery = require('jquery')
in app.js
OR
you can make dependent file load after parent file loaded.. such as below concept
require.config({
baseUrl: "scripts/appScript",
paths: {
'jquery':'jQuery/jquery.min',
'bootstrap':'bootstrap/bootstrap.min'
},
shim
shim: {
'bootstrap':['jquery'],
},
// kick start application
deps: ['app']
});
Above code shown that bootstrap
is dependent on Jquery
so i have added in shim
and make it dependent
The 'Access-Control-Allow-Origin' header contains multiple values
This happens when you have Cors option configured at multiple locations. In my case I had it at the controller level as well as in the Startup.Auth.cs/ConfigureAuth.
My understanding is if you want it application wide then just configure it under Startup.Auth.cs/ConfigureAuth like this...You will need reference to Microsoft.Owin.Cors
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
If you rather keep it at the controller level then you may just insert at the Controller level.
[EnableCors("http://localhost:24589", "*", "*")]
public class ProductsController : ApiController
{
ProductRepository _prodRepo;
How to unblock with mysqladmin flush hosts
You should put it into command line in windows.
mysqladmin -u [username] -p flush-hosts
**** [MySQL password]
or
mysqladmin flush-hosts -u [username] -p
**** [MySQL password]
For network login use the following command:
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts
you can permanently solution your problem by editing my.ini file[Mysql configuration file]
change variables max_connections = 10000;
or
login into MySQL using command line -
mysql -u [username] -p
**** [MySQL password]
put the below command into MySQL window
SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;
check veritable using command-
show variables like "max_connections";
show variables like "max_connect_errors";
Wait until ActiveWorkbook.RefreshAll finishes - VBA
I was having this same problem, and tried all the above solutions with no success. I finally solved the problem by deleting the entire query and creating a new one.
The new one had the exact same settings as the one that didn't work (literally the same query definition as I simply copied the old one).
I have no idea why this solved the problem, but it did.
Why call git branch --unset-upstream to fixup?
For me, .git/refs/origin/master
had got corrupt.
I did the following, which fixed the problem for me.
rm .git/refs/remotes/origin/master
git fetch
git branch --set-upstream-to=origin/master
"The system cannot find the file specified"
Server Error in '/' Application.
The system cannot find the file specified
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The system
cannot find the file specified
Source Error:
{
SqlCommand cmd = new SqlCommand("select * from tblemployee",con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
Source File: d:\C#
programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line:
23
if your error is same like mine..just do this
right click on your table in sqlserver object explorer,choose properties
in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..
Facebook key hash does not match any stored key hashes
Follow these steps in order to generate the correct key hashes.
- Open your project in android studio and run the project.
- Click on Gradle menu.
- Select your app and expand task tree.
- Double click on android -> signingReport and see the magic
- Result after clicking above tab
- Copy the SHA1 key and browse SHA1 key to key hash
- After converting the SHA1 key to key hash copy the new key hash and paste it in facebook console. This will work like charm.
How to configure SMTP settings in web.config
I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.
When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:
SmtpClient smtpClient = new SmtpClient("smtp.sender.you", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(msgMail);
To this:
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);
Run command on the Ansible host
ansible your_server_name -i custom_inventory_file_name -m -a "uptime"
The default module is command module, hence command
keyword is not required.
If you need to issue any command with elevated privileges use -b
at the end of the same command.
ansible your_server_name -i custom_inventory_file_name -m -a "uptime" -b
Git command to checkout any branch and overwrite local changes
git reset
and git clean
can be overkill in some situations (and be a huge waste of time).
If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch>
is the best option.
If you're like me, your other option was to clean and perform a --hard reset
then recompile your project.
" netsh wlan start hostednetwork " command not working no matter what I try
This was a real issue for me, and quite a sneaky problem to try and remedy...
The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).
To fix it:
- Hold the Windows Key + Push
R
- Type:
ncpa.cpl
in to the box, and hit OK
.
- Identify the network adapter you want to use for the hostednetwork, right-click it, and select
Properties
.
- You'll see a big box in the middle of the properties window, under the heading
The connection uses the following items:
. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK
.
- Try running the
netsh wlan start hostednetwork
command again.
- Repeat steps 4 and 5 as necessary.
In my case my adapter was running a module called SoftEther Lightweight Network Protocol
, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.
If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.
Can't start hostednetwork
First check if your wlan card support hosted network and if no update the card driver. Follow this steps
1) open cmd with administrative rights
2) on the black screen type: netsh wlan show driver | findstr Hosted
3) See Hosted network supported, if No then update drivers
"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
- Make sure that you have Office runtime installed on the server.
- If you are using Windows Server 2008 then using office interops is a lenghty configuration and here are the steps.
Better is to move to Open XML or you can configure as below
- Install MS Office Pro Latest (I used 2010 Pro)
- Create User ExcelUser. Assign WordUser with Admin Group
- Go to Computer -> Manage
- Add User with below options
- User Options Password Never Expires
- Password Cannot Be Change
Com+ Configuration
- Go to Control Panel - > Administrator -> Component Services -> DCOM Config
- Open Microsoft Word 97 - 2003 Properties
- General -> Authentication Level : None
- Security -> Customize all 3 permissions to allow everyone
- Identity -> This User -> Use ExcelUser /password
- Launch the Excel App to make sure everything is fine
3.Change the security settings of Microsoft Excel Application in DCOM Config.
Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.
Right click to get properties dialog. Go to Security tab and customize permissions
See the posts here: Error while creating Excel object , Excel manipulations in WCF using COM
phpinfo() is not working on my CentOS server
Be sure that the tag "php" is stick in the code like this:
?php phpinfo(); ?>
Not like this:
? php phpinfo(); ?>
OR the server will treat it as a (normal word),
so the server will not understand the language you are writing to deal with it so it will be blank.
I know it's a silly error ...but it happened ^_^
Sending email from Azure
Sending from a third party SMTP isn't restricted by or specific to Azure. Using System.Net.Mail, create your message, configure your SMTP client, send the email:
// create the message
var msg = new MailMessage();
msg.From = new MailAddress("[email protected]");
msg.To.Add(strTo);
msg.Subject = strSubject;
msg.IsBodyHtml = true;
msg.Body = strMessage;
// configure the smtp server
var smtp = new SmtpClient("YourSMTPServer");
var = new System.Net.NetworkCredential("YourSMTPServerUserName", "YourSMTPServerPassword");
// send the message
smtp.Send(msg);
UPDATE: I added a post on Medium about how to do this with an Azure Function - https://medium.com/@viperguynaz/building-a-serverless-contact-form-f8f0bff46ba9
SQL Error: 0, SQLState: 08S01 Communications link failure
The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing.
So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.
Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error
I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.
I just made two changes and I don't which help.
Go to IIS 6 Manager
Select properties of SMTP server
On tab Access, select Relays
Add your public IP address
Close the dialog and on the same tab click to Authentication button.
Add Integrated Windows Authentication
Maybe some step is not needed, but it works.
npm ERR cb() never called
I encountered the same problem on my Mac and I have tried all methods I can find: upgrade to latest Node, clean cache, remove _node_mudules_ directory, but all have no effect. Eventually, I believed it was the problem of Node environment, so I degraded my Node to an old LTS version 6.14.1, then the problem disappeared. This is what I do:
Install NVM (To get a brand new isolated node environment, you'd better use NVM to manage your multiple Node environments, go to here for details)
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
Install Node.js 6.14.1
nvm install 6.14.1
Switch to the specific Node environment you install above
nvm use 6.14.1
Install create-react-app
npm install -g create-react-app
Create your react app
create-react-app appname
Managing SSH keys within Jenkins for Git
This works for me if you have config and the private key file in the /Jenkins/.ssh/ you need to chown (change owner) for these 2 files then restart jenkins in order for the jenkins instance to read these 2 files.
PHP : send mail in localhost
It is possible to send Emails without using any heavy libraries I have included my example here.
lightweight SMTP Email sender for PHP
https://github.com/jerryurenaa/EZMAIL
Tested in both environments production and development.
and most importantly emails will not go to spam unless your IP is blacklisted by the server.
cheers.
How to do a GitHub pull request
I followed tim peterson's instructions but I created a local branch for my changes. However, after pushing I was not seeing the new branch in GitHub. The solution was to add -u to the push command:
git push -u origin <branch>
Svn switch from trunk to branch
In my case, I wanted to check out
a new branch
that has cut recently
but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network
so I copped the previous branch
that I already checked in
I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help
)
svn switch ^/branches/newBranchName
go check svn info
again you can see it is becoming the newBranchName go ahead and svn up
and this how I got the new branch easily, quickly with minimum data transmitting over the internet
hope sharing my case helps and speeds up your work
Can I use an image from my local file system as background in HTML?
You forgot the C: after the file:///
This works for me
<!DOCTYPE html>
<html>
<head>
<title>Experiment</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
html,body { width: 100%; height: 100%; }
</style>
</head>
<body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
</body>
</html>
How to add images to README.md on GitHub?
In new Github UI, this works for me -
Example - Commit your image.png in a folder (myFolder) and add the following line in your README.md:
![Optional Text](../main/myFolder/image.png)
How to get all Windows service names starting with a common word?
Using PowerShell, you can use the following
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name
This will show a list off all services which displayname starts with "NATION-".
You can also directly stop or start the services;
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service
or simply
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service
Include an SVG (hosted on GitHub) in MarkDown
I have a working example with an img-tag, but your images won't display.
The difference I see is the content-type.
I checked the github image from your post (the google doc images don't load at all because of connection failures). The image from github is delivered as content-type: text/plain, which won't get rendered as an image by your browser.
The correct content-type value for svg is image/svg+xml. So you have to make sure that svg files set the correct mime type, but that's a server issue.
Try it with http://svg.tutorial.aptico.de/grafik_svg/dummy3.svg and don't forget to specify width and height in the tag.
how to delete all commit history in github?
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
How to specify a local file within html using the file: scheme?
The 'file' protocol is not a network protocol. Therefore file://192.168.1.57/~User/2ndFile.html simply does not make much sense.
Question is how you load the first file. Is that really done using a web server? Does not really sound like. If it is, then why not use the same protocol, most likely http? You cannot expect to simply switch the protocol and use two different protocols the same way...
I suspect the first file is really loaded using the apache server at all, but simply by opening the file? href="2ndFile.html" simply works because it uses a "relative url". This makes the browser use the same protocol and path as where he got the first (current) file from.
Latest jQuery version on Google's CDN
I don't know if/where it's published, but you can get the latest release by omitting the minor and build numbers.
Latest 1.8.x:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
Latest 1.x:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
However, do keep in mind that these links have a much shorter cache timeout than with the full version number, so your users may be downloading them more than you'd like. See The crucial .0 in Google CDN references to jQuery 1.x.0 for more information.
How to get HttpClient to pass credentials along with the request?
OK, so thanks to all of the contributors above. I am using .NET 4.6 and we also had the same issue. I spent time debugging System.Net.Http
, specifically the HttpClientHandler
, and found the following:
if (ExecutionContext.IsFlowSuppressed())
{
IWebProxy webProxy = (IWebProxy) null;
if (this.useProxy)
webProxy = this.proxy ?? WebRequest.DefaultWebProxy;
if (this.UseDefaultCredentials || this.Credentials != null || webProxy != null && webProxy.Credentials != null)
this.SafeCaptureIdenity(state);
}
So after assessing that the ExecutionContext.IsFlowSuppressed()
might have been the culprit, I wrapped our Impersonation code as follows:
using (((WindowsIdentity)ExecutionContext.Current.Identity).Impersonate())
using (System.Threading.ExecutionContext.SuppressFlow())
{
// HttpClient code goes here!
}
The code inside of SafeCaptureIdenity
(not my spelling mistake), grabs WindowsIdentity.Current()
which is our impersonated identity. This is being picked up because we are now suppressing flow. Because of the using/dispose this is reset after invocation.
It now seems to work for us, phew!
Pushing from local repository to GitHub hosted remote
This worked for my GIT version 1.8.4:
- From the local repository folder, right click and select 'Git Commit Tool'.
- There, select the files you want to upload, under 'Unstaged Changes' and click 'Stage Changed' button. (You can initially click on 'Rescan' button to check what files are modified and not uploaded yet.)
- Write a Commit Message and click 'Commit' button.
- Now right click in the folder again and select 'Git Bash'.
- Type: git push origin master and enter your credentials. Done.
How to form a correct MySQL connection string?
try creating connection string this way:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{ //watch out for this SQL injection vulnerability below
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
(413) Request Entity Too Large | uploadReadAheadSize
For anyone else ever looking for an IIS WCF error 413 : Request entity to large and using a WCF service in Sharepoint, this is the information for you. The settings in the application host and web.config suggested in other sites/posts don't work in SharePoint if using the MultipleBaseAddressBasicHttpBindingServiceHostFactory. You can use SP Powershell to get the SPWebService.Content service, create a new SPWcvSettings object and update the settings as above for your service (they won't exist). Remember to just use the name of the service (e.g. [yourservice.svc]) when creating and adding the settings. See this site for more info https://robertsep.wordpress.com/2010/12/21/set-maximum-upload-filesize-sharepoint-wcf-service
PHP-FPM and Nginx: 502 Bad Gateway
Before messing with Nginx config, try to disable ChromePHP first.
1 - Open app/config/config_dev.yml
2 - Comment these lines:
chromephp:
type: chromephp
level: info
ChromePHP pack the debug info json-encoded in the X-ChromePhp-Data header, which is too big for the default config of nginx with fastcgi.
Force LF eol in git repo and working copy
Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)
Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....
However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.
As you're partially working on Linux and Windows, make sure core.eol
is set to native
and core.autocrlf
is set to true
.
Then, replace the content of your .gitattributes
file with the following
* text=auto
This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.
However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.
Provided you work on a C based image processing project, replace the content of your .gitattributes
file with the following
* text=auto
*.txt text
*.c text
*.h text
*.jpg binary
This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.
In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.
As a real world example, you can also peek at this commit where those changes to a .gitattributes
file are demonstrated.
UPDATE to the answer considering the following comment
I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory
Makes sense. Thanks for the clarification. In this specific context, the .gitattributes
file by itself won't be enough.
Run the following commands against your repository
$ git config core.eol lf
$ git config core.autocrlf input
As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol
will make sure text files bear LF line endings on checkouts. core.autocrlf
will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.
Optionally, you can help Git distinguish what is a text file by creating a .gitattributes
file containing something similar to the following:
# Autodetect text files
* text=auto
# ...Unless the name matches the following
# overriding patterns
# Definitively text files
*.txt text
*.c text
*.h text
# Ensure those won't be messed up with
*.jpg binary
*.data binary
If you decided to create a .gitattributes
file, commit it.
Lastly, ensure git status
mentions "nothing to commit (working directory clean)", then perform the following operation
$ git checkout-index --force --all
This will recreate your files in your working directory, taking into account your config changes and the .gitattributes
file and replacing any potential overlooked CRLF in your text files.
Once this is done, every text file in your working directory WILL bear LF line endings and git status
should still consider the workdir as clean.
HTTP 404 Page Not Found in Web Api hosted in IIS 7.5
Based on this SO answer, I just had to change path="*."
to path="*"
for the added ExtensionlessUrlHandler-Integrated-4.0
in configuration>system.WebServer>handlers
in my web.config
Before:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
After:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
How to fix error ::Format of the initialization string does not conform to specification starting at index 0::
None of the listed solutions in this thread worked for me. I started getting this error after I made some changes to the connection strings section of the web.config file. (My app connects to multiple databases.) I carefully examined what changes I had made are realized I had removed the tag at the top of my list. I restored the tag at the top of my list of connection strings and the problem went away immediately. This site that was getting the error is a application that resides below the main site (https://www.domain.org/MySite). This might not fix the problem for everyone, but it did resolve the problem for me.
MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error
After making above improvement such as checking if mysql service
is running or not, you just need to give a small password while creating connection, it is ' '
or 1 time press on space-bar in case of GUI or workbench. After which you just need to validate your machine with server (validated HOST). For that purpose click on 'New Server Instance'
and it will configure server/HOST on your behalf itself.
I have done this successfully just a few couple of minutes ago. My workbench software is able to show all pre-installed databases
etc now.
hope it will work for you as well.
Thanks!!!
Creating an IFRAME using JavaScript
You can use:
<script type="text/javascript">
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://google.com/");
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
</script>
also check basics of the iFrame element
Why use 'virtual' for class properties in Entity Framework model definitions?
The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it:
public virtual double Area()
{
return x * y;
}
You cannot use the virtual modifier with the static, abstract, private, or override modifiers. The following example shows a virtual property:
class MyBaseClass
{
// virtual auto-implemented property. Overrides can only
// provide specialized behavior if they implement get and set accessors.
public virtual string Name { get; set; }
// ordinary virtual property with backing field
private int num;
public virtual int Number
{
get { return num; }
set { num = value; }
}
}
class MyDerivedClass : MyBaseClass
{
private string name;
// Override auto-implemented property with ordinary property
// to provide specialized accessor behavior.
public override string Name
{
get
{
return name;
}
set
{
if (value != String.Empty)
{
name = value;
}
else
{
name = "Unknown";
}
}
}
}
REST API Authentication
I've been using the JWT authentication. Works just fine in my application.
There is an authentication method that will require the user credentials. This method validates the credentials and returns an access token in case of success.
This token must be sent to every other method in my Web API in the header of the request.
It's pretty easy to implement, and very easy to test.
Multiple types were found that match the controller named 'Home'
Even though you are not using areas, you can still specify in your RouteMap which namespace to use
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" },
new[] { "NameSpace.OfYour.Controllers" }
);
But it sounds like the actual issue is the way your two apps are set up in IIS
.gitignore after commit
Even after you delete the file(s) and then commit, you will still have those files in history. To delete those, consider using BFG Repo-Cleaner. It is an alternative to git-filter-branch.
IIS: Where can I find the IIS logs?
I'm adding this answer because after researching the web, I ended up at this answer but still didn't know which subfolder of the IIS logs folder to look in.
If your server has multiple websites, you will need to know the IIS ID for the site. An easy way to get this in IIS is to simply click on the Sites folder in the left panel. The ID for each site is shown in the right panel.
Once you know the ID, let's call it n, the corresponding logs are in the W3SVCn subfolder of the IIS logs folder. So, if your website ID is 4, say, and the IIS logs are in the default location, then the logs are in this folder:
%SystemDrive%\inetpub\logs\LogFiles\W3SVC4
Acknowlegements:
- Answer by @jishi tells where the logs are by default.
- Answer by @Rafid explains how to find actual location (maybe not default).
- Answer by @Bergius gives a programmatic way to find the log folder location for a specific website, taking ID into account, without using IIS.
How to pull remote branch from somebody else's repo
No, you don't need to add them as a remote. That would be clumbersome and a pain to do each time.
Grabbing their commits:
git fetch [email protected]:theirusername/reponame.git theirbranch:ournameforbranch
This creates a local branch named ournameforbranch
which is exactly the same as what theirbranch
was for them. For the question example, the last argument would be foo:foo
.
Note :ournameforbranch
part can be further left off if thinking up a name that doesn't conflict with one of your own branches is bothersome. In that case, a reference called FETCH_HEAD
is available. You can git log FETCH_HEAD
to see their commits then do things like cherry-picked
to cherry pick their commits.
Pushing it back to them:
Oftentimes, you want to fix something of theirs and push it right back. That's possible too:
git fetch [email protected]:theirusername/reponame.git theirbranch
git checkout FETCH_HEAD
# fix fix fix
git push [email protected]:theirusername/reponame.git HEAD:theirbranch
If working in detached state worries you, by all means create a branch using :ournameforbranch
and replace FETCH_HEAD
and HEAD
above with ournameforbranch
.
Asp.net Validation of viewstate MAC failed
If you're using a web farm and running the same application on multiple computers, you need to define the machine key explicitly in the machine.config file:
<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decryptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />
Put it under the <system.web>
tag.
The AutoGenerate for the machine code can not be used. To generate your own machineKey see this powershell script:
https://support.microsoft.com/en-us/kb/2915218#bookmark-appendixa
How to publish a Web Service from Visual Studio into IIS?
If using Visual Studio 2010 you can right-click on the project for the service, and select properties
. Then select the Web
tab. Under the Servers
section you can configure the URL. There is also a button to create the virtual directory.
ContractFilter mismatch at the EndpointDispatcher exception
If you are calling WCF method you should include interface in Header.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
if (Url.Contains(".svc"))
{
isWCFService = true;
req.Headers.Add("SOAPAction", "http://tempuri.org/WCF_INterface/GetAPIKeys");
}
else
{
req.Headers.Add("SOAPAction", "\"http://tempuri.org/" + asmxMethodName+ "\"");
}
Authenticate Jenkins CI for Github private repository
If you need Jenkins to access more then 1 project you will need to:
1. add public key to one github user account
2. add this user as Owner (to access all projects) or as a Collaborator in every project.
Many public keys for one system user will not work because GitHub will find first matched deploy key and will send back error like "ERROR: Permission to user/repo2 denied to user/repo1"
http://help.github.com/ssh-issues/
SVN check out linux
There should be svn
utility on you box, if installed:
$ svn checkout http://example.com/svn/somerepo somerepo
This will check out a working copy from a specified repository to a directory somerepo
on our file system.
You may want to print commands, supported by this utility:
$ svn help
uname -a
output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm
or the following command:
$ sudo yum install subversion
Get IFrame's document, from JavaScript in main document
In case you get a cross-domain error:
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'>
attribute for the inner html.
For example, for the inner html, use the this
html parameter (yes - this
is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
Skipping Incompatible Libraries at compile
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
How do I give PHP write access to a directory?
You can set selinux to permissive in order to analyze.
# setenforce 0
Selinux will log but permit acesses. So you can check the /var/log/audit/audit.log
for details. Maybe you will need change selinux context. Fot this, you will use chcon
command. If you need, show us your audit.log
to more detailed answer.
Don't forget to enable selinux after you solved the problem. It better keep selinux enforced.
# setenforce 1
MySQL - SELECT * INTO OUTFILE LOCAL ?
Since I find myself rather regularly looking for this exact problem (in the hopes I missed something before...), I finally decided to take the time and write up a small gist to export MySQL queries as CSV files, kinda like https://stackoverflow.com/a/28168869 but based on PHP and with a couple of more options. This was important for my use case, because I need to be able to fine-tune the CSV parameters (delimiter, NULL value handling) AND the files need to be actually valid CSV, so that a simple CONCAT
is not sufficient since it doesn't generate valid CSV files if the values contain line breaks or the CSV delimiter.
Caution: Requires PHP to be installed on the server!
(Can be checked via php -v
)
"Install" mysql2csv
via
wget https://gist.githubusercontent.com/paslandau/37bf787eab1b84fc7ae679d1823cf401/raw/29a48bb0a43f6750858e1ddec054d3552f3cbc45/mysql2csv -O mysql2csv -q && (sha256sum mysql2csv | cmp <(echo "b109535b29733bd596ecc8608e008732e617e97906f119c66dd7cf6ab2865a65 mysql2csv") || (echo "ERROR comparing hash, Found:" ;sha256sum mysql2csv) ) && chmod +x mysql2csv
(download content of the gist, check checksum and make it executable)
Usage example
./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"
generates file /tmp/result.csv
with content
foo,bar
1,2
help for reference
./mysql2csv --help
Helper command to export data for an arbitrary mysql query into a CSV file.
Especially helpful if the use of "SELECT ... INTO OUTFILE" is not an option, e.g.
because the mysql server is running on a remote host.
Usage example:
./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"
cat /tmp/result.csv
Options:
-q,--query=name [required]
The query string to extract data from mysql.
-h,--host=name
(Default: 127.0.0.1) The hostname of the mysql server.
-D,--database=name
The default database.
-P,--port=name
(Default: 3306) The port of the mysql server.
-u,--user=name
The username to connect to the mysql server.
-p,--password=name
The password to connect to the mysql server.
-F,--file=name
(Default: php://stdout) The filename to export the query result to ('php://stdout' prints to console).
-L,--delimiter=name
(Default: ,) The CSV delimiter.
-C,--enclosure=name
(Default: ") The CSV enclosure (that is used to enclose values that contain special characters).
-E,--escape=name
(Default: \) The CSV escape character.
-N,--null=name
(Default: \N) The value that is used to replace NULL values in the CSV file.
-H,--header=name
(Default: 1) If '0', the resulting CSV file does not contain headers.
--help
Prints the help for this command.
Can I make a phone call from HTML on Android?
I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:
in your onCreate you'll need to use a webview and assign a WebViewClient, as below:
browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());
then handle the click on a phone number like this:
private class InternalWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.indexOf("tel:") > -1) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
return true;
} else {
return false;
}
}
}
Let me know if you need more pointers.
Git fails when pushing commit to github
Looks like a server issue (i.e. a "GitHub" issue).
If you look at this thread, it can happen when the git-http-backend
gets a corrupted heap.(and since they just put in place a smart http support...)
But whatever the actual cause is, it may also be related with recent sporadic disruption in one of the GitHub fileserver.
Do you still see this error message? Because if you do:
- check your local Git version (and upgrade to the latest one)
- report this as a GitHub bug.
Note: the Smart HTTP Support is a big deal for those of us behind an authenticated-based enterprise firewall proxy!
From now on, if you clone a repository over the http://
url and you are using a Git client version 1.6.6 or greater, Git will automatically use the newer, better transport mechanism.
Even more amazing, however, is that you can now push over that protocol and clone private repositories as well. If you access a private repository, or you are a collaborator and want push access, you can put your username in the URL and Git will prompt you for the password when you try to access it.
Older clients will also fall back to the older, less efficient way, so nothing should break - just newer clients should work better.
So again, make sure to upgrade your Git client first.
How to download a branch with git?
Navigate to the folder on your new machine you want to download from git on git bash.
Use below command to download the code from any branch you like
git clone 'git ssh url' -b 'Branch Name'
It will download the respective branch code.
How to make a website secured with https
Try making a boot directory in PHP, as in
<?PHP
$ip = $_SERVER['REMOTE_ADDR'];
$privacy = ['BOOTSTRAP_CONFIG'];
$shell = ['BOOTSTRAP_OUTPUT'];
enter code here
if $ip == $privacy {
function $privacy int $ip = "https://";
} endif {
echo $shell
}
?>
Thats mainly it!
Change the maximum upload file size
You can also use ini_set function (only for PHP version below 5.3):
ini_set('post_max_size', '64M');
ini_set('upload_max_filesize', '64M');
Like @acme said, in php 5.3 and above this settings are PHP_INI_PERDIR directives so they can't be set using ini_set. You can use user.ini instead.
Viewing my IIS hosted site on other machines on my network
Very Late Answer but I will highlight some point as I had to deal with it years ago setting up my IIS site across network
- Both your machines should be connected to the same network (same wireless network is fine)
- Access your remote machine via IP
168.192.x.x
or via http://his-pc-name
(do not forget the http part)
- This will server the default IIS page on the remote machine (same that is served through localhost). If you want to server another site, [you have to make that default] first1.
Make sure your IIS is working fine on remote machine by checking localhost
which should served the default site. Also make sure your firewall is configured to allow connection via port 80 or you can just disable firewall for the time being for testing purposes.
What is the curl error 52 "empty reply from server"?
I've had this problem before. Figured out I had another application using the same port (3000).
Easy way to find this out:
In the terminal, type netstat -a -p TCP -n | grep 3000
(substitute the port you're using for the '3000'). If there is more than one listening, something else is already occupying that port. You should stop that process or change the port for your new process.
How do I find the data directory for a SQL Server instance?
i would have done a backup restore simply becuase its easier and support versioning. Reference data especially needs to be versioned in order to know when it started taking effect. A dettach attach wont give you that ability. Also with backups you can continue to provide updated copies without having to shut down the database.
Can I use multiple versions of jQuery on the same page?
Yes, it's doable due to jQuery's noconflict mode. http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/
<!-- load jQuery 1.1.3 -->
<script type="text/javascript" src="http://example.com/jquery-1.1.3.js"></script>
<script type="text/javascript">
var jQuery_1_1_3 = $.noConflict(true);
</script>
<!-- load jQuery 1.3.2 -->
<script type="text/javascript" src="http://example.com/jquery-1.3.2.js"></script>
<script type="text/javascript">
var jQuery_1_3_2 = $.noConflict(true);
</script>
Then, instead of $('#selector').function();
, you'd do jQuery_1_3_2('#selector').function();
or jQuery_1_1_3('#selector').function();
.
How to get the current date and time of your timezone in Java?
As Jon Skeet already said, java.util.Date
does not have a time zone. A Date
object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.
When you format a Date object into a string, for example by using SimpleDateFormat
, then you can set the time zone on the DateFormat
object to let it know in which time zone you want to display the date and time:
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
System.out.println("Date and time in Madrid: " + df.format(date));
If you want the local time zone of the computer that your program is running on, use:
df.setTimeZone(TimeZone.getDefault());
Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
You might want to use your local file as a last resort.
Seems as of now jQuery's own CDN does not support https. If it did you then might want to load from there first.
So here's the sequence:
Google CDN =>
Microsoft CDN =>
Your local copy.
<!-- load jQuery from Google's CDN -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<!-- fallback to Microsoft's Ajax CDN -->
<script> window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js">\x3C/script>')</script>
<!-- fallback to local file -->
<script> window.jQuery || document.write('<script src="Assets/jquery-1.8.3.min.js">\x3C/script>')</script>
How do I speed up the gwt compiler?
The GWT compiler is doing a lot of code analysis so it is going to be difficult to speed it up. This session from Google IO 2008 will give you a good idea of what GWT is doing and why it does take so long.
My recommendation is for development use Hosted Mode as much as possible and then only compile when you want to do your testing. This does sound like the solution you've come to already, but basically that's why Hosted Mode is there (well, that and debugging).
You can speed up the GWT compile but only compiling for some browsers, rather than 5 kinds which GWT does by default. If you want to use Hosted Mode make sure you compile for at least two browsers; if you compile for a single browser then the browser detection code is optimised away and then Hosted Mode doesn't work any more.
An easy way to configure compiling for fewer browsers is to create a second module which inherits from your main module:
<module rename-to="myproject">
<inherits name="com.mycompany.MyProject"/>
<!-- Compile for IE and Chrome -->
<!-- If you compile for only one browser, the browser detection javascript
is optimised away and then Hosted Mode doesn't work -->
<set-property name="user.agent" value="ie6,safari"/>
</module>
If the rename-to
attribute is set the same then the output files will be same as if you did a full compile
GUI-based or Web-based JSON editor that works like property explorer
Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.
Converting a structure to JSON is very straightforward:
use strict;
use warnings;
use JSON::Any;
my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);
How to add a custom HTTP header to every WCF call?
A bit late to the party but Juval Lowy addresses this exact scenario in his book and the associated ServiceModelEx library.
Basically he defines ClientBase and ChannelFactory specialisations that allow specifying type-safe header values. I suggesst downloading the source and looking at the HeaderClientBase and HeaderChannelFactory classes.
John
What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?
Yes , Jared and Kelly Orr are right.
I use the following code like in edit exception.
foreach (var issue in dinner.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
in stead of
ModelState.AddRuleViolations(dinner.GetRuleViolations());
How to fix "could not find a base address that matches schema http"... in WCF
There should be a way to solve this pretty easily with external config sections and an extra deployment step that drops a deployment specific external .config file into a known location. We typically use this solution to handle the different server configurations for our different deployment environments (Staging, QA, production, etc) with our "dev box" being the default if no special copy occurs.
Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?
I am surprised that there isn't more information posted about Solr. Solr is quite similar to Sphinx but has more advanced features (AFAIK as I haven't used Sphinx -- only read about it).
The answer at the link below details a few things about Sphinx which also applies to Solr.
Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?
Solr also provides the following additional features:
- Supports replication
- Multiple cores (think of these as separate databases with their own configuration and own indexes)
- Boolean searches
- Highlighting of keywords (fairly easy to do in application code if you have regex-fu; however, why not let a specialized tool do a better job for you)
- Update index via XML or delimited file
- Communicate with the search server via HTTP (it can even return Json, Native PHP/Ruby/Python)
- PDF, Word document indexing
- Dynamic fields
- Facets
- Aggregate fields
- Stop words, synonyms, etc.
- More Like this...
- Index directly from the database with custom queries
- Auto-suggest
- Cache Autowarming
- Fast indexing (compare to MySQL full-text search indexing times) -- Lucene uses a binary inverted index format.
- Boosting (custom rules for increasing relevance of a particular keyword or phrase, etc.)
- Fielded searches (if a search user knows the field he/she wants to search, they narrow down their search by typing the field, then the value, and ONLY that field is searched rather than everything -- much better user experience)
BTW, there are tons more features; however, I've listed just the features that I have actually used in production. BTW, out of the box, MySQL supports #1, #3, and #11 (limited) on the list above. For the features you are looking for, a relational database isn't going to cut it. I'd eliminate those straight away.
Also, another benefit is that Solr (well, Lucene actually) is a document database (e.g. NoSQL) so many of the benefits of any other document database can be realized with Solr. In other words, you can use it for more than just search (i.e. Performance). Get creative with it :)
Formatting code snippets for blogging on Blogger
I have created a tool that gets the job done. You can find it on my blog:
Free Online C# Code Colorizer
Besides colorizing your C# code, the tool also takes care of all the '<' and '>' symbols convering them to '<' and '&gt;'. Tabs are converted to spaces in order to look the same in different browsers. You can even make the colorizer inline the CSS styles, in case you cannot or you do not want to insert a CSS style sheet in you blog or website.
Pushing an existing Git repository to SVN
Yet another sequence that worked (with some comments on each step):
Install git-svn
and subversion
toolkits:
sudo apt-get install git-svn subversion
Switch inside the PROJECT_FOLDER
cd PROJECT_FOLDER
Create the project path on the Subversion server (unfortunately the current git-svn
plugin has a defect in comparison with TortoiseSVN). It is unable to store source code directly into the PROJECT_FOLDER
. Instead, by default, it will upload all the code into PROJECT_FOLDER/trunk
.
svn mkdir --parents protocol:///path/to/repo/PROJECT_FOLDER/trunk -m "creating git repo placeholder"
This is the place where trunk
at the end of the path is mandatory
Initialize the git-svn
plugin context inside the .git
folder
git svn init -s protocol:///path/to/repo/PROJECT_FOLDER
This is the place where trunk
at the end of the path is unnecessary
Fetch an empty Subversion
repository information
git svn fetch
This step is helping to synchronize the Subversion server with the git-svn
plugin. This is the moment when git-svn
plugin establishes remotes/origin
path and associates it with the trunk
subfolder on the server side.
Rebase old Git commits happened before the git-svn
plugin became involved in the process (this step is optional)
git rebase origin/trunk
Add new/modified files to commit (this step is regular for Git activities and is optional)
git add .
Commit freshly added files into the local Git repository (this step is optional and is only applicable if step 7 has been used):
git commit -m "Importing Git repository"
Pushing all the project changes history into the Subversion server:
git svn dcommit
How to load up CSS files using Javascript?
I know this is a pretty old thread but here comes my 5 cents.
There is another way to do this depending on what your needs are.
I have a case where i want a css file to be active only a while. Like css switching. Activate the css and then after another event deativate it.
Instead of loading the css dynamically and then removing it you can add a Class/an id in front of all elements in the new css and then just switch that class/id of the base node of your css (like body tag).
You would with this solution have more css files initially loaded but you have a more dynamic way of switching css layouts.
WCF service startup error "This collection already contains an address with scheme http"
I had this problem, and the cause was rather silly. I was trying out Microsoft's demo regarding running a ServiceHost from w/in a Command Line executable. I followed the instructions, including where it says to add the appropriate Service (and interface). But I got the above error.
Turns out when I added the service class, VS automatically added the configuration to the app.config. And the demo was trying to add that info too. Since it was already in the config, I removed the demo part, and it worked.
TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"
I got this error too when I had my server as an exception for the proxy in the SVN config file like this: http-proxy-exceptions = *.repo.domain.com
The solution for me was to use the svn server IP instead of the name. For some reason the name was not getting properly resolved from Eclipse Juno - Subclipse and from TortoiseSVN.
So, what worked for me: http-proxy-exceptions = XXX.XX.X.X
(the server IP)
Trying to use Spring Boot REST to Read JSON String from POST
To add on to Andrea's solution, if you are passing an array of JSONs for instance
[
{"name":"value"},
{"name":"value2"}
]
Then you will need to set up the Spring Boot Controller like so:
@RequestMapping(
value = "/process",
method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object>[] payload)
throws Exception {
System.out.println(payload);
}
Eclipse and Windows newlines
To recursively remove the carriage returns (\r
) from the CVS/* files in all child directories, run the following in a unix shell:
find ./ -wholename "\*CVS/[RE]\*" -exec dos2unix -q -o {} \;
Git - how delete file from remote repository
The easiest thing to do is to move the file from your local directory temporarily, then commit changes to your remote repo. Then add it back to your local repo, make sure to update .gitignore so it doesn't commit to remote again
Query to list all users of a certain group
memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:
(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))
If you don't yet have the distinguished name, you can search for it with:
(&(objectCategory=group)(cn=myCustomGroup))
and return the attribute distinguishedName
. Case may matter.
UTF-8 all the way through
I recently discovered that using strtolower()
can cause issues where the data is truncated after a special character.
The solution was to use
mb_strtolower($string, 'UTF-8');
mb_ uses MultiByte. It supports more characters but in general is a little slower.
What is the effect of encoding an image in base64?
It will definitely cost you more space & bandwidth if you want to use base64 encoded images. However if your site has a lot of small images you can decrease the page loading time by encoding your images to base64 and placing them into html. In this way, the client browser wont need to make a lot of connections to the images, but will have them in html.
How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?
cat /proc/meminfo | grep MemTotal
or free gives you the exact amount of RAM your server has. This is not "available memory".
I guess your issue comes up when you have a VM and you would like to calculate the full amount of memory hosted by the hypervisor but you will have to log into the hypervisor in that case.
cat /proc/meminfo | grep MemTotal
is equivalent to
getconf -a | grep PAGES | awk 'BEGIN {total = 1} {if (NR == 1 || NR == 3) total *=$NF} END {print total / 1024" kB"}'
Jinja2 template not rendering if-elif-else statement properly
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
- Used
{% elif ... %}
instead of {$ elif ... %}
.
- moved the
</tr>
tag out of the if
conditional structure, it needs to be there always.
- put quotes around the
id
attribute
Note that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
C++ performance vs. Java/C#
Actually, C# does not really run in a virtual machine like Java does. IL is compiled into assembly language, which is entirely native code and runs at the same speed as native code. You can pre-JIT an .NET application which entirely removes the JIT cost and then you are running entirely native code.
The slowdown with .NET will come not because .NET code is slower, but because it does a lot more behind the scenes to do things like garbage collect, check references, store complete stack frames, etc. This can be quite powerful and helpful when building applications, but also comes at a cost. Note that you could do all these things in a C++ program as well (much of the core .NET functionality is actually .NET code which you can view in ROTOR). However, if you hand wrote the same functionality you would probably end up with a much slower program since the .NET runtime has been optimized and finely tuned.
That said, one of the strengths of managed code is that it can be fully verifiable, ie. you can verify that the code will never access another processes's memory or do unsage things before you execute it. Microsoft has a research prototype of a fully managed operating system that has suprisingly shown that a 100% managed environment can actually perform significantly faster than any modern operating system by taking advantage of this verification to turn off security features that are no longer needed by managed programs (we are talking like 10x in some cases). SE radio has a great episode talking about this project.
How to connect mySQL database using C++
Yes, you will need the mysql c++ connector library. Read on below, where I explain how to get the example given by mysql developers to work.
Note(and solution): IDE: I tried using Visual Studio 2010, but just a few sconds ago got this all to work, it seems like I missed it in the manual, but it suggests to use Visual Studio 2008. I downloaded and installed VS2008 Express for c++, followed the steps in chapter 5 of manual and errors are gone! It works. I'm happy, problem solved. Except for the one on how to get it to work on newer versions of visual studio. You should try the mysql for visual studio addon which maybe will get vs2010 or higher to connect successfully. It can be downloaded from mysql website
Whilst trying to get the example mentioned above to work, I find myself here from difficulties due to changes to the mysql dev website. I apologise for writing this as an answer, since I can't comment yet, and will edit this as I discover what to do and find the solution, so that future developers can be helped.(Since this has gotten so big it wouldn't have fitted as a comment anyways, haha)
@hd1 link to "an example" no longer works. Following the link, one will end up at the page which gives you link to the main manual. The main manual is a good reference, but seems to be quite old and outdated, and difficult for new developers, since we have no experience especially if we missing a certain file, and then what to add.
@hd1's link has moved, and can be found with a quick search by removing the url components, keeping just the article name, here it is anyways: http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-complete-example-1.html
Getting 7.5 MySQL Connector/C++ Complete Example 1 to work
Downloads:
-Get the mysql c++ connector, even though it is bigger choose the installer package, not the zip.
-Get the boost libraries from boost.org, since boost is used in connection.h and mysql_connection.h from the mysql c++ connector
Now proceed:
-Install the connector to your c drive, then go to your mysql server install folder/lib and copy all libmysql files, and paste in your connector install folder/lib/opt
-Extract the boost library to your c drive
Next:
It is alright to copy the code as it is from the example(linked above, and ofcourse into a new c++ project). You will notice errors:
-First: change
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
to
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
Not sure what that tiny double arrow is for, but I don't think it is part of c++
-Second: Fix other errors of them by reading Chapter 5 of the sql manual, note my paragraph regarding chapter 5 below
[Note 1]: Chapter 5 Building MySQL Connector/C++ Windows Applications with Microsoft Visual Studio
If you follow this chapter, using latest c++ connecter, you will likely see that what is in your connector folder and what is shown in the images are quite different. Whether you look in the mysql server installation include and lib folders or in the mysql c++ connector folders' include and lib folders, it will not match perfectly unless they update the manual, or you had a magic download, but for me they don't match with a connector download initiated March 2014.
Just follow that chapter 5,
-But for c/c++, General, Additional Include Directories include the "include" folder from the connector you installed, not server install folder
-While doing the above, also include your boost folder see note 2 below
-And for the Linker, General.. etc use the opt folder from connector/lib/opt
*[Note 2]*A second include needs to happen, you need to include from the boost library variant.hpp,
this is done the same as above, add the main folder you extracted from the boost zip download, not boost or lib or the subfolder "variant" found in boostmainfolder/boost.. Just the main folder as the second include
Next:
What is next I think is the Static Build, well it is what I did anyways. Follow it.
Then build/compile. LNK errors show up(Edit: Gone after changing ide to visual studio 2008). I think it is because I should build connector myself(if you do this in visual studio 2010 then link errors should disappear), but been working on trying to get this to work since Thursday, will see if I have the motivation to see this through after a good night sleep(and did and now finished :) ).
CREATE DATABASE permission denied in database 'master' (EF code-first)
Permission denied is a security so you need to add a "User" permission..
- Right click you database(which is .mdf file) and then properties
- Go to security tab
- Click Continue button
- Click Add button
- Click Advance button
- Another window will show, then you click the "Find Now" button on the right side.
- On the fields below, go to the bottom most and click the "Users". Click OK.
- Click the permission "Users" that you have been created, then Check the full control checkbox.
There you go. You have now permission to your database.
Note: The connection-string in the above questions is using SQL-server authentication. So, Before taking the above step, You have to login using windows-authentication first, and then you have to give permission to the user who is using sql-server authentication. Permission like "dbcreator".
if you login with SQL server authentication and trying to give permission to the user you logged in. it shows, permission denied error.
Adding a parameter to the URL with JavaScript
I have a 'class' that does this and here it is:
function QS(){
this.qs = {};
var s = location.search.replace( /^\?|#.*$/g, '' );
if( s ) {
var qsParts = s.split('&');
var i, nv;
for (i = 0; i < qsParts.length; i++) {
nv = qsParts[i].split('=');
this.qs[nv[0]] = nv[1];
}
}
}
QS.prototype.add = function( name, value ) {
if( arguments.length == 1 && arguments[0].constructor == Object ) {
this.addMany( arguments[0] );
return;
}
this.qs[name] = value;
}
QS.prototype.addMany = function( newValues ) {
for( nv in newValues ) {
this.qs[nv] = newValues[nv];
}
}
QS.prototype.remove = function( name ) {
if( arguments.length == 1 && arguments[0].constructor == Array ) {
this.removeMany( arguments[0] );
return;
}
delete this.qs[name];
}
QS.prototype.removeMany = function( deleteNames ) {
var i;
for( i = 0; i < deleteNames.length; i++ ) {
delete this.qs[deleteNames[i]];
}
}
QS.prototype.getQueryString = function() {
var nv, q = [];
for( nv in this.qs ) {
q[q.length] = nv+'='+this.qs[nv];
}
return q.join( '&' );
}
QS.prototype.toString = QS.prototype.getQueryString;
//examples
//instantiation
var qs = new QS;
alert( qs );
//add a sinle name/value
qs.add( 'new', 'true' );
alert( qs );
//add multiple key/values
qs.add( { x: 'X', y: 'Y' } );
alert( qs );
//remove single key
qs.remove( 'new' )
alert( qs );
//remove multiple keys
qs.remove( ['x', 'bogus'] )
alert( qs );
I have overridden the toString method so there is no need to call QS::getQueryString, you can use QS::toString or, as I have done in the examples just rely on the object being coerced into a string.
What is System, out, println in System.out.println() in Java
Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.
From the javadoc about System
, here's what the doc says:
public final class System
extends Object
The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
JDK1.0
Regarding System.out
public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
Bootstrap: add margin/padding space between columns
A solution for someone like me when cells got background color
HTML
<div class="row">
<div class="col-6 cssBox">
a<br />ba<br />ba<br />b
</div>
<div class="col-6 cssBox">
a<br />b
</div>
</div>
CSS
.cssBox {
background-color: red;
margin: 0 10px;
flex-basis: calc(50% - 20px);
}
How to monitor Java memory usage?
Explicitly running System.gc() on a production system is a terrible idea. If the memory gets to any size at all, the entire system can freeze while a full GC is running. On a multi-gigabyte-sized server, this can easily be very noticeable, depending on how the jvm is configured, and how much headroom it has, etc etc - I've seen pauses of more than 30 seconds.
Another issue is that by explicitly calling GC you're not actually monitoring how the JVM is running the GC, you're actually altering it - depending on how you've configured the JVM, it's going to garbage collect when appropriate, and usually incrementally (It doesn't just run a full GC when it runs out of memory). What you'll be printing out will be nothing like what the JVM will do on it's own - for one thing you'll probably see fewer automatic / incremental GC's as you'll be clearing the memory manually.
As Nick Holt's post points out, options to print GC activity already exist as JVM flags.
You could have a thread that just prints out free and available at reasonable intervals, this will show you actual mem useage.
PostgreSQL Exception Handling
You could write this as a psql script, e.g.,
START TRANSACTION;
CREATE TABLE ...
CREATE TABLE ...
COMMIT;
\echo 'Task completed sucessfully.'
and run with
psql -f somefile.sql
Raising errors with parameters isn't possible in PostgreSQL directly. When porting such code, some people encode the necessary information in the error string and parse it out if necessary.
It all works a bit differently, so be prepared to relearn/rethink/rewrite a lot of things.
How to get a List<string> collection of values from app.config in WPF?
I love Richard Nienaber's answer, but as Chuu pointed out, it really doesn't tell how to accomplish what Richard is refering to as a solution.
Therefore I have chosen to provide you with the way I ended up doing this, ending with the result Richard is talking about.
The solution
In this case I'm creating a greeting widget that needs to know which options it has to greet in. This may be an over-engineered solution to OPs question as I am also creating an container for possible future widgets.
First I set up my collection to handle the different greetings
public class GreetingWidgetCollection : System.Configuration.ConfigurationElementCollection
{
public List<IGreeting> All { get { return this.Cast<IGreeting>().ToList(); } }
public GreetingElement this[int index]
{
get
{
return base.BaseGet(index) as GreetingElement;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new GreetingElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((GreetingElement)element).Greeting;
}
}
Then we create the acutal greeting element and it's interface
(You can omit the interface, that's just the way I'm always doing it.)
public interface IGreeting
{
string Greeting { get; set; }
}
public class GreetingElement : System.Configuration.ConfigurationElement, IGreeting
{
[ConfigurationProperty("greeting", IsRequired = true)]
public string Greeting
{
get { return (string)this["greeting"]; }
set { this["greeting"] = value; }
}
}
The greetingWidget property so our config understands the collection
We define our collection GreetingWidgetCollection
as the ConfigurationProperty
greetingWidget
so that we can use "greetingWidget" as our container in the resulting XML.
public class Widgets : System.Configuration.ConfigurationSection
{
public static Widgets Widget => ConfigurationManager.GetSection("widgets") as Widgets;
[ConfigurationProperty("greetingWidget", IsRequired = true)]
public GreetingWidgetCollection GreetingWidget
{
get { return (GreetingWidgetCollection) this["greetingWidget"]; }
set { this["greetingWidget"] = value; }
}
}
The resulting XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<widgets>
<greetingWidget>
<add greeting="Hej" />
<add greeting="Goddag" />
<add greeting="Hello" />
...
<add greeting="Konnichiwa" />
<add greeting="Namaskaar" />
</greetingWidget>
</widgets>
</configuration>
And you would call it like this
List<GreetingElement> greetings = Widgets.GreetingWidget.All;
Bootstrap 4 Dropdown Menu not working?
include them with this order
this will work
i dont know why :D
<!-- jQuery -->
<script src="js/jquery-3.4.1.min.js"></script>
<!-- Popper -->
<script src="js/popper.min.js"></script>
<!-- Bootstrap js -->
<script src="js/bootstrap.min.js"></script>
httpd-xampp.conf: How to allow access to an external IP besides localhost?
Add below code in to file d:\xampp\apache\conf\extra\httpd-xampp.conf:
<IfModule alias_module>
...
Alias / "d:/xampp/my/folder/"
<Directory "d:/xampp/my/folder">
AllowOverride AuthConfig Limit
Order allow,deny
Allow from all
Require all granted
</Directory>
Above config can access from http://127.0.0.1/
Note: someone suggest that replace from Require local
to Require all granted
but not work for me
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
# Require local
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Android camera intent
Try the following I found Here's a link
If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.
EasyImage.openCamera(Activity activity, int type);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
@Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
//Some error handling
}
@Override
public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
//Handle the images
onPhotosReturned(imagesFiles);
}
});
}
SQL sum with condition
Try moving ValueDate
:
select sum(CASE
WHEN ValueDate > @startMonthDate THEN cash
ELSE 0
END)
from Table a
where a.branch = p.branch
and a.transID = p.transID
(reformatted for clarity)
You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)
The actual best answer for this problem depends on your environment, specifically what encoding your terminal expects.
The quickest one-line solution is to encode everything you print to ASCII, which your terminal is almost certain to accept, while discarding characters that you cannot print:
print ch #fails
print ch.encode('ascii', 'ignore')
The better solution is to change your terminal's encoding to utf-8, and encode everything as utf-8 before printing. You should get in the habit of thinking about your unicode encoding EVERY time you print or read a string.
No tests found for given includes Error, when running Parameterized Unit test in Android Studio
I made the mistake of defining my test like this
class MyTest {
@Test
fun `test name`() = runBlocking {
// something here that isn't Unit
}
}
That resulted in runBlocking
returning something, which meant that the method wasn't void and junit didn't recognize it as a test. That was pretty lame. I explicitly supply a type parameter now to run blocking. It won't stop the pain or get me my two hours back but it will make sure this doesn't happen again.
class MyTest {
@Test
fun `test name`() = runBlocking<Unit> { // Specify Unit
// something here that isn't Unit
}
}
Disabling enter key for form
if you use jQuery, its quite simple. Here you go
$(document).keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
}
});
Casting LinkedHashMap to Complex Object
I had similar Issue where we have GenericResponse object containing list of values
ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
redisMatchedDriverUrl,
HttpMethod.POST,
requestEntity,
ResponseDTO.class
);
Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects
ObjectMapper mapper = new ObjectMapper();
List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });
What is difference between MVC, MVP & MVVM design pattern in terms of coding c#
MVP:
Advantages:
Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.
Disadvantages:
1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.
3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.
MVC:
Advanatages:
Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.
Disadvantagaes:
Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.
MVVM:
After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.
Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.
How to print a Groovy variable in Jenkins?
You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
Random date in C#
Well, if you gonna present alternate optimization, we can also go for an iterator:
static IEnumerable<DateTime> RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
while (true)
yield return start.AddDays(gen.Next(range));
}
you could use it like this:
int i=0;
foreach(DateTime dt in RandomDay())
{
Console.WriteLine(dt);
if (++i == 10)
break;
}
Android Starting Service at Boot Time , How to restart service class after device Reboot?
Most the solutions posted here are missing an important piece: doing it without a wake lock runs the risk of your Service getting killed before it is finished processing. Saw this solution in another thread, answering here as well.
Since WakefulBroadcastReceiver is deprecated in api 26 it is recommended for API Levels below 26
You need to obtain a wake lock . Luckily, the Support library gives us a class to do this:
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
then, in your Service, make sure to release the wake lock:
@Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock.
...
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
Don't forget to add the WAKE_LOCK permission and register your receiver in the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
...
<service android:name=".SimpleWakefulReceiver">
<intent-filter>
<action android:name="com.example.SimpleWakefulReceiver"/>
</intent-filter>
</service>
How to Set Active Tab in jQuery Ui
Just to clarify in complete detail. This is what works with the current version of jQuery Ui
$( "#tabs" ).tabs( "option", "active", # );
where # is the index of the tab you want to make active.
Warning message: In `...` : invalid factor level, NA generated
The warning message is because your "Type" variable was made a factor and "lunch" was not a defined level. Use the stringsAsFactors = FALSE
flag when making your data frame to force "Type" to be a character.
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame': 3 obs. of 2 variables:
$ Type : Factor w/ 1 level "": NA 1 1
$ Amount: chr "100" "0" "0"
>
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame': 3 obs. of 2 variables:
$ Type : chr "lunch" "" ""
$ Amount: chr "100" "0" "0"
"Large data" workflows using pandas
I recently came across a similar issue. I found simply reading the data in chunks and appending it as I write it in chunks to the same csv works well. My problem was adding a date column based on information in another table, using the value of certain columns as follows. This may help those confused by dask and hdf5 but more familiar with pandas like myself.
def addDateColumn():
"""Adds time to the daily rainfall data. Reads the csv as chunks of 100k
rows at a time and outputs them, appending as needed, to a single csv.
Uses the column of the raster names to get the date.
"""
df = pd.read_csv(pathlist[1]+"CHIRPS_tanz.csv", iterator=True,
chunksize=100000) #read csv file as 100k chunks
'''Do some stuff'''
count = 1 #for indexing item in time list
for chunk in df: #for each 100k rows
newtime = [] #empty list to append repeating times for different rows
toiterate = chunk[chunk.columns[2]] #ID of raster nums to base time
while count <= toiterate.max():
for i in toiterate:
if i ==count:
newtime.append(newyears[count])
count+=1
print "Finished", str(chunknum), "chunks"
chunk["time"] = newtime #create new column in dataframe based on time
outname = "CHIRPS_tanz_time2.csv"
#append each output to same csv, using no header
chunk.to_csv(pathlist[2]+outname, mode='a', header=None, index=None)
Hiding and Showing TabPages in tabControl
It looks easier for me to clear all TabPages add add those wished:
PropertyTabControl.TabPages.Clear();
PropertyTabControl.TabPages.Add(AspectTabPage);
PropertyTabControl.TabPages.Add(WerkstattTabPage);
or
PropertyTabControl.TabPages.Clear();
PropertyTabControl.TabPages.Add(TerminTabPage);
Is std::vector copying the objects with a push_back?
Yes, std::vector<T>::push_back()
creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*>
instead of std::vector<whatever>
.
However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem).
How to replace item in array?
ES6 way:
const items = Array(523, 3452, 334, 31, ...5346);
We wanna replace 3452
with 1010
, solution:
const newItems = items.map(item => item === 3452 ? 1010 : item);
Surely, the question is for many years ago and for now I just prefer to use immutable solution, definitely, it is awesome for ReactJS
.
For frequent usage I offer below function:
const itemReplacer = (array, oldItem, newItem) =>
array.map(item => item === oldItem ? newItem : item);
How do I initialize Kotlin's MutableList to empty MutableList?
Various forms depending on type of List, for Array List:
val myList = mutableListOf<Kolory>()
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()
For LinkedList:
val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()
For other list types, will be assumed Mutable if you construct them directly:
val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()
This holds true for anything implementing the List
interface (i.e. other collections libraries).
No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:
val myList: List<Kolory> = ArrayList()
How to do a https request with bad certificate?
The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}
Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport
struct over time.
Convert comma separated string of ints to int array
import java.util.*;
import java.io.*;
public class problem
{
public static void main(String args[])enter code here
{
String line;
String[] lineVector;
int n,m,i,j;
Scanner sc = new Scanner(System.in);
line = sc.nextLine();
lineVector = line.split(",");
//enter the size of the array
n=Integer.parseInt(lineVector[0]);
m=Integer.parseInt(lineVector[1]);
int arr[][]= new int[n][m];
//enter the array here
System.out.println("Enter the array:");
for(i=0;i<n;i++)
{
line = sc.nextLine();
lineVector = line.split(",");
for(j=0;j<m;j++)
{
arr[i][j] = Integer.parseInt(lineVector[j]);
}
}
sc.close();
}
}
On the first line enter the size of the array separated by a comma. Then enter the values in the array separated by a comma.The result is stored in the array arr.
e.g
input:
2,3
1,2,3
2,4,6
will store values as
arr = {{1,2,3},{2,4,6}};
Recommended way to get hostname in Java
Environment variables may also provide a useful means -- COMPUTERNAME
on Windows, HOSTNAME
on most modern Unix/Linux shells.
See: https://stackoverflow.com/a/17956000/768795
I'm using these as "supplementary" methods to InetAddress.getLocalHost().getHostName()
, since as several people point out, that function doesn't work in all environments.
Runtime.getRuntime().exec("hostname")
is another possible supplement. At this stage, I haven't used it.
import java.net.InetAddress;
import java.net.UnknownHostException;
// try InetAddress.LocalHost first;
// NOTE -- InetAddress.getLocalHost().getHostName() will not work in certain environments.
try {
String result = InetAddress.getLocalHost().getHostName();
if (StringUtils.isNotEmpty( result))
return result;
} catch (UnknownHostException e) {
// failed; try alternate means.
}
// try environment properties.
//
String host = System.getenv("COMPUTERNAME");
if (host != null)
return host;
host = System.getenv("HOSTNAME");
if (host != null)
return host;
// undetermined.
return null;
Get Base64 encode file-data from Input Form
After struggling with this myself, I've come to implement FileReader for browsers that support it (Chrome, Firefox and the as-yet unreleased Safari 6), and a PHP script that echos back POSTed file data as Base64-encoded data for the other browsers.
Changing route doesn't scroll to top in the new page
Using angularjs UI Router, what I'm doing is this:
.state('myState', {
url: '/myState',
templateUrl: 'app/views/myState.html',
onEnter: scrollContent
})
With:
var scrollContent = function() {
// Your favorite scroll method here
};
It never fails on any page, and it is not global.
How to create custom exceptions in Java?
For a checked exception:
public class MyCustomException extends Exception { }
Technically, anything that extends Throwable
can be an thrown, but exceptions are generally extensions of the Exception
class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Error
s which usually are not something designed to be gracefully handled beyond the JVM internals.
You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.
As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via
throw new MyCustomException()
and catch via
catch (MyCustomException e) { }
Read file content from S3 bucket with boto3
boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide readline
or readlines
.
s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
key = obj.key
body = obj.get()['Body'].read()
How to change Jquery UI Slider handle
The CSS class that can be changed to add a image to the JQuery slider handle is called ".ui-slider-horizontal .ui-slider-handle".
The following code shows a demo:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script>
<style type="text/css">
.ui-slider-horizontal .ui-state-default {background: white url(http://stackoverflow.com/content/img/so/vote-arrow-down.png) no-repeat scroll 50% 50%;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#slider").slider();
});
</script>
</head>
<body>
<div id="slider"></div>
</body>
</html>
I think registering a handle option was the old way of doing it and no longer supported in JQuery-ui 1.7.2?
Cleanest way to reset forms
//Declare the jquery param on top after import
declare var $: any;
declare var jQuery: any;
clearForm() {
$('#contactForm')[0].reset();
}
In where shall I use isset() and !empty()
!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations
<?php
$array = [ "name_new" => "print me"];
if (!empty($array['name'])){
echo $array['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array2 = [ "name" => NULL];
if (!empty($array2['name'])){
echo $array2['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array3 = [ "name" => ""];
if (!empty($array3['name'])){
echo $array3['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array4 = [1,2];
if (!empty($array4['name'])){
echo $array4['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array5 = [];
if (!empty($array5['name'])){
echo $array5['name'];
}
//output : {nothing}
?>
Spring Boot REST service exception handling
Although this is an older question, I would like to share my thoughts on this. I hope, that it will be helpful to some of you.
I am currently building a REST API which makes use of Spring Boot 1.5.2.RELEASE with Spring Framework 4.3.7.RELEASE. I use the Java Config approach (as opposed to XML configuration). Also, my project uses a global exception handling mechanism using the @RestControllerAdvice
annotation (see later below).
My project has the same requirements as yours: I want my REST API to return a HTTP 404 Not Found
with an accompanying JSON payload in the HTTP response to the API client when it tries to send a request to an URL which does not exist. In my case, the JSON payload looks like this (which clearly differs from the Spring Boot default, btw.):
{
"code": 1000,
"message": "No handler found for your request.",
"timestamp": "2017-11-20T02:40:57.628Z"
}
I finally made it work. Here are the main tasks you need to do in brief:
- Make sure that the
NoHandlerFoundException
is thrown if API clients
call URLS for which no handler method exists (see Step 1 below).
- Create a custom error class (in my case
ApiError
) which contains all the data that should be returned to the API client (see step 2).
- Create an exception handler which reacts on the
NoHandlerFoundException
and returns a proper error message to the API client (see step 3).
- Write a test for it and make sure, it works (see step 4).
Ok, now on to the details:
Step 1: Configure application.properties
I had to add the following two configuration settings to the project's application.properties
file:
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
This makes sure, the NoHandlerFoundException
is thrown in cases where a client tries to access an URL for which no controller method exists which would be able to handle the request.
Step 2: Create a Class for API Errors
I made a class similar to the one suggested in this article on Eugen Paraschiv's blog. This class represents an API error. This information is
sent to the client in the HTTP response body in case of an error.
public class ApiError {
private int code;
private String message;
private Instant timestamp;
public ApiError(int code, String message) {
this.code = code;
this.message = message;
this.timestamp = Instant.now();
}
public ApiError(int code, String message, Instant timestamp) {
this.code = code;
this.message = message;
this.timestamp = timestamp;
}
// Getters and setters here...
}
Step 3: Create / Configure a Global Exception Handler
I use the following class to handle exceptions (for simplicity, I have removed import statements, logging code and some other, non-relevant pieces of code):
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiError noHandlerFoundException(
NoHandlerFoundException ex) {
int code = 1000;
String message = "No handler found for your request.";
return new ApiError(code, message);
}
// More exception handlers here ...
}
Step 4: Write a test
I want to make sure, the API always returns the correct error messages to the calling client, even in the case of failure. Thus, I wrote a test like this:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SprintBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("dev")
public class GlobalExceptionHandlerIntegrationTest {
public static final String ISO8601_DATE_REGEX =
"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$";
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(roles = "DEVICE_SCAN_HOSTS")
public void invalidUrl_returnsHttp404() throws Exception {
RequestBuilder requestBuilder = getGetRequestBuilder("/does-not-exist");
mockMvc.perform(requestBuilder)
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.code", is(1000)))
.andExpect(jsonPath("$.message", is("No handler found for your request.")))
.andExpect(jsonPath("$.timestamp", RegexMatcher.matchesRegex(ISO8601_DATE_REGEX)));
}
private RequestBuilder getGetRequestBuilder(String url) {
return MockMvcRequestBuilders
.get(url)
.accept(MediaType.APPLICATION_JSON);
}
The @ActiveProfiles("dev")
annotation can be left away. I use it only as I work with different profiles. The RegexMatcher
is a custom Hamcrest matcher I use to better handle timestamp fields. Here's the code (I found it here):
public class RegexMatcher extends TypeSafeMatcher<String> {
private final String regex;
public RegexMatcher(final String regex) {
this.regex = regex;
}
@Override
public void describeTo(final Description description) {
description.appendText("matches regular expression=`" + regex + "`");
}
@Override
public boolean matchesSafely(final String string) {
return string.matches(regex);
}
// Matcher method you can call on this matcher class
public static RegexMatcher matchesRegex(final String string) {
return new RegexMatcher(regex);
}
}
Some further notes from my side:
- In many other posts on StackOverflow, people suggested setting the
@EnableWebMvc
annotation. This was not necessary in my case.
- This approach works well with MockMvc (see test above).
R dates "origin" must be supplied
So generally this has been solved, but you might get this error message because the date you use is not in the correct format.
I know this is an old post, but whenever I run this I get NA all the way down my date column. My dates are in this format 20150521 – NealC Jun 5 '15 at 16:06
If you have dates of this format just check the format of your dates with:
str(sides$date)
If the format is not a character, then convert it:
as.character(sides$date)
For as.Date, you won't need an origin any longer, because this is supplied for numeric values only. Thus you can use (assuming you have the format of NealC):
as.Date(as.character(sides$date),format="%Y%m%d")
I hope this might help some of you.
How to uncommit my last commit in Git
Be careful with that.
But you can use the rebase command
git rebase -i HEAD~2
A vi
will open and all you have to do is delete the line with the commit. Also can read instructions that were shown in proper edition @ vi
. A couple of things can be performed on this mode.
Using bind variables with dynamic SELECT INTO clause in PL/SQL
In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up.
My vote goes to your first option,
EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;
Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.
MySQL Insert query doesn't work with WHERE clause
The simplest way is to use IF to violate your a key constraint. This only works for INSERT IGNORE but will allow you to use constraint in a INSERT.
INSERT INTO Test (id, name) VALUES (IF(1!=0,NULL,1),'Test');
How can I make a clickable link in an NSAttributedString?
I have written a method, that adds a link(linkString) to a string (fullString) with a certain url(urlString):
- (NSAttributedString *)linkedStringFromFullString:(NSString *)fullString withLinkString:(NSString *)linkString andUrlString:(NSString *)urlString
{
NSRange range = [fullString rangeOfString:linkString options:NSLiteralSearch];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:fullString];
NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = @{NSForegroundColorAttributeName:RGB(0x999999),
NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Light" size:10],
NSParagraphStyleAttributeName:paragraphStyle};
[str addAttributes:attributes range:NSMakeRange(0, [str length])];
[str addAttribute: NSLinkAttributeName value:urlString range:range];
return str;
}
You should call it like this:
NSString *fullString = @"A man who bought the Google.com domain name for $12 and owned it for about a minute has been rewarded by Google for uncovering the flaw.";
NSString *linkString = @"Google.com";
NSString *urlString = @"http://www.google.com";
_youTextView.attributedText = [self linkedStringFromFullString:fullString withLinkString:linkString andUrlString:urlString];
How to inherit constructors?
Too bad we're kind of forced to tell the compiler the obvious:
Subclass(): base() {}
Subclass(int x): base(x) {}
Subclass(int x,y): base(x,y) {}
I only need to do 3 constructors in 12 subclasses, so it's no big deal, but I'm not too fond of repeating that on every subclass, after being used to not having to write it for so long. I'm sure there's a valid reason for it, but I don't think I've ever encountered a problem that requires this kind of restriction.
How do I find out where login scripts live?
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
Calculating number of full months between two dates in SQL
SELECT dateadd(dd,number,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)) AS gun FROM master..spt_values
WHERE type = 'p'
AND year(dateadd(dd,number,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)))=year(DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))
Get file content from URL?
1) local simplest methods
<?php
echo readfile("http://example.com/"); //needs "Allow_url_include" enabled
//OR
echo include("http://example.com/"); //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb" //needs "Allow_url_fopen" enabled
?>
2) Better Way is CURL:
echo get_remote_data('http://example.com'); // GET request
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request
It automatically handles FOLLOWLOCATION problem + Remote urls:
src="./imageblabla.png"
turned into:
src="http://example.com/path/imageblabla.png"
Code : https://github.com/tazotodua/useful-php-scripts/blob/master/get-remote-url-content-data.php
SQL Server Installation - What is the Installation Media Folder?
If you've downloaded SQL from the Microsoft site, rename the file to a zip file and then you can extract the files inside to a folder, then choose that one when you "Browse for SQL server Installation Media"
SQLEXPRADV_x64_ENU.exe > SQLEXPRADV_x64_ENU.zip
7zip will open it (standard Windows zip doesn't work though)
Extract to something like C:\SQLInstallMedia
You will get folders like 1033_enu_lp, resources, x64 and a bunch of files.
increase the java heap size permanently?
This worked for me:
export _JAVA_OPTIONS="-Xmx1g"
It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:
java -XshowSettings:vm
and it will tell you:
Picked up _JAVA_OPTIONS: -Xmx1g
Difference between Iterator and Listiterator?
the following is that the difference between iterator and listIterator
iterator :
boolean hasNext();
E next();
void remove();
listIterator:
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);
C# How to determine if a number is a multiple of another?
I don't get that part about the string stuff, but why don't you use the modulo operator (%
) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.
It goes like that:
int a = 10; int b = 5;
// is a a multiple of b
if ( a % b == 0 ) ....
What to put in a python module docstring?
To quote the specifications:
The docstring of a script
(a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.
The docstring for a module
should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py
module) should also list the modules and subpackages exported by the package.
The docstring for a class
should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__
method. Individual methods should be documented by their own docstring.
The docstring of a function or method
is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
Re-render React component when prop changes
I would recommend having a look at this answer of mine, and see if it is relevant to what you are doing. If I understand your real problem, it's that your just not using your async action correctly and updating the redux "store", which will automatically update your component with it's new props.
This section of your code:
componentDidMount() {
if (this.props.isManager) {
this.props.dispatch(actions.fetchAllSites())
} else {
const currentUserId = this.props.user.get('id')
this.props.dispatch(actions.fetchUsersSites(currentUserId))
}
}
Should not be triggering in a component, it should be handled after executing your first request.
Have a look at this example from redux-thunk:
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
You don't necessarily have to use redux-thunk, but it will help you reason about scenarios like this and write code to match.
"Debug certificate expired" error in Eclipse Android plugins
H-m-m-m. Interesting how so many people have had slightly different experiences with this. I remember the days when this was considered a sign that the software was not ready for release, and the team would actually fix it BEFORE users started seeing these problems:(
My own experience was just a little different. I had already tried Project>Clean, but still got the same build failure. Then I deleted the debug.keystore (under .android) just as the first answer said. Still got the same problem. Then I did a clean again, and wonder of wonders, it worked!
Now don't get me wrong, I am glad that I got it working thanks to the hints in this thread. But clearly clean isn't working right, and how did it find an expired key after I deleted the keystore??? Clearly something is wrong with Eclipse or the ADT -- not so sure which.
Node.js get file extension
import extname in order to return the extension the file:
import { extname } from 'path';
extname(file.originalname);
where file is the file 'name' of form
Jquery Ajax Posting json to webservice
You mentioned using json2.js to stringify your data, but the POSTed data appears to be URLEncoded JSON You may have already seen it, but this post about the invalid JSON primitive covers why the JSON is being URLEncoded.
I'd advise against passing a raw, manually-serialized JSON string into your method. ASP.NET is going to automatically JSON deserialize the request's POST data, so if you're manually serializing and sending a JSON string to ASP.NET, you'll actually end up having to JSON serialize your JSON serialized string.
I'd suggest something more along these lines:
var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }];
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ Markers: markers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
error: function(errMsg) {
alert(errMsg);
}
});
The key to avoiding the invalid JSON primitive issue is to pass jQuery a JSON string for the data
parameter, not a JavaScript object, so that jQuery doesn't attempt to URLEncode your data.
On the server-side, match your method's input parameters to the shape of the data you're passing in:
public class Marker
{
public decimal position { get; set; }
public int markerPosition { get; set; }
}
[WebMethod]
public string CreateMarkers(List<Marker> Markers)
{
return "Received " + Markers.Count + " markers.";
}
You can also accept an array, like Marker[] Markers
, if you prefer. The deserializer that ASMX ScriptServices uses (JavaScriptSerializer) is pretty flexible, and will do what it can to convert your input data into the server-side type you specify.
Measure the time it takes to execute a t-sql query
Another way is using a SQL Server built-in feature named Client Statistics
which is accessible through Menu > Query > Include Client Statistics.
You can run each query in separated query window and compare the results which is given in Client Statistics
tab just beside the Messages
tab.
For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.
You can read all 3 ways for acquiring execution time in here.
You may even need to display Estimated Execution Plan
ctrlL for further investigation about your query.
Javascript how to parse JSON array
Not sure if my data matched exactly but I had an array of arrays of JSON objects, that got exported from jQuery FormBuilder when using pages.
Hopefully my answer can help anyone who stumbles onto this question looking for an answer to a problem similar to what I had.
The data looked somewhat like this:
var allData =
[
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
],
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
]
]
What I did to parse this was to simply do the following:
JSON.parse("["+allData.toString()+"]")
C# Switch-case string starting with
In addition to substring answer, you can do it as mystring.SubString(0,3) and check in case statement if its "abc".
But before the switch statement you need to ensure that your mystring is atleast 3 in length.
How to properly use the "choices" field option in Django
$ pip install django-better-choices
For those who are interested, I have created django-better-choices
library, that provides a nice interface to work with Django choices for Python 3.7+. It supports custom parameters, lots of useful features and is very IDE friendly.
You can define your choices as a class:
from django_better_choices import Choices
class PAGE_STATUS(Choices):
CREATED = 'Created'
PENDING = Choices.Value('Pending', help_text='This set status to pending')
ON_HOLD = Choices.Value('On Hold', value='custom_on_hold')
VALID = Choices.Subset('CREATED', 'ON_HOLD')
class INTERNAL_STATUS(Choices):
REVIEW = 'On Review'
@classmethod
def get_help_text(cls):
return tuple(
value.help_text
for value in cls.values()
if hasattr(value, 'help_text')
)
Then do the following operations and much much more:
print( PAGE_STATUS.CREATED ) # 'created'
print( PAGE_STATUS.ON_HOLD ) # 'custom_on_hold'
print( PAGE_STATUS.PENDING.display ) # 'Pending'
print( PAGE_STATUS.PENDING.help_text ) # 'This set status to pending'
'custom_on_hold' in PAGE_STATUS.VALID # True
PAGE_STATUS.CREATED in PAGE_STATUS.VALID # True
PAGE_STATUS.extract('CREATED', 'ON_HOLD') # ~= PAGE_STATUS.VALID
for value, display in PAGE_STATUS:
print( value, display )
PAGE_STATUS.get_help_text()
PAGE_STATUS.VALID.get_help_text()
And of course, it is fully supported by Django and Django Migrations:
class Page(models.Model):
status = models.CharField(choices=PAGE_STATUS, default=PAGE_STATUS.CREATED)
Full documentation here: https://pypi.org/project/django-better-choices/
Oracle PL/SQL : remove "space characters" from a string
To remove any whitespaces you could use:
myValue := replace(replace(replace(replace(replace(replace(myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13));
Example: remove all whitespaces in a table:
update myTable t
set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
where
length(t.myValue) > length(replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13)));
or
update myTable t
set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
where
t.myValue like '% %'
Capture key press (or keydown) event on DIV element
(1) Set the tabindex
attribute:
<div id="mydiv" tabindex="0" />
(2) Bind to keydown:
$('#mydiv').on('keydown', function(event) {
//console.log(event.keyCode);
switch(event.keyCode){
//....your actions for the keys .....
}
});
To set the focus on start:
$(function() {
$('#mydiv').focus();
});
To remove - if you don't like it - the div
focus border, set outline: none
in the CSS.
See the table of keycodes for more keyCode
possibilities.
All of the code assuming you use jQuery.
#
Find PHP version on windows command line
This how I check php version
PS C:\Windows\system32> php -version
Result:
PHP 7.2.7 (cli) (built: Jun 19 2018 23:44:15) ( NTS MSVC15 (Visual C++ 2017) x86 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
PS C:\Windows\system32>
Most efficient way to reverse a numpy array
Because this seems to not be marked as answered yet... The Answer of Thomas Arildsen should be the proper one: just use
np.flipud(your_array)
if it is a 1d array (column array).
With matrizes do
fliplr(matrix)
if you want to reverse rows and flipud(matrix)
if you want to flip columns. No need for making your 1d column array a 2dimensional row array (matrix with one None layer) and then flipping it.
Configure cron job to run every 15 minutes on Jenkins
1) Your cron is wrong. If you want to run job every 15 mins on Jenkins use this:
H/15 * * * *
2) Warning from Jenkins Spread load evenly by using ‘...’ rather than ‘...’
came with JENKINS-17311:
To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.
Examples:
H/15 * * * *
- every fifteen minutes (perhaps at :07, :22, :37, :52):
H(0-29)/10 * * * *
- every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24)
H 9-16/2 * * 1-5
- once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM)
H H 1,15 1-11 *
- once a day on the 1st and 15th of every month except December
Getting Index of an item in an arraylist;
Rather than a brute force loop through the list (eg 1 to 10000), rather use an iterative search approach :
The List needs to be sorted by the element to be tested.
Start search at the middle element size()/2 eg 5000
if search item greater than element at 5000, then test the element at the midpoint between the upper(10000) and midpoint(5000) - 7500
keep doing this until you reach the match (or use a brute force loop through once you get down to a smaller range (eg 20 items)
You can search a list of 10000 in around 13 to 14 tests, rather than potentially 9999 tests.
Python function global variables?
As others have noted, you need to declare a variable global
in a function when you want that function to be able to modify the global variable. If you only want to access it, then you don't need global
.
To go into a bit more detail on that, what "modify" means is this: if you want to re-bind the global name so it points to a different object, the name must be declared global
in the function.
Many operations that modify (mutate) an object do not re-bind the global name to point to a different object, and so they are all valid without declaring the name global
in the function.
d = {}
l = []
o = type("object", (object,), {})()
def valid(): # these are all valid without declaring any names global!
d[0] = 1 # changes what's in d, but d still points to the same object
d[0] += 1 # ditto
d.clear() # ditto! d is now empty but it`s still the same object!
l.append(0) # l is still the same list but has an additional member
o.test = 1 # creating new attribute on o, but o is still the same object
How to round up a number to nearest 10?
floor()
will go down.
ceil()
will go up.
round()
will go to nearest by default.
Divide by 10, do the ceil, then multiply by 10 to reduce the significant digits.
$number = ceil($input / 10) * 10;
Edit: I've been doing it this way for so long.. but TallGreenTree's answer is cleaner.
"Invalid form control" only in Google Chrome
It will show that message if you have code like this:
<form>
<div style="display: none;">
<input name="test" type="text" required/>
</div>
<input type="submit"/>
</form>
solution to this problem will depend on how the site should work
for example if you don't want the form to submit unless this field is required you should disable the submit button
so the js code to show the div should enable the submit button as well
you can hide the button too (should be disabled and hidden because if it's hidden but not disabled the user can submit the form with others way like press enter
in any other field but if the button is disabled this won't happen
if you want the form to submit if the div is hidden you should disable any required input inside it and enable the inputs while you are showing the div
if someone need the codes to do so you should tell me exactly what you need
What does void do in java?
Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.
Test if a command outputs an empty string
Sometimes you want to save the output, if it's non-empty, to pass it to another command. If so, you could use something like
list=`grep -l "MY_DESIRED_STRING" *.log `
if [ $? -eq 0 ]
then
/bin/rm $list
fi
This way, the rm
command won't hang if the list is empty.
Generating random numbers in C
int *generate_randomnumbers(int start, int end){
int *res = malloc(sizeof(int)*(end-start));
srand(time(NULL));
for (int i= 0; i < (end -start)+1; i++){
int r = rand()%end + start;
int dup = 0;
for (int j = 0; j < (end -start)+1; j++){
if (res[j] == r){
i--;
dup = 1;
break;
}
}
if (!dup)
res[i] = r;
}
return res;
}
Job for mysqld.service failed See "systemctl status mysqld.service"
In my particular case, the error was appearing due to missing /var/log/mysql
with mysql-server
package 5.7.21-1 on Debian-based Linux distro. Having ran strace
and sudo /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid
( which is what the systemd
service actually runs), it became apparent that the issue was due to this:
2019-01-01T09:09:22.102568Z 0 [ERROR] Could not open file '/var/log/mysql/error.log' for error logging: No such file or directory
I've recently removed contents of several directories in /var/log
so it was no surprise. The solution was to create the directory and make it owned by mysql
user as in
$ sudo mkdir /var/log/mysql
$ sudo chown -R mysql:mysql /var/log/mysql
Having done that I've happily logged in via sudo mysql -u root
and greeted with the old and familiar mysql>
prompt
Failed Apache2 start, no error log
Thanks, Tim! Big stumper for me. A few other details others may find helpful:
(Apache2 on Ubuntu 12.04)
I have two sites running on the same server and had just updated the SSL cert for one of them. Upon restarting the server, I got that cryptic message and neither site worked (obviously). I too found the redirect for the log files in the config files. I tracked that down and found the issue (in the log file for the site I had just updated).
My config files are located in /etc/apache2/sites-available
vim or cat the file (cat {filename}) and look for the ErrorLog line. That tells you where to look on your server. cat that file and the error message I found was:
[error] Unable to configure RSA server private key
[error] SSL Library Error: 185073780 error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch
[warn] RSA server certificate CommonName (CN) `<snip>.com' does NOT match server name!?
I had copied one of my cert files to the wrong directory. I simply moved it to the correct directory and everything was fine on the next start. (tip: where those file should be is also in the config file ;)
How to create a DB link between two oracle instances
Creation of DB Link
CREATE DATABASE LINK dblinkname
CONNECT TO $usename
IDENTIFIED BY $password
USING '$sid';
(Note: sid is being passed between single quotes above. )
Example Queries for above DB Link
select * from tableA@dblinkname;
insert into tableA(select * from tableA@dblinkname);
Modifying a file inside a jar
most of the answers above saying you can't do it for class file.
Even if you want to update class file you can do that also.
All you need to do is that drag and drop the class file from your workspace in the jar.
In case you want to verify your changes in class file , you can do it using a decompiler like jd-gui.
Max retries exceeded with URL in requests
I got similar problem but the following code worked for me.
url = <some REST url>
page = requests.get(url, verify=False)
"verify=False" disables SSL verification. Try and catch can be added as usual.
Calculating distance between two points (Latitude, Longitude)
As you're using SQL 2008 or later, I'd recommend checking out the GEOGRAPHY data type. SQL has built in support for geospatial queries.
e.g. you'd have a column in your table of type GEOGRAPHY which would be populated with a geospatial representation of the coordinates (check out the MSDN reference linked above for examples). This datatype then exposes methods allowing you to perform a whole host of geospatial queries (e.g. finding the distance between 2 points)
Getting attribute of element in ng-click function in angularjs
Addition to the answer of Brett DeWoody: (which is updated now)
var dataValue = obj.srcElement.attributes.data.nodeValue;
Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property.
I found:
var dataValue = obj.currentTarget.attributes.data.nodeValue;
Works in IE, Chrome and FF, I did not test Safari.
How can I list (ls) the 5 last modified files in a directory?
The accepted answer lists only the filenames, but to get the top 5 files one can also use:
ls -lht | head -6
where:
-l
outputs in a list format
-h
makes output human readable (i.e. file sizes appear in kb, mb, etc.)
-t
sorts output by placing most recently modified file first
head -6
will show 5 files because ls
prints the block size in the first line of output.
I think this is a slightly more elegant and possibly more useful approach.
Example output:
total 26960312
-rw-r--r--@ 1 user staff 1.2K 11 Jan 11:22 phone2.7.py
-rw-r--r--@ 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf
-rw-r--r--@ 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf
-rw-r--r--@ 1 user staff 502K 8 Jan 10:20 lab-01.pdf
-rw-rw-rw-@ 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv
Interfaces vs. abstract classes
The real question is: whether to use interfaces or base classes. This has been covered before.
In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.
How to import existing Git repository into another?
I can suggest another solution (alternative to git-submodules) for your problem - gil (git links) tool
It allows to describe and manage complex git repositories dependencies.
Also it provides a solution to the git recursive submodules dependency problem.
Consider you have the following project dependencies:
sample git repository dependency graph
Then you can define .gitlinks
file with repositories relation description:
# Projects
CppBenchmark CppBenchmark https://github.com/chronoxor/CppBenchmark.git master
CppCommon CppCommon https://github.com/chronoxor/CppCommon.git master
CppLogging CppLogging https://github.com/chronoxor/CppLogging.git master
# Modules
Catch2 modules/Catch2 https://github.com/catchorg/Catch2.git master
cpp-optparse modules/cpp-optparse https://github.com/weisslj/cpp-optparse.git master
fmt modules/fmt https://github.com/fmtlib/fmt.git master
HdrHistogram modules/HdrHistogram https://github.com/HdrHistogram/HdrHistogram_c.git master
zlib modules/zlib https://github.com/madler/zlib.git master
# Scripts
build scripts/build https://github.com/chronoxor/CppBuildScripts.git master
cmake scripts/cmake https://github.com/chronoxor/CppCMakeScripts.git master
Each line describe git link in the following format:
- Unique name of the repository
- Relative path of the repository (started from the path of .gitlinks file)
- Git repository which will be used in git clone command
Repository branch to checkout
- Empty line or line started with # are not parsed (treated as comment).
Finally you have to update your root sample repository:
# Clone and link all git links dependencies from .gitlinks file
gil clone
gil link
# The same result with a single command
gil update
As the result you'll clone all required projects and link them to each other in a proper way.
If you want to commit all changes in some repository with all changes in child linked repositories you can do it with a single command:
gil commit -a -m "Some big update"
Pull, push commands works in a similar way:
gil pull
gil push
Gil (git links) tool supports the following commands:
usage: gil command arguments
Supported commands:
help - show this help
context - command will show the current git link context of the current directory
clone - clone all repositories that are missed in the current context
link - link all repositories that are missed in the current context
update - clone and link in a single operation
pull - pull all repositories in the current directory
push - push all repositories in the current directory
commit - commit all repositories in the current directory
More about git recursive submodules dependency problem.
How to read all files in a folder from Java?
Given a baseDir, lists out all the files and directories below it, written iteratively.
public static List<File> listLocalFilesAndDirsAllLevels(File baseDir) {
List<File> collectedFilesAndDirs = new ArrayList<>();
Deque<File> remainingDirs = new ArrayDeque<>();
if(baseDir.exists()) {
remainingDirs.add(baseDir);
while(!remainingDirs.isEmpty()) {
File dir = remainingDirs.removeLast();
List<File> filesInDir = Arrays.asList(dir.listFiles());
for(File fileOrDir : filesInDir) {
collectedFilesAndDirs.add(fileOrDir);
if(fileOrDir.isDirectory()) {
remainingDirs.add(fileOrDir);
}
}
}
}
return collectedFilesAndDirs;
}
How does a Linux/Unix Bash script know its own PID?
If the process is a child process and $BASHPID is not set, it is possible to query the ppid of a created child process of the running process. It might be a bit ugly, but it works. Example:
sleep 1 &
mypid=$(ps -o ppid= -p "$!")
React Router Pass Param to Component
if you are using class component, you are most likely to use GSerjo suggestion. Pass in the params via <Route>
props to your target component:
exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />}
How do I merge dictionaries together in Python?
In Python2,
d1={'a':1,'b':2}
d2={'a':10,'c':3}
d1 overrides d2:
dict(d2,**d1)
# {'a': 1, 'c': 3, 'b': 2}
d2 overrides d1:
dict(d1,**d2)
# {'a': 10, 'c': 3, 'b': 2}
This behavior is not just a fluke of implementation; it is guaranteed in the documentation:
If a key is specified both in the
positional argument and as a keyword
argument, the value associated with
the keyword is retained in the
dictionary.
$http get parameters does not work
From $http.get
docs, the second parameter is a configuration object:
get(url, [config]);
Shortcut method to perform GET
request.
You may change your code to:
$http.get('accept.php', {
params: {
source: link,
category_id: category
}
});
Or:
$http({
url: 'accept.php',
method: 'GET',
params: {
source: link,
category_id: category
}
});
As a side note, since Angular 1.6: .success
should not be used anymore, use .then
instead:
$http.get('/url', config).then(successCallback, errorCallback);
HTML-encoding lost when attribute read from input field
Good answer. Note that if the value to encode is undefined
or null
with jQuery 1.4.2 you might get errors such as:
jQuery("<div/>").text(value).html is not a function
OR
Uncaught TypeError: Object has no method 'html'
The solution is to modify the function to check for an actual value:
function htmlEncode(value){
if (value) {
return jQuery('<div/>').text(value).html();
} else {
return '';
}
}
Celery Received unregistered task of type (run example)
Whether you use CELERY_IMPORTS
or autodiscover_tasks
, the important point is the tasks are able to be found and the name of the tasks registered in Celery should match the names the workers try to fetch.
When you launch the Celery, say celery worker -A project --loglevel=DEBUG
, you should see the name of the tasks. For example, if I have a debug_task
task in my celery.py
.
[tasks]
. project.celery.debug_task
. celery.backend_cleanup
. celery.chain
. celery.chord
. celery.chord_unlock
. celery.chunks
. celery.group
. celery.map
. celery.starmap
If you can't see your tasks in the list, please check your celery configuration imports the tasks correctly, either in --setting
, --config
, celeryconfig
or config_from_object
.
If you are using celery beat, make sure the task name, task
, you use in CELERYBEAT_SCHEDULE
matches the name in the celery task list.
TypeError: 'NoneType' object is not iterable in Python
Explanation of error: 'NoneType' object is not iterable
In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:
>>> print(type(None)) #Python2
<type 'NoneType'> #In Python2 the type of None is the 'NoneType' type.
>>> print(type(None)) #Python3
<class 'NoneType'> #In Python3, the type of None is the 'NoneType' class.
Iterating over a variable that has value None fails:
for a in None:
print("k") #TypeError: 'NoneType' object is not iterable
Python methods return NoneType if they don't return a value:
def foo():
print("k")
a, b = foo() #TypeError: 'NoneType' object is not iterable
You need to check your looping constructs for NoneType like this:
a = None
print(a is None) #prints True
print(a is not None) #prints False
print(a == None) #prints True
print(a != None) #prints False
print(isinstance(a, object)) #prints True
print(isinstance(a, str)) #prints False
Guido says only use is
to check for None
because is
is more robust to identity checking. Don't use equality operations because those can spit bubble-up implementationitis of their own. Python's Coding Style Guidelines - PEP-008
NoneTypes are Sneaky, and can sneak in from lambdas:
import sys
b = lambda x : sys.stdout.write("k")
for a in b(10):
pass #TypeError: 'NoneType' object is not iterable
NoneType is not a valid keyword:
a = NoneType #NameError: name 'NoneType' is not defined
Concatenation of None
and a string:
bar = "something"
foo = None
print foo + bar #TypeError: cannot concatenate 'str' and 'NoneType' objects
What's going on here?
Python's interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__
method on the None.
None has no __iter__
method defined, so Python's virtual machine tells you what it sees: that NoneType has no __iter__
method.
This is why Python's duck-typing ideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.
Java or C++ doesn't have these problems because such a program wouldn't be allowed to compile since you haven't defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.
How can I pass POST parameters in a URL?
You can make a link perform an Ajax post request when it's clicked.
In jQuery:
$('a').click(function(e) {
var $this = $(this);
e.preventDefault();
$.post('url', {'user': 'something', 'foo': 'bar'}, function() {
window.location = $this.attr('href');
});
});
You could also make the link submit a POST form with JavaScript:
<form action="url" method="post">
<input type="hidden" name="user" value="something" />
<a href="#">CLick</a>
</form>
<script>
$('a').click(function(e) {
e.preventDefault();
$(this).parents('form').submit();
});
</script>
How do I fix a Git detached head?
A solution without creating a temporary branch.
How to exit (“fix”) detached HEAD state when you already changed something in this mode and, optionally, want to save your changes:
Commit changes you want to keep. If you want to take over any of the changes you made in detached HEAD state, commit them. Like:
git commit -a -m "your commit message"
Discard changes you do not want to keep. The hard reset will discard any uncommitted changes that you made in detached HEAD state:
git reset --hard
(Without this, step 3 would fail, complaining about modified uncommitted files in the detached HEAD.)
Check out your branch. Exit detached HEAD state by checking out the branch you worked on before, for example:
git checkout master
Take over your commits. You can now take over the commits you made in detached HEAD state by cherry-picking, as shown in my answer to another question.
git reflog
git cherry-pick <hash1> <hash2> <hash3> …
Can I add jars to maven 2 build classpath without installing them?
After having really long discussion with CloudBees guys about properly maven packaging of such kind of JARs, they made an interesting good proposal for a solution:
Creation of a fake Maven project which attaches a pre-existing JAR as a primary artifact, running into belonged POM install:install-file execution. Here is an example of such kinf of POM:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<id>image-util-id</id>
<phase>install</phase>
<goals>
<goal>install-file</goal>
</goals>
<configuration>
<file>${basedir}/file-you-want-to-include.jar</file>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<packaging>jar</packaging>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
But in order to implement it, existing project structure should be changed. First, you should have in mind that for each such kind of JAR there should be created different fake Maven project (module). And there should be created a parent Maven project including all sub-modules which are : all JAR wrappers and existing main project. The structure could be :
root project (this contains the parent POM file includes all sub-modules with module XML element) (POM packaging)
JAR 1 wrapper Maven child project (POM packaging)
JAR 2 wrapper Maven child project (POM packaging)
main existing Maven child project (WAR, JAR, EAR .... packaging)
When parent running via mvn:install or mvn:packaging is forced and sub-modules will be executed. That could be concerned as a minus here, since project structure should be changed, but offers a non static solution at the end
What is the difference between GitHub and gist?
GISTS
The Gist is an outstanding service provided by GitHub. Using this service, you can share your work publically or privately. You can share a single file, articles, full applications or source code etc.
The GitHub is much more than just Gists. It provides immense services to group together a project or programs digital resources in a centralized location called repository and share among stakeholder. The GitHub repository will hold or maintain the multiple version of the files or history of changes and you can retrieve a specific version of a file when you want. Whereas gist will create each post as a new repository and will maintain the history of the file.
Implement an input with a mask
I wrote a similar solution some time ago.
Of course it's just a PoC and can be improved further.
This solution covers the following features:
- Seamless character input
- Pattern customization
- Live validation while you typing
- Full date validation (including correct days in each month and a leap year consideration)
- Descriptive errors, so the user will understand what is going on while he is unable to type a character
- Fix cursor position and prevent selections
- Show placeholder if the value is empty
_x000D_
_x000D_
const pattern = "__/__/____";_x000D_
const patternFreeChar = "_";_x000D_
const validDate = [_x000D_
/^[0-3]$/,_x000D_
/^(0[1-9]|[12]\d|3[01])$/,_x000D_
/^(0[1-9]|[12]\d|3[01])[01]$/,_x000D_
/^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)$/,_x000D_
/^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)[12]$/,_x000D_
/^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)(19|20)/_x000D_
]_x000D_
_x000D_
/**_x000D_
* Validate a date as your type._x000D_
* @param {string} date The date in format DDMMYYYY as a string representation._x000D_
* @throws {Error} When the date is invalid._x000D_
*/_x000D_
function validateStartTypingDate(date) {_x000D_
if ( !date ) return "";_x000D_
_x000D_
date = date.substr(0, 8);_x000D_
_x000D_
if ( !/^\d+$/.test(date) )_x000D_
throw new Error("Please type numbers only");_x000D_
_x000D_
if ( !validDate[Math.min(date.length-1,validDate.length-1)].test(date) ) {_x000D_
let errMsg = "";_x000D_
switch ( date.length ) {_x000D_
case 1:_x000D_
throw new Error("Day in month can start only with 0, 1, 2 or 3");_x000D_
_x000D_
case 2:_x000D_
throw new Error("Day in month must be in a range between 01 and 31");_x000D_
_x000D_
case 3:_x000D_
throw new Error("Month can start only with 0 or 1");_x000D_
_x000D_
case 4: {_x000D_
const day = parseInt(date.substr(0,2));_x000D_
const month = parseInt(date.substr(2,2));_x000D_
const monthName = new Date(0,month-1).toLocaleString('en-us',{month:'long'});_x000D_
_x000D_
if ( month < 1 || month > 12 )_x000D_
throw new Error("Month number must be in a range between 01 and 12");_x000D_
_x000D_
if ( day > 30 && [4,6,9,11].includes(month) )_x000D_
throw new Error(`${monthName} have maximum 30 days`);_x000D_
_x000D_
if ( day > 29 && month === 2 )_x000D_
throw new Error(`${monthName} have maximum 29 days`);_x000D_
break; _x000D_
}_x000D_
_x000D_
case 5:_x000D_
case 6:_x000D_
throw new Error("We support only years between 1900 and 2099, so the full year can start only with 19 or 20");_x000D_
}_x000D_
}_x000D_
_x000D_
if ( date.length === 8 ) {_x000D_
const day = parseInt(date.substr(0,2));_x000D_
const month = parseInt(date.substr(2,2));_x000D_
const year = parseInt(date.substr(4,4));_x000D_
const monthName = new Date(0,month-1).toLocaleString('en-us',{month:'long'});_x000D_
if ( !isLeap(year) && month === 2 && day === 29 )_x000D_
throw new Error(`The year you are trying to enter (${year}) is not a leap year. Thus, in this year, ${monthName} can have maximum 28 days`);_x000D_
}_x000D_
_x000D_
return date;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Check whether the given year is a leap year._x000D_
*/_x000D_
function isLeap(year) {_x000D_
return new Date(year, 1, 29).getDate() === 29;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Move cursor to the end of the provided input element._x000D_
*/_x000D_
function moveCursorToEnd(el) {_x000D_
if (typeof el.selectionStart == "number") {_x000D_
el.selectionStart = el.selectionEnd = el.value.length;_x000D_
} else if (typeof el.createTextRange != "undefined") {_x000D_
el.focus();_x000D_
var range = el.createTextRange();_x000D_
range.collapse(false);_x000D_
range.select();_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Move cursor to the end of the self input element._x000D_
*/_x000D_
function selfMoveCursorToEnd() {_x000D_
return moveCursorToEnd(this);_x000D_
}_x000D_
_x000D_
const input = document.querySelector("input")_x000D_
_x000D_
input.addEventListener("keydown", function(event){_x000D_
event.preventDefault();_x000D_
document.getElementById("date-error-msg").innerText = "";_x000D_
_x000D_
// On digit pressed_x000D_
let inputMemory = this.dataset.inputMemory || "";_x000D_
_x000D_
if ( event.key.length === 1 ) {_x000D_
try {_x000D_
inputMemory = validateStartTypingDate(inputMemory + event.key);_x000D_
} catch (err) {_x000D_
document.getElementById("date-error-msg").innerText = err.message;_x000D_
}_x000D_
}_x000D_
_x000D_
// On backspace pressed_x000D_
if ( event.code === "Backspace" ) {_x000D_
inputMemory = inputMemory.slice(0, -1);_x000D_
}_x000D_
_x000D_
// Build an output using a pattern_x000D_
if ( this.dataset.inputMemory !== inputMemory ) {_x000D_
let output = pattern;_x000D_
for ( let i=0, digit; i<inputMemory.length, digit=inputMemory[i]; i++ ) {_x000D_
output = output.replace(patternFreeChar, digit);_x000D_
}_x000D_
this.dataset.inputMemory = inputMemory;_x000D_
this.value = output;_x000D_
}_x000D_
_x000D_
// Clean the value if the memory is empty_x000D_
if ( inputMemory === "" ) {_x000D_
this.value = "";_x000D_
}_x000D_
}, false);_x000D_
_x000D_
input.addEventListener('select', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('mousedown', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('mouseup', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('click', selfMoveCursorToEnd, false);
_x000D_
<input type="text" placeholder="DD/MM/YYYY" />_x000D_
<div id="date-error-msg"></div>
_x000D_
_x000D_
_x000D_
A link to jsfiddle:
https://jsfiddle.net/d1xbpw8f/56/
Good luck!
How to get Enum Value from index in Java?
Here's three ways to do it.
public enum Months {
JAN(1), FEB(2), MAR(3), APR(4), MAY(5), JUN(6), JUL(7), AUG(8), SEP(9), OCT(10), NOV(11), DEC(12);
int monthOrdinal = 0;
Months(int ord) {
this.monthOrdinal = ord;
}
public static Months byOrdinal2ndWay(int ord) {
return Months.values()[ord-1]; // less safe
}
public static Months byOrdinal(int ord) {
for (Months m : Months.values()) {
if (m.monthOrdinal == ord) {
return m;
}
}
return null;
}
public static Months[] MONTHS_INDEXED = new Months[] { null, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };
}
import static junit.framework.Assert.assertEquals;
import org.junit.Test;
public class MonthsTest {
@Test
public void test_indexed_access() {
assertEquals(Months.MONTHS_INDEXED[1], Months.JAN);
assertEquals(Months.MONTHS_INDEXED[2], Months.FEB);
assertEquals(Months.byOrdinal(1), Months.JAN);
assertEquals(Months.byOrdinal(2), Months.FEB);
assertEquals(Months.byOrdinal2ndWay(1), Months.JAN);
assertEquals(Months.byOrdinal2ndWay(2), Months.FEB);
}
}
Maven Jacoco Configuration - Exclude classes/packages from report not working
Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs
<configuration>
<excludes>
<exclude>**/*Config.*</exclude>
<exclude>**/*Dev.*</exclude>
</excludes>
</configuration>
The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax
* Match zero or more characters
** Match zero or more directories
? Match a single character
You may also exclude a package and all of its children/subpackages this way:
<exclude>some/package/**/*</exclude>
This will exclude every class in some.package
, as well as any children. For example, some.package.child
wouldn't be included in the reports either.
I have tested and my report goal reports on a reduced number of classes using the above.
If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings
Settings > General Settings > Exclusions > Code Coverage
Sonar Docs explains it a bit more
Running your command above
mvn clean verify
Will show the classes have been excluded
No exclusions
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes
With exclusions
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes
Hope this helps
How can I join multiple SQL tables using the IDs?
SELECT
a.nameA, /* TableA.nameA */
d.nameD /* TableD.nameD */
FROM TableA a
INNER JOIN TableB b on b.aID = a.aID
INNER JOIN TableC c on c.cID = b.cID
INNER JOIN TableD d on d.dID = a.dID
WHERE DATE(c.`date`) = CURDATE()
How to escape the equals sign in properties files
This method should help to programmatically generate values guaranteed to be 100% compatible with .properties
files:
public static String escapePropertyValue(final String value) {
if (value == null) {
return null;
}
try (final StringWriter writer = new StringWriter()) {
final Properties properties = new Properties();
properties.put("escaped", value);
properties.store(writer, null);
writer.flush();
final String stringifiedProperties = writer.toString();
final Pattern pattern = Pattern.compile("(.*?)escaped=(.*?)" + Pattern.quote(System.lineSeparator()) + "*");
final Matcher matcher = pattern.matcher(stringifiedProperties);
if (matcher.find() && matcher.groupCount() <= 2) {
return matcher.group(matcher.groupCount());
}
// This should never happen unless the internal implementation of Properties::store changed
throw new IllegalStateException("Could not escape property value");
} catch (final IOException ex) {
// This should never happen. IOException is only because the interface demands it
throw new IllegalStateException("Could not escape property value", ex);
}
}
You can call it like this:
final String escapedPath = escapePropertyValue("C:\\Users\\X");
writeToFile(escapedPath); // will pass "C\\:\\\\Users\\\\X"
This method a little bit expensive but, writing properties to a file is typically an sporadic operation anyway.
Get a list of dates between two dates using a function
A Bit late to the party, but I like this solution quite a bit.
CREATE FUNCTION ExplodeDates(@startDate DateTime, @endDate DateTime)
RETURNS table as
return (
SELECT TOP (DATEDIFF(DAY, @startDate, @endDate) + 1)
DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @startDate) AS DATE
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
)
What is the naming convention in Python for variable and function names?
As the Style Guide for Python Code admits,
The naming conventions of Python's
library are a bit of a mess, so we'll
never get this completely consistent
Note that this refers just to Python's standard library. If they can't get that consistent, then there hardly is much hope of having a generally-adhered-to convention for all Python code, is there?
From that, and the discussion here, I would deduce that it's not a horrible sin if one keeps using e.g. Java's or C#'s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, internal consistency matters most.
Feel free to dismiss me as a heretic. :-) Like the OP, I'm not a "Pythonista", not yet anyway.
Simple jQuery, PHP and JSONP example?
To make the server respond with a valid JSONP array, wrap the JSON in brackets ()
and preprend the callback
:
echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";
Using json_encode() will convert a native PHP array into JSON:
$array = array(
'fullname' => 'Jeff Hansen',
'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";
How do I import modules or install extensions in PostgreSQL 9.1+?
How to download and install if you have SUSE. As an example I am downloading the tablefunc module so I can use crosstab. I have PostgreSQL 9.6.1.
right-click desktop, terminal, type:
sudo zypper in postgreql-contrib
Enter credentials, continue by typing:
y
Run query (I ran mine from pgAdminIII):
CREATE EXTENSION tablefunc;
You should now have the crosstab
function.
I did not have to restart.
How to change root logging level programmatically for logback
Try this:
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);
Note that you can also tell logback to periodically scan your config file like this:
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>
How to change Oracle default data pump directory to import dumpfile?
use DIRECTORY option.
Documentation here:
http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907
DIRECTORY
Default: DATA_PUMP_DIR
Purpose
Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.
Syntax and Description
DIRECTORY=directory_object
The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.
A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.
Example
The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".
> impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp
LOGFILE=dpump_dir2:expfull.log
This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.
jQuery: How to capture the TAB keypress within a Textbox
Edit: Since your element is dynamically inserted, you have to use delegated on()
as in your example, but you should bind it to the keydown event, because as @Marc comments, in IE the keypress event doesn't capture non-character keys:
$("#parentOfTextbox").on('keydown', '#textbox', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
// call custom function here
}
});
Check an example here.
Does Django scale?
What's the "largest" site that's built on Django today? (I measure size mostly by user traffic)
In the US, it was Mahalo. I'm told they handle roughly 10 million uniques a month. Now, in 2019, Mahalo is powered by Ruby on Rails.
Abroad, the Globo network (a network of news, sports, and entertainment sites in Brazil); Alexa ranks them in to top 100 globally (around 80th currently).
Other notable Django users include PBS, National Geographic, Discovery, NASA (actually a number of different divisions within NASA), and the Library of Congress.
Can Django deal with 100k users daily, each visiting the site for a couple of hours?
Yes -- but only if you've written your application right, and if you've got enough hardware. Django's not a magic bullet.
Could a site like StackOverflow run on Django?
Yes (but see above).
Technology-wise, easily: see soclone for one attempt. Traffic-wise, compete pegs StackOverflow at under 1 million uniques per month. I can name at least dozen Django sites with more traffic than SO.
How to get array keys in Javascript?
You need to call the hasOwnProperty
function to check whether the property is actually defined on the object itself (as opposed to its prototype), like this:
for (var key in widthRange) {
if (key === 'length' || !widthRange.hasOwnProperty(key)) continue;
var value = widthRange[key];
}
Note that you need a separate check for length
.
However, you shouldn't be using an array here at all; you should use a regular object. All Javascript objects function as associative arrays.
For example:
var widthRange = { }; //Or new Object()
widthRange[46] = { sel:46, min:0, max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };
How does one represent the empty char?
There is no such thing as the "empty character" ''
.
If you need a space character, that can be represented as a space: c[i] = ' '
or as its ASCII octal equivalent: c[i] = '\040'
. If you need a NUL character that's c[i] = '\0'
.
How to pass Multiple Parameters from ajax call to MVC Controller
function final_submit1() {
var city = $("#city").val();
var airport = $("#airport").val();
var vehicle = $("#vehicle").val();
if(city && airport){
$.ajax({
type:"POST",
cache:false,
data:{"city": city,"airport": airport},
url:'http://airportLimo/ajax-car-list',
success: function (html) {
console.log(html);
//$('#add').val('data sent');
//$('#msg').html(html);
$('#pprice').html("Price: $"+html);
}
});
}
}
Delete all data in SQL Server database
First you'll have to disable all the triggers :
sp_msforeachtable 'ALTER TABLE ? DISABLE TRIGGER all';
Run this script : (Taken from this post Thank you @SQLMenace)
SET NOCOUNT ON
GO
SELECT 'USE [' + db_name() +']';
;WITH a AS
(
SELECT 0 AS lvl,
t.object_id AS tblID
FROM sys.TABLES t
WHERE t.is_ms_shipped = 0
AND t.object_id NOT IN (SELECT f.referenced_object_id
FROM sys.foreign_keys f)
UNION ALL
SELECT a.lvl + 1 AS lvl,
f.referenced_object_id AS tblId
FROM a
INNER JOIN sys.foreign_keys f ON a.tblId = f.parent_object_id
AND a.tblID <> f.referenced_object_id
)
SELECT
'Delete from ['+ object_schema_name(tblID) + '].[' + object_name(tblId) + ']'
FROM a
GROUP BY tblId
ORDER BY MAX(lvl),1
This script will produce DELETE
statements in proper order. starting from referenced tables then referencing ones
Copy the DELETE FROM
statements and run them once
enable triggers
sp_msforeachtable 'ALTER TABLE ? ENABLE TRIGGER all'
Commit the changes :
begin transaction
commit;
Creating a dynamic choice field
You can declare the field as a first-class attribute of your form and just set choices dynamically:
class WaypointForm(forms.Form):
waypoints = forms.ChoiceField(choices=[])
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
self.fields['waypoints'].choices = waypoint_choices
You can also use a ModelChoiceField and set the queryset on init in a similar manner.
How do I mock a static method that returns void with PowerMock?
You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources
will throw the exception :
// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception
Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.
By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.
Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.
Hope that helps.
Regards
Changing the child element's CSS when the parent is hovered
If you're using Twitter Bootstrap styling and base JS for a drop down menu:
.child{ display:none; }
.parent:hover .child{ display:block; }
This is the missing piece to create sticky-dropdowns (that aren't annoying)
- The behavior is to:
- Stay open when clicked, close when clicking again anywhere else on the page
- Close automatically when the mouse scrolls out of the menu's elements.
How to convert an array into an object using stdClass()
The quick and dirty way is using json_encode
and json_decode
which will turn the entire array (including sub elements) into an object.
$clasa = json_decode(json_encode($clasa)); //Turn it into an object
The same can be used to convert an object into an array. Simply add , true
to json_decode
to return an associated array:
$clasa = json_decode(json_encode($clasa), true); //Turn it into an array
An alternate way (without being dirty) is simply a recursive function:
function convertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = convertToObject($value);
}
$object->$key = $value;
}
return $object;
}
or in full code:
<?php
function convertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = convertToObject($value);
}
$object->$key = $value;
}
return $object;
}
$clasa = array(
'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);
$obj = convertToObject($clasa);
print_r($obj);
?>
which outputs (note that there's no arrays - only stdClass
's):
stdClass Object
(
[e1] => stdClass Object
(
[nume] => Nitu
[prenume] => Andrei
[sex] => m
[varsta] => 23
)
[e2] => stdClass Object
(
[nume] => Nae
[prenume] => Ionel
[sex] => m
[varsta] => 27
)
[e3] => stdClass Object
(
[nume] => Noman
[prenume] => Alice
[sex] => f
[varsta] => 22
)
[e4] => stdClass Object
(
[nume] => Geangos
[prenume] => Bogdan
[sex] => m
[varsta] => 23
)
[e5] => stdClass Object
(
[nume] => Vasile
[prenume] => Mihai
[sex] => m
[varsta] => 25
)
)
So you'd refer to it by $obj->e5->nume
.
DEMO
Plot different DataFrames in the same figure
Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupby
and unstack
ing:
(Assuming you have this in dataframe, with datetime index already)
In [1]: df
Out[1]:
value
datetime
2010-01-01 1
2010-02-01 1
2009-01-01 1
# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)
In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
value
Year 2009 2010
Month
1 1 1
2 NaN 1
Now it's easy to plot (each year as a separate line):
df.groupby(['Month','Year']).mean().unstack().plot()
Efficient iteration with index in Scala
There's nothing in the stdlib that will do it for you without creating tuple garbage, but it's not too hard to write your own. Unfortunately I've never bothered to figure out how to do the proper CanBuildFrom implicit raindance to make such things generic in the type of collection they're applied to, but if it's possible, I'm sure someone will enlighten us. :)
def foreachWithIndex[A](as: Traversable[A])(f: (Int,A) => Unit) {
var i = 0
for (a <- as) {
f(i, a)
i += 1
}
}
def mapWithIndex[A,B](in: List[A])(f: (Int,A) => B): List[B] = {
def mapWithIndex0(in: List[A], gotSoFar: List[B], i: Int): List[B] = {
in match {
case Nil => gotSoFar.reverse
case one :: more => mapWithIndex0(more, f(i, one) :: gotSoFar, i+1)
}
}
mapWithIndex0(in, Nil, 0)
}
// Tests....
@Test
def testForeachWithIndex() {
var out = List[Int]()
ScalaUtils.foreachWithIndex(List(1,2,3,4)) { (i, num) =>
out :+= i * num
}
assertEquals(List(0,2,6,12),out)
}
@Test
def testMapWithIndex() {
val out = ScalaUtils.mapWithIndex(List(4,3,2,1)) { (i, num) =>
i * num
}
assertEquals(List(0,3,4,3),out)
}
"Cross origin requests are only supported for HTTP." error when loading a local file
If you insist on running the .html
file locally and not serving it with a webserver, you can prevent those cross origin requests from happening in the first place by making the problematic resources available inline.
I had this problem when trying to to serve .js
files through file://
. My solution was to update my build script to replace <script src="...">
tags with <script>...</script>
.
Here's a gulp
approach for doing that:
1.
run npm install --save-dev
to packages gulp
, gulp-inline
and del
.
2.
After creating a gulpfile.js
to the root directory, add the following code (just change the file paths for whatever suits you):
let gulp = require('gulp');
let inline = require('gulp-inline');
let del = require('del');
gulp.task('inline', function (done) {
gulp.src('dist/index.html')
.pipe(inline({
base: 'dist/',
disabledTypes: 'css, svg, img'
}))
.pipe(gulp.dest('dist/').on('finish', function(){
done()
}));
});
gulp.task('clean', function (done) {
del(['dist/*.js'])
done()
});
gulp.task('bundle-for-local', gulp.series('inline', 'clean'))
- Either run
gulp bundle-for-local
or update your build script to run it automatically.
You can see the detailed problem and solution for my case here.
How to completely DISABLE any MOUSE CLICK
To disable all mouse click
var event = $(document).click(function(e) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
// disable right click
$(document).bind('contextmenu', function(e) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
to enable it again:
$(document).unbind('click');
$(document).unbind('contextmenu');
Parsing Query String in node.js
Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:
// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');
// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';
// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
// Parse the request URL. Relative URLs require an origin explicitly.
const url = new URL(request.url, serverOrigin);
// Parse the URL query. The leading '?' has to be removed before this.
const query = parseQuery(url.search.substr(1));
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(`Hello, ${query.name}!\n`);
});
// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);
// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);
If you run the script above, you can test the server response like this, for example:
curl -q http://localhost:8000/status?name=ryan
Hello, ryan!
Enable & Disable a Div and its elements in Javascript
The following selects all descendant elements and disables them:
$("#dcacl").find("*").prop("disabled", true);
But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:
$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);
To re-enable you just set "disabled" to false.
I want to Disable them at loading the page and then by a click i can enable them
OK, so put the above code in a document ready handler, and setup an appropriate click handler:
$(document).ready(function() {
var $dcac1kids = $("#dcac1").find(":input");
$dcac1kids.prop("disabled",true);
// not sure what you want to click on to re-enable
$("selector for whatever you want to click").one("click",function() {
$dcac1kids.prop("disabled",false);
}
}
I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one()
since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one()
to .click()
if appropriate.