MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw
and cygwin fork
package.
To install the MinGW-w64 toolchain (Reference):
pacman -Sy pacman
to update the package databasepacman -Syu
to update the package database and core system packagespacman -Su
to update the restpacman -S mingw-w64-i686-toolchain
pacman -S mingw-w64-x86_64-toolchain
make
, run pacman -S make
In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.
This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:
) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:
. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.
$( '#iframe' ).attr( 'src', function ( i, val ) { return val; });
Try purge
sudo aptitude purge phpmyadmin
Not sure this works with plain old apt-get
though
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
To sort by cpu usage: top -o cpu
I think your issue is the line:**
sp.DataReceived += port_OnReceiveDatazz;
Shouldn't it be:
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).
I've also seen suggestions that you should turn the following options on for your serial port:
sp.DtrEnable = true; // Data-terminal-ready
sp.RtsEnable = true; // Request-to-send
You may also have to set the handshake to RequestToSend (via the handshake enumeration).
UPDATE:
Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?
So instead of this:
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();
Do this:
sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
Let me know how that goes.
They are format specifiers. They are used when you want to include the value of your Python expressions into strings, with a specific format enforced.
See Dive into Python for a relatively detailed introduction.
Install pip:
apt-get install pip
For acess MySQL from Python, install:
pip3 install mysqlclient
This is complex solution for this task.
(function($){_x000D_
if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {_x000D_
$('input, select').on('change focus', function (e) {_x000D_
setTimeout(function () {_x000D_
$.each(_x000D_
document.querySelectorAll('*:-webkit-autofill'),_x000D_
function () {_x000D_
var clone = $(this).clone(true, true);_x000D_
$(this).after(clone).remove();_x000D_
updateActions();_x000D_
})_x000D_
}, 300)_x000D_
}).change();_x000D_
}_x000D_
var updateActions = function(){};// method for update input actions_x000D_
updateActions(); // start on load and on rebuild_x000D_
})(jQuery)
_x000D_
*:-webkit-autofill,_x000D_
*:-webkit-autofill:hover,_x000D_
*:-webkit-autofill:focus,_x000D_
*:-webkit-autofill:active {_x000D_
/* use animation hack, if you have hard styled input */_x000D_
transition: all 5000s ease-in-out 0s;_x000D_
transition-property: background-color, color;_x000D_
/* if input has one color, and didn't have bg-image use shadow */_x000D_
-webkit-box-shadow: 0 0 0 1000px #fff inset;_x000D_
/* text color */_x000D_
-webkit-text-fill-color: #fff;_x000D_
/* font weigth */_x000D_
font-weight: 300!important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" name="name" autocomplete="name"/>_x000D_
<input type="email" name="email" autocomplete="email"/>
_x000D_
Single line, and only calculating logs once. First convert to log-space, then take the 1-period diff.
np.diff(np.log(df.price))
In earlier versions of numpy:
np.log(df.price)).diff()
You can use different syntax to achieve different things. If it is windows authentication you want, you could try this:
sqlcmd /S /d -E
If you want to use SQL Server authentication you could try this:
sqlcmd /S /d -U -P
Definitions:
/S = the servername/instance name. Example: Pete's Laptop/SQLSERV
/d = the database name. Example: Botlek1
-E = Windows authentication.
-U = SQL Server authentication/user. Example: Pete
-P = password that belongs to the user. Example: 1234
Hope this helps!
This solution will give you the Network parameters. Check out this solution
Maybe you can try this: though please note - This pulls the column count, not the row count
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int count = reader.VisibleFieldCount;
Console.WriteLine(count);
}
}
Try this:
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:= _
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "Tempo"
End Sub
Or use a With
clause to avoid repeatedly calling out your object
Private Sub CreateSheet()
Dim ws As Worksheet
With ThisWorkbook
Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
ws.Name = "Tempo"
End With
End Sub
Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.
Sub CreateSheet()
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
End With
End Sub
Note: It also works for #if / #elif / #endif matching. The caret must be on the #.
Similar to brianegge's awk solution, here is the Perl equivalent:
ps | egrep 11383 | perl -lane 'print $F[3]'
-a
enables autosplit mode, which populates the @F
array with the column data.
Use -F,
if your data is comma-delimited, rather than space-delimited.
Field 3 is printed since Perl starts counting from 0 rather than 1
You can do this:
<div style="text-align: center">
<a href="contact.html" class="button large hpbottom">Get Started</a>
</div>
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
let screenSize: CGRect = UIScreen.main.bounds
Postgres hasn't implemented an equivalent to INSERT OR REPLACE
. From the ON CONFLICT
docs (emphasis mine):
It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE
applies more generally, since it lets you set new values based on preexisting data. For example:
INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;
Just using this will add "mynewclass" to the element with the id myElement and revert it on the next call.
<div id="showhide" class="meta-info" onclick="changeclass(this);">
function changeclass(element) {
$(element).toggleClass('mynewclass');
}
Or for a slighly more jQuery way (you would run this after the DOM is loaded)
<div id="showhide" class="meta-info">
$('#showhide').click(function() {
$(this).toggleClass('mynewclass');
});
See a working example of this here: http://jsfiddle.net/S76WN/
dispatch_barrier_async is the better way, while not blocking current thread.
dispatch_barrier_async(accessQueue, { dictionary[object.ID] = object })
This is a standard problem.
Note that MySQL allows you to omit columns from the GROUP BY clause, which Standard SQL does not, but you do not get deterministic results in general when you use the MySQL facility.
SELECT *
FROM Messages AS M
JOIN (SELECT To_ID, From_ID, MAX(TimeStamp) AS Most_Recent
FROM Messages
WHERE To_ID = 12345678
GROUP BY From_ID
) AS R
ON R.To_ID = M.To_ID AND R.From_ID = M.From_ID AND R.Most_Recent = M.TimeStamp
WHERE M.To_ID = 12345678
I've added a filter on the To_ID
to match what you're likely to have. The query will work without it, but will return a lot more data in general. The condition should not need to be stated in both the nested query and the outer query (the optimizer should push the condition down automatically), but it can do no harm to repeat the condition as shown.
TL;DR
In several occasions, I've solved this kind of errors by just closing my terminal session and opening a new one before retrying the failing command.
Long explanation
In some SOs (such as MacOS) there is already a pre-installed, system-wide version of ruby. If you are using a version manager, such as rbenv
or asdf
, they work by playing with the environment of your current session so that the relevant commands point to the binaries installed by the version manager.
When installing a new binary, the version manager installs it in a special location, usually somewhere under the user's home directory. It then configures everything in your PATH
so that you get the freshly installed binaries when you issue a command, instead of the ones that came with your system. However, if you don't restart the session (there are other ways of getting your environment updated, but that's the easiest one) you don't get the new configuration and you will be using the original installation.
You can await on Promise.all()
:
await Promise.all([someCall(), anotherCall()]);
To store the results:
let [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]);
Note that Promise.all
fails fast, which means that as soon as one of the promises supplied to it rejects, then the entire thing rejects.
const happy = (v, ms) => new Promise((resolve) => setTimeout(() => resolve(v), ms))
const sad = (v, ms) => new Promise((_, reject) => setTimeout(() => reject(v), ms))
Promise.all([happy('happy', 100), sad('sad', 50)])
.then(console.log).catch(console.log) // 'sad'
_x000D_
If, instead, you want to wait for all the promises to either fulfill or reject, then you can use Promise.allSettled
. Note that Internet Explorer does not natively support this method.
const happy = (v, ms) => new Promise((resolve) => setTimeout(() => resolve(v), ms))
const sad = (v, ms) => new Promise((_, reject) => setTimeout(() => reject(v), ms))
Promise.allSettled([happy('happy', 100), sad('sad', 50)])
.then(console.log) // [{ "status":"fulfilled", "value":"happy" }, { "status":"rejected", "reason":"sad" }]
_x000D_
Note: If you use
Promise.all
actions that managed to finish before rejection happen are not rolled back, so you may need to take care of such situation. For example if you have 5 actions, 4 quick, 1 slow and slow rejects. Those 4 actions may be already executed so you may need to roll back. In such situation consider usingPromise.allSettled
while it will provide exact detail which action failed and which not.
If it's inside, then you'll gain the overhead of the try/catch structure N times, as opposed to just the once on the outside.
Every time a Try/Catch structure is called it adds overhead to the execution of the method. Just the little bit of memory & processor ticks needed to deal with the structure. If you're running a loop 100 times, and for hypothetical sake, let's say the cost is 1 tick per try/catch call, then having the Try/Catch inside the loop costs you 100 ticks, as opposed to only 1 tick if it's outside of the loop.
Sure you can use isinstance
, but be aware that this is not how Python works. Python is a duck typed language. You should not explicitly check your types. A TypeError
will be raised if the incorrect type was passed.
So just assume it is an int
. Don't bother checking.
If you are using bootstrap then the below solution will work.
<div>
<button type="submit" class="btn btn-primary" >Invoke User Endpoint</button>
<button type="submit" class="btn btn-primary ml-3">Invoke Hello Endpoint</button>
</div>
_x000D_
Expression you are looking for may be:
...
return any( isinstance(e, list) for e in my_list )
Testing:
>>> my_list = [1,2]
>>> any( isinstance(e, list) for e in my_list )
False
>>> my_list = [1,2, [3,4,5]]
>>> any( isinstance(e, list) for e in my_list )
True
>>>
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
This is a known bug in Android 4 to 4.4(KitKat) and is resolved in ">4.4"
See here: https://code.google.com/p/android/issues/detail?id=71936
Swift 3
For a simple solution without third party code:
Just use a normal UIAlertController but with style = actionSheet (look at code down below)
let alertDisapperTimeInSeconds = 2.0
let alert = UIAlertController(title: nil, message: "Toast!", preferredStyle: .actionSheet)
self.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + alertDisapperTimeInSeconds) {
alert.dismiss(animated: true)
}
The advantage of this solution:
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
Backup
..PLAIN
for Format USE INSERT COMMANDS
Use Column Inserts
if you want column names in your inserts.Backup
button1)
$stateProvider
.state('app.example1', {
url: '/example',
views: {
'menuContent': {
templateUrl: 'templates/example.html',
controller: 'ExampleCtrl'
}
}
})
.state('app.example2', {
url: '/example2/:object',
views: {
'menuContent': {
templateUrl: 'templates/example2.html',
controller: 'Example2Ctrl'
}
}
})
2)
.controller('ExampleCtrl', function ($state, $scope, UserService) {
$scope.goExample2 = function (obj) {
$state.go("app.example2", {object: JSON.stringify(obj)});
}
})
.controller('Example2Ctrl', function ($state, $scope, $stateParams) {
console.log(JSON.parse($state.params.object));
})
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
I have a similar problem importing those libs. I am using Anaconda Navigator 1.8.2 with Spyder 3.2.8.
My code is the following:
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math
#from tf.keras.models import Sequential # This does not work!
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import InputLayer, Input
from tensorflow.python.keras.layers import Reshape, MaxPooling2D
from tensorflow.python.keras.layers import Conv2D, Dense, Flatten
I get the following error:
from tensorflow.python.keras.models import Sequential
ModuleNotFoundError: No module named 'tensorflow.python.keras'
I solve this erasing tensorflow.python
With this code I solve the error:
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math
#from tf.keras.models import Sequential # This does not work!
from keras.models import Sequential
from keras.layers import InputLayer, Input
from keras.layers import Reshape, MaxPooling2D
from keras.layers import Conv2D, Dense, Flatten
Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.
this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();
They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.
As for your replacement, you haven't specified what language you're using, so here's the sketch:
someString.replace("\r\n", "\n").replace("\r", "\n")
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")
base directory + your filename
In my case when I browsed to site5.com I got the following error.
HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.
Most likely causes: A default document is not configured for the requested URL, and directory browsing is not enabled on the server.
And then when I browsed to
site5.com/home/index
I was met with
HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Most likely causes: The directory or file specified does not exist on the Web server. The URL contains a typographical error. A custom filter or module, such as URLScan, restricts access to the file.
All that I did is installed the feature in IIS ASP.NET 4.8 as shown below.
First, set customErrors = "Off" in the web.config and redeploy to get a more detailed error message that will help us diagnose the problem. You could also RDP into the instance and browse to the site from IIS locally to view the errors.
<system.web>
<customErrors mode="Off" />
First guess though - you have some references (most likely Azure SDK references) that are not set to Copy Local = true. So, all your dependencies are not getting deployed.
Get to the detailed error first and update your question.
UPDATE: A second option now available in VS2013 is Remote Debugging a Cloud Service or Virtual Machine.
I have Tried something Like this and it worked really fine with me
Socket Skt;
String host = "localhost";
int i = 8983; // port no.
try {
System.out.println("Looking for "+ i);
Skt = new Socket(host, i);
System.out.println("There is a Server on port "
+ i + " of " + host);
}
catch (UnknownHostException e) {
System.out.println("Exception occured"+ e);
}
catch (IOException e) {
System.out.println("port is not used");
}
I assume person_id
is the primary key of Person
table, so here's how you update a single record:
Person result = (from p in Context.Persons
where p.person_id == 5
select p).SingleOrDefault();
result.is_default = false;
Context.SaveChanges();
and here's how you update multiple records:
List<Person> results = (from p in Context.Persons
where .... // add where condition here
select p).ToList();
foreach (Person p in results)
{
p.is_default = false;
}
Context.SaveChanges();
[Try this solution it's simple] You can create a static variable in a Swift class then call it from any Objective-C class.
If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.
Comment.find_all_by_id([2, 3, 5])
will work even if some of the ids don't exist. This works in the
user.comments.find_all_by_id(potentially_nonexistent_ids)
case as well.
Comment.where(id: [2, 3, 5])
Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.
The title attribute is meant to give more information. It's not useful for SEO so it's never a good idea to have the same text in the title and alt which is meant to describe the image or input is vs. what it does. for instance:
<button title="prints out hello world">Sample Buttons</button>
<img title="Hms beagle in the straits of magellan" alt="HMS Beagle painting" src="hms-beagle.jpg" />
The title attribute will make a tool tip, but it will be controlled by the browser as far as where it shows up and what it looks like. If you want more control there are third party jQuery options, many css templates such as Bootstrap have built in solutions, and you can also write a simple css solution if you want. check out this w3schools solution.
Starting from 4.x the sort methods have been changed. If you are using >4.x. Try using any of the following.
Post.find({}).sort('-date').exec(function(err, docs) { ... });
Post.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Post.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Post.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });
The following code were written in ES6 and it will work in most of the browsers without an issue.
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];_x000D_
_x000D_
// Construct the comma seperated string_x000D_
// If a column values contains a comma then surround the column value by double quotes_x000D_
const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');_x000D_
_x000D_
// Format the CSV string_x000D_
const data = encodeURI('data:text/csv;charset=utf-8,' + csv);_x000D_
_x000D_
// Create a virtual Anchor tag_x000D_
const link = document.createElement('a');_x000D_
link.setAttribute('href', data);_x000D_
link.setAttribute('download', 'export.csv');_x000D_
_x000D_
// Append the Anchor tag in the actual web page or application_x000D_
document.body.appendChild(link);_x000D_
_x000D_
// Trigger the click event of the Anchor link_x000D_
link.click();_x000D_
_x000D_
// Remove the Anchor link form the web page or application_x000D_
document.body.removeChild(link);
_x000D_
Use \overset{above}{main}
in math mode. In your case, \overset{a}{\#}
.
You can add multiple only by code even if you have the second onclick
atribute in the html it gets ignored, and click2 triggered
never gets printed, you could add one on action the mousedown
but that is just an workaround.
So the best to do is add them by code as in:
var element = document.getElementById("multiple_onclicks");_x000D_
element.addEventListener("click", function(){console.log("click3 triggered")}, false);_x000D_
element.addEventListener("click", function(){console.log("click4 triggered")}, false);
_x000D_
<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");' > Click me</button>
_x000D_
You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.
Just to add on to the accepted answer and the comments.
var x = 12; //or whatever offset
var CurrentDate = new Date();
//For the very rare cases like the end of a month
//eg. May 30th - 3 months will give you March instead of February
var date = CurrentDate.getDate();
CurrentDate.setDate(1);
CurrentDate.setMonth(CurrentDate.getMonth()+X);
CurrentDate.setDate(date);
mvn-war-plugin 2.3 fixes this:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
</plugin>
...
You are probably having a problem with the sort of CSV file that you have.
Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.
You need something like this, maybe it can be improved. This is a first attempt:
...
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
...
@Configuration
...
@org.springframework.context.annotation.PropertySource("classpath:/config/default.properties")
...
public class GeneralApplicationConfiguration implements WebApplicationInitializer
{
@Autowired
Environment env;
public void someMethod() {
...
Map<String, Object> map = new HashMap();
for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
PropertySource propertySource = (PropertySource) it.next();
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
...
}
...
Basically, everything from the Environment that's a MapPropertySource
(and there are quite a lot of implementations) can be accessed as a Map
of properties.
npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
Your existing configuration can be updated automatically by running the following command:
ng update @angular/cli
or:
npm install
Or you can do that with ES6 template literal:
<a :href="`/job/${r.id}`"
String.equals("")
is actually a bit slower than just an isEmpty()
call. Strings store a count variable initialized in the constructor, since Strings are immutable.
isEmpty()
compares the count variable to 0, while equals will check the type, string length, and then iterate over the string for comparison if the sizes match.
So to answer your question, isEmpty()
will actually do a lot less! and that's a good thing.
You can also solve this problem via Apache configuration using mod_remoteip, by adding the following to a conf.d file:
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 172.16.0.0/12
LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
You can find a really good boilerplate made by Henrik Joreteg (ampersandjs) here: https://github.com/HenrikJoreteg/hjs-webpack
Then in your webpack.config.js
var getConfig = require('hjs-webpack')
module.exports = getConfig({
in: 'src/index.js',
out: 'public',
clearBeforeBuild: true,
https: process.argv.indexOf('--https') !== -1
})
As per official documentation link shared by Andre Kirpitch, Oracle 10g gives a maximum size of 4000 bytes or characters for varchar2. If you are using a higher version of oracle (for example Oracle 12c), you can get a maximum size upto 32767 bytes or characters for varchar2. To utilize the extended datatype feature of oracle 12, you need to start oracle in upgrade mode. Follow the below steps in command prompt:
1) Login as sysdba (sqlplus / as sysdba)
2) SHUTDOWN IMMEDIATE;
3) STARTUP UPGRADE;
4) ALTER SYSTEM SET max_string_size=extended;
5) Oracle\product\12.1.0.2\rdbms\admin\utl32k.sql
6) SHUTDOWN IMMEDIATE;
7) STARTUP;
If you're on Debian 8 (Jessie) Linux, try to cd
into the directory of the 'metropolises.sql'
. Run mysql
and execute SOURCE ./metropolises.sql;
Basically, try the relative path. I tried this and it works.
Here's a nice concise version:
set isX64=False && if /I "%PROCESSOR_ARCHITECTURE%"=="AMD64" ( set isX64=True ) else ( if /I "%PROCESSOR_ARCHITEW6432%"=="AMD64" ( set isX64=True ) )
echo %isX64%
Don't use the "Program Files (x86)" directory as evidence of anything: naughty software can easily create this directory on a 32-bit machine. Instead use the PROCESSOR_ARCHITECTURE and PROCESSOR_ARCHITEW6432 environment variables.
Just add text-align: center;
to your <ul>
. Problem solved.
Pass a selector to the jQuery parents function:
d.parents('.a').attr('id')
EDIT Hmm, actually Slaks's answer is superior if you only want the closest ancestor that matches your selector.
Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!
Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278
Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
Dim rw As Long, ref
With ThisWorkbook.Sheets(1)
.Cells.Clear
rw = 1
.Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
For Each ref In ThisWorkbook.VBProject.References
rw = rw + 1
.Range("A" & rw & ":D" & rw) = Array(ref.Description, _
"v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
Next ref
.Range("A:D").Columns.AutoFit
End With
End Sub
Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.
Sub ListReferencePaths()
'Macro purpose: To determine full path and Globally Unique Identifier (GUID)
'to each referenced library. Select the reference in the Tools\References
'window, then run this code to get the information on the reference's library
On Error Resume Next
Dim i As Long
Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID"
For i = 1 To ThisWorkbook.VBProject.References.Count
With ThisWorkbook.VBProject.References(i)
Debug.Print .Name & " | " & .FullPath & " | " & .GUID
End With
Next i
On Error GoTo 0
End Sub
RegexBuddy is telling me if you want to include it at the beginning, this is the correct syntax:
"(?i)\\b(\\w+)\\b(\\s+\\1)+\\b"
Sort the array into ascending order then assign a variable to the (n-1)th term.
Use .loc
for label based indexing:
df.loc[df.A==0, 'B'] = np.nan
The df.A==0
expression creates a boolean series that indexes the rows, 'B'
selects the column. You can also use this to transform a subset of a column, e.g.:
df.loc[df.A==0, 'B'] = df.loc[df.A==0, 'B'] / 2
I don't know enough about pandas internals to know exactly why that works, but the basic issue is that sometimes indexing into a DataFrame returns a copy of the result, and sometimes it returns a view on the original object. According to documentation here, this behavior depends on the underlying numpy behavior. I've found that accessing everything in one operation (rather than [one][two]) is more likely to work for setting.
Canonical Data in RDBMS, Graph Data;
Think as "Normalization" or "Normal form" of a data in a RDBMS. Same data exists in different tables, represented with a unique identifier and mapped it in different tables.
or
Think a single form of a data in Graph Database that represented in many triples.
Major benefit of it is to make Dml (Data manipulation) more efficient since you can upsert (insert/update) only one value instead of many.
Swift and Xcode 10+
#if DEBUG
will pass in ANY development/ad-hoc build, device or simulator. It's only false for App Store and TestFlight builds.
Example:
#if DEBUG
print("Not App Store build")
#else
print("App Store build")
#endif
you can use onMouseOver={this.onToggleOpen}
and onMouseOut={this.onToggleOpen}
to muse over and out on component
If you don't mind using NumPy, then:
In [319]: real = np.array([1234.5678])
In [327]: integ, deci = int(np.floor(real)), np.asscalar(real % 1)
In [328]: integ, deci
Out[328]: (1234, 0.5678000000000338)
You can use CSS to hide the button.
button {
visibility: hidden;
}
If your <button>
is just a clickable area on the image, why bother make it a button? You can use <map>
element instead.
You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i
to rate
and using that instead. See the updated code below:
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
# V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
for rate in growthRates:
# V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
fund = fund * (1 + 0.01 * rate) + depositPerYear
SavingsRecord += [fund,]
return SavingsRecord
print nestEgVariable(10000,10,[3,4,5,0,3])
I'd do this:
add the dependency as you like in your pom:
<dependency>
<groupId>com.stackoverflow...</groupId>
<artifactId>artifactId...</artifactId>
<version>1.0</version>
</dependency>
run mvn install
it will try to download the jar and fail. On the process, it
will give you the complete command of installing the jar with the error message. Copy that command and run it! easy huh?!
Setup:
My OS windows 8 64bit
Eclipse version Standard/SDK Kepler Service Release 2
My JDK is jdk-8u5-windows-i586
My JRE is jre-8u5-windows-i586
This how I overcome my error.
At the very first my Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
also didn't work.
Then I login to this website and downloaded the UCanAccess 2.0.8 zip (as Mr.Gord Thompson said) file and unzip it.
Then you will also able to find these *.jar files in that unzip folder:
ucanaccess-2.0.8.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.4.jar
Then what I did was I copied all these 5 files and paste them in these 2 locations:
C:\Program Files (x86)\eclipse\lib
C:\Program Files (x86)\eclipse\lib\ext
(I did that funny thing becoz I was unable to import these libraries to my project)
Then I reopen the eclipse with my project.then I see all that *.jar files in my project's JRE System Library folder.
Finally my code works.
public static void main(String[] args)
{
try
{
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\Hasith\\Documents\\JavaDatabase1.mdb");
Statement stment = conn.createStatement();
String qry = "SELECT * FROM Table1";
ResultSet rs = stment.executeQuery(qry);
while(rs.next())
{
String id = rs.getString("ID") ;
String fname = rs.getString("Nama");
System.out.println(id + fname);
}
}
catch(Exception err)
{
System.out.println(err);
}
//System.out.println("Hasith Sithila");
}
Problem in your SQL :
You can construct your sql like this :
$wpdb->prepare(
"INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ('$name', '$email', '$phone', '$country',
'$course', '$message', '$datesent')"
);
You can also use $wpdb->insert()
$wpdb->insert('table_name', input_array())
If you don't have too many files that have changed, this will leave you with no extra commits.
1. Duplicate branch temporarily
$ git checkout -b temp_branch
2. Reset to last wanted commit
$ git reset --hard HEAD~n
, where n
is the number of commits you need to go back
3. Checkout each file from original branch
$ git checkout origin/original_branch filename.ext
Now you can commit and force push (to overwrite remote), if needed.
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
<c:if test="${ansokanInfo.pSystem eq 'NAT'}">
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work? This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
how about just getting the length of char in your EditText and display it?
something along the line of
tv.setText(s.length() + " / " + String.valueOf(charCounts));
Here's a brief tutorial on how __doPostBack()
works.
To be honest, I don't use it much; at least directly. Many server controls, (e.g., Button
, LinkButton
, ImageButton
, parts of the GridView
, etc.) use __doPostBack
as their post back mechanism.
OAuth 2.0 signatures are not required for the actual API calls once the token has been generated. It has only one security token.
OAuth 1.0 requires client to send two security tokens for each API call, and use both to generate the signature. It requires the protected resources endpoints have access to the client credentials in order to validate the request.
Here describes the difference between OAuth 1.0 and 2.0 and how both work.
If you need rounded shadow. Works for swift 4.2
extension UIView {
func dropShadow() {
var shadowLayer: CAShapeLayer!
let cornerRadius: CGFloat = 16.0
let fillColor: UIColor = .white
if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
shadowLayer.fillColor = fillColor.cgColor
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: -2.0, height: 2.0)
shadowLayer.shadowOpacity = 0.8
shadowLayer.shadowRadius = 2
layer.insertSublayer(shadowLayer, at: 0)
}
}
}
The list is maintaining an object reference to the original value stored in the list. So when you execute this line:
Integer x = i.next();
Both x
and the list are storing a reference to the same object. However, when you execute:
x = Integer.valueOf(9);
nothing has changed in the list, but x
is now storing a reference to a different object. The list has not changed. You need to use some of the list manipulation methods, such as
list.set(index, Integer.valueof(9))
Note: this has nothing to do with the immutability of Integer
, as others are suggesting. This is just basic Java object reference behaviour.
Here's a complete example, to help explain the point. Note that this makes use of the ListIterator
class, which supports removing/setting items mid-iteration:
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List<Foo> fooList = new ArrayList<Foo>();
for (int i = 0; i < 9; i++)
fooList.add(new Foo(i, i));
// Standard iterator sufficient for altering elements
Iterator<Foo> iterator = fooList.iterator();
if (iterator.hasNext()) {
Foo foo = iterator.next();
foo.x = 99;
foo.y = 42;
}
printList(fooList);
// List iterator needed for replacing elements
ListIterator<Foo> listIterator = fooList.listIterator();
if (listIterator.hasNext()) {
// Need to call next, before set.
listIterator.next();
// Replace item returned from next()
listIterator.set(new Foo(99,99));
}
printList(fooList);
}
private static void printList(List<?> list) {
Iterator<?> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next());
}
System.out.println();
}
private static class Foo {
int x;
int y;
Foo(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("[%d, %d]", x, y);
}
}
}
This will print:
[99, 42][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
[99, 99][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
this.label1.BackColor = System.Drawing.Color.Transparent;
gets rid of the additional restrictions on the id attribute see here. The only requirements left (apart from being unique in the document) are:
ID should match:
[A-Za-z][-A-Za-z0-9_:.]*
-
(hyphen), _
(underscore), :
(colon) and .
(period)but one should avoid :
and .
beacause:
For example, an ID could be labelled "a.b:c" and referenced in the style sheet as #a.b:c but as well as being the id for the element, it could mean id "a", class "b", pseudo-selector "c". Best to avoid the confusion and stay away from using . and : altogether.
If using Web Compiler in Visual Studio you can add the path to includePath
in compilerconfig.json.defaults. Then there is no need for some number of ../
since the compiler will use includePath as a location to look for the import.
For example:
"includePath": "node_modules/foundation-sites/scss",
If you pass a DateTime
from a .Net code to a javascript code,
C#:
DateTime net_datetime = DateTime.Now;
javascript treats it as a string, like "/Date(1245398693390)/"
:
You can convert it as fllowing:
// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))
or:
// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))
I've a directory with a bunch of files. I want to find all the files that DO NOT contain the string "speedup" so I successfully used the following command:
grep -iL speedup *
Try the following implementation in Swift 3.0
func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
Usage
delayWithSeconds(1) {
//Do something
}
Angular Concepts
imports
makes the exported declarations of other modules available in the current moduledeclarations
are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.providers
are to make services and values known to DI (dependency injection). They are added to the root scope and they are injected to other services or directives that have them as dependency.A special case for providers
are lazy loaded modules that get their own child injector. providers
of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).
For more details about modules see also https://angular.io/docs/ts/latest/guide/ngmodule.html
exports
makes the components, directives, and pipes available in modules that add this module to imports
. exports
can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.
entryComponents
registers components for offline compilation so that they can be used with ViewContainerRef.createComponent()
. Components used in router configurations are added implicitly.
TypeScript (ES2015) imports
import ... from 'foo/bar'
(which may resolve to an index.ts
) are for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.
Angular's @NgModule()
imports
and TypeScript import
are entirely different concepts.
See also jDriven - TypeScript and ES6 import syntax
Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.
Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.
library(tidyverse)
MyDate %>%
filter(!is.na(the_variable)) %>%
ggplot(aes(x= the_variable, fill=the_variable)) +
geom_bar(stat="bin")
You should be able to remove the annoying NAs on your plot. Hope this works :)
Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).
This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.
for (i in 1:1000)
{
print(i)
date_time<-Sys.time()
while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
I summarize the answers found in that article:
MongoDB: Better querying, data storage in BSON (faster access), better data consistency, multiple collections
CouchDB: Better replication, with master to master replication and conflict resolution, data storage in JSON (human-readable, better access through REST services), querying through map-reduce.
So in conclusion, MongoDB is faster, CouchDB is safer.
Also: http://nosql.mypopescu.com/post/298557551/couchdb-vs-mongodb
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
According to Flexbugs:
In IE 10-11,
min-height
declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.
Here are a couple of workarounds:
<aside>
and <section>
:html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1;
display: flex;
}
aside, section {
overflow: auto;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1 0 auto;
display: flex;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
Try this, perhaps it works ;)
.factory('authInterceptor', function($location, $q, $window) {
return {
request: function(config) {
config.headers = config.headers || {};
config.headers.Authorization = 'xxxx-xxxx';
return config;
}
};
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
})
And make sure your back end works too, try this. I'm using RESTful CodeIgniter.
class App extends REST_Controller {
var $authorization = null;
public function __construct()
{
parent::__construct();
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
if(!$this->input->get_request_header('Authorization')){
$this->response(null, 400);
}
$this->authorization = $this->input->get_request_header('Authorization');
}
}
On Android 4.4 KitKat, I found mine in:
/sdcard/Android/data/<app.package.name>
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
The correct path shouldn't end with "/", I had it wrong that caused the trouble
Right way:
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
Got the issue for months, and finally discovered that when we disable DNSSEC on our api domain, everything was ok :simple_smile:
Most of these answers are wrong due to the failure to use a locale based comparison for sorting. Look at localizedStandardCompare()
Give them all a name that is the same
For example
<input type="button" value="a" name="btn" onclick="a" />
<input type="button" value="b" name="btn" onclick="b" />
Then in your php use:
$val = $_POST['btn']
Edit, as BalusC said; If you're not going to use onclick for doing any javascript (for example, sending the form) then get rid of it and use type="submit"
I did this:
click SDk Manager:
Change in updates to Canary Channel, check and update it...
After go in build.gradle and change the compile version to 26.0.0-beta2:
After go in gradle/build.gradle and change dependencies classpath 'com.android.tools.build:gradle:3.0.0-alpha7':
After sync the project... It works to me! I hope I've helped... tks!
You know you can always check to see what others are doing. Open source software tend to allow access to their repositories. For example you could point your SVN browser to http://svn.doctrine-project.org and take a look at the versioning system used by a real project.
Version numbers, tags, it's all there.
This short and clean code:
::-webkit-input-placeholder {color: red;}
:-moz-placeholder {color: red; /* For Firefox 18- */}
::-moz-placeholder {color: red; /* For Firefox 19+ */}
:-ms-input-placeholder {color: red;}
STEP 1: cd /opt/google/chrome
STEP 2: edit google-chrome file. gedit google-chrome
STEP 3: find this line: exec -a "$0" "$HERE/chrome" "$@"
.
Mostly this line is in the end of google-chrome file.
Comment it out like this : #exec -a "$0" "$HERE/chrome" "$@"
STEP 4:add a new line at the same place.
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir
STEP 5: save google-chrome file and quit. And then you can use chrome as root user. Enjoy it!
This is for the icon in the browser (most of the sites omit the type):
<link rel="icon" type="image/vnd.microsoft.icon"
href="http://example.com/favicon.ico" />
or
<link rel="icon" type="image/png"
href="http://example.com/image.png" />
or
<link rel="apple-touch-icon"
href="http://example.com//apple-touch-icon.png">
for the shortcut icon:
<link rel="shortcut icon"
href="http://example.com/favicon.ico" />
Place them in the <head></head>
section.
Edit may 2019 some additional examples from MDN
/* Microsoft Edge Browser 12-18 (All versions before Chromium) */
This one should work:
@supports (-ms-ime-align:auto) {
.selector {
property: value;
}
}
For more see: Browser Strangeness
I feel like $all
would be more appropriate in this situation. If you are looking for person that is into sushi you do :
PersonModel.find({ favoriteFood : { $all : ["sushi"] }, ...})
As you might want to filter more your search, like so :
PersonModel.find({ favoriteFood : { $all : ["sushi", "bananas"] }, ...})
$in
is like OR and $all
like AND. Check this : https://docs.mongodb.com/manual/reference/operator/query/all/
To control the number of significant digits, use the format specifier %g.
Let's name Emile's solution prettylist2f. Here is the modified one:
prettylist2g = lambda l : '[%s]' % ', '.join("%.2g" % x for x in l)
Usage:
>>> c_e_alpha_eps0 = [299792458., 2.718281828, 0.00729735, 8.8541878e-12]
>>> print(prettylist2f(c_e_alpha_eps0)) # [299792458.00, 2.72, 0.01, 0.00]
>>> print(prettylist2g(c_e_alpha_eps0)) # [3e+08, 2.7, 0.0073, 8.9e-12]
If you want flexibility in the number of significant digits, use f-string formatting instead:
prettyflexlist = lambda p, l : '[%s]' % ', '.join(f"{x:.{p}}" for x in l)
print(prettyflexlist(3,c_e_alpha_eps0)) # [3e+08, 2.72, 0.0073, 8.85e-12]
I would have written:
percent = 100
while True:
try:
pyc = int(input('enter pyc :'))
tpy = int(input('enter tpy:'))
percent = (pyc / tpy) * percent
break
except ZeroDivisionError as detail:
print 'Handling run-time error:', detail
if you don't like the double brackets or you don't want to write a function, you can just use a variable.
$path = Test-Path C:\Code
if (!$path) {
write "it doesn't exist!"
}
In AVD Manager
select the VD and click edit, set the resolution to little as you are able to read the text on VD.
I use 800x600 pixels, RAM set to 512 MB, and it works like a charm without high use of CPU time.
Inline frame is just one "box" and you can place it anywhere on your site. Frames are a bunch of 'boxes' put together to make one site with many pages.
import json
jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""
def getTargetIds(jsonData):
data = json.loads(jsonData)
if 'to' not in data:
raise ValueError("No target in given data")
if 'data' not in data['to']:
raise ValueError("No data for target")
for dest in data['to']['data']:
if 'id' not in dest:
continue
targetId = dest['id']
print("to_id:", targetId)
Output:
In [9]: getTargetIds(s)
to_id: 1543
You could do this:
import java.io.*;
import java.util.*;
class WriteText
{
public static void main(String[] args)
{
try {
String text = "Your sample content to save in a text file.";
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(text);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
return ;
}
};
I added jstl jar in a library and added it to build path and deployment assembly but it dint worked. then i simply copied my jstl jar into lib folder inside webcontent, it worked. in eclipse lib folder in included to deployment assembly by default
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
What about:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
I was just having the same issue...
To resolve the problem (at least in my case) ensure you have included the lib folder in your bundle classpath:
Manifest-Version: 1.0
...
Bundle-ClassPath: lib/gson-1.6.jar,
.
...
Or if you want to include all jar's in the folder:
Bundle-ClassPath: lib/
You will still need to place the jar files on the java build path as shown above. Then your imported jar's should appear in the folder "Referenced Libraries"
I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);
Here is a UDF I built to detectc columns with extended ascii charaters. It is quick and you can extended the character set you want to check. The second parameter allows you to switch between checking anything outside the standard character set or allowing an extended set:
create function [dbo].[udf_ContainsNonASCIIChars]
(
@string nvarchar(4000),
@checkExtendedCharset bit
)
returns bit
as
begin
declare @pos int = 0;
declare @char varchar(1);
declare @return bit = 0;
while @pos < len(@string)
begin
select @char = substring(@string, @pos, 1)
if ascii(@char) < 32 or ascii(@char) > 126
begin
if @checkExtendedCharset = 1
begin
if ascii(@char) not in (9,124,130,138,142,146,150,154,158,160,170,176,180,181,183,184,185,186,192,193,194,195,196,197,199,200,201,202,203,204,205,206,207,209,210,211,212,213,214,216,217,218,219,220,221,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255)
begin
select @return = 1;
select @pos = (len(@string) + 1)
end
else
begin
select @pos = @pos + 1
end
end
else
begin
select @return = 1;
select @pos = (len(@string) + 1)
end
end
else
begin
select @pos = @pos + 1
end
end
return @return;
end
USAGE:
select Address1
from PropertyFile_English
where udf_ContainsNonASCIIChars(Address1, 1) = 1
Based on Tim's second edit and this page you could do this:
@echo off
if "%1"=="loop" (
for /l %%f in (1,1,1000000) do (
echo %%f
if exist %%f exit
)
goto :eof
)
cmd /v:on /q /d /c "%0 loop"
echo done
This page suggests a way to use a goto inside a loop, it seems it does work, but it takes some time in a large loop. So internally it finishes the loop before the goto is executed.
Everyone is correct. However, if you're also busy testing your code your own application might still "own" the socket if it starts and stops relatively quickly. Try SO_REUSEADDR as a socket option:
What exactly does SO_REUSEADDR do?
This socket option tells the kernel that even if this port is busy (in the TIME_WAIT state), go ahead and reuse it anyway. If it is busy, but with another state, you will still get an address already in use error. It is useful if your server has been shut down, and then restarted right away while sockets are still active on its port. You should be aware that if any unexpected data comes in, it may confuse your server, but while this is possible, it is not likely.
It has been pointed out that "A socket is a 5 tuple (proto, local addr, local port, remote addr, remote port). SO_REUSEADDR just says that you can reuse local addresses. The 5 tuple still must be unique!" by Michael Hunter ([email protected]). This is true, and this is why it is very unlikely that unexpected data will ever be seen by your server. The danger is that such a 5 tuple is still floating around on the net, and while it is bouncing around, a new connection from the same client, on the same system, happens to get the same remote port. This is explained by Richard Stevens in ``2.7 Please explain the TIME_WAIT state.''.
If you want your current value to be displayed beneath the slider and moving along with it, try this:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>MySliderValue</title>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<h1>MySliderValue</h1>_x000D_
_x000D_
<div style="position:relative; margin:auto; width:90%">_x000D_
<span style="position:absolute; color:red; border:1px solid blue; min-width:100px;">_x000D_
<span id="myValue"></span>_x000D_
</span>_x000D_
<input type="range" id="myRange" max="1000" min="0" style="width:80%"> _x000D_
</div>_x000D_
_x000D_
<script type="text/javascript" charset="utf-8">_x000D_
var myRange = document.querySelector('#myRange');_x000D_
var myValue = document.querySelector('#myValue');_x000D_
var myUnits = 'myUnits';_x000D_
var off = myRange.offsetWidth / (parseInt(myRange.max) - parseInt(myRange.min));_x000D_
var px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.offsetParent.offsetWidth / 2);_x000D_
_x000D_
myValue.parentElement.style.left = px + 'px';_x000D_
myValue.parentElement.style.top = myRange.offsetHeight + 'px';_x000D_
myValue.innerHTML = myRange.value + ' ' + myUnits;_x000D_
_x000D_
myRange.oninput =function(){_x000D_
let px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.offsetWidth / 2);_x000D_
myValue.innerHTML = myRange.value + ' ' + myUnits;_x000D_
myValue.parentElement.style.left = px + 'px';_x000D_
};_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Note that this type of HTML input element has one hidden feature, such as you can move the slider with left/right/down/up arrow keys when the element has focus on it. The same with Home/End/PageDown/PageUp keys.
When Card I always use RoundedRectangleBorder.
Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(20.0),
child: Container(
child: Column(
children: <Widget>[
ListTile(
title: Text(
'example',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
],
),
),
),
You can also use REPLACE()
:
UPDATE Table
SET Column = REPLACE(Column, 'Test123', 'Test')
you can try this.
data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
data_you_need=data_you_need.append(data,ignore_index=True)
I hope it can help.
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
The easiest way is to create a DtaTable as of now
DataTable table = new DataTable
{
Columns = {
"Name", // typeof(string) is implied
{"Marks", typeof(int)}
},
TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 500);
this is what i did
first execute create database x
. x is the name of your old database eg the name of the mdf.
Then open sql sever configration and stop the sql sever.
There after browse to the location of your new created database it should be under program file, in my case is
C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQL\MSSQL\DATA
and repleace the new created mdf and Idf with the old files/database.
then simply restart the sql server and walla :)
Here is an even shorter way of achieving this:
1) using Negative character class pattern matching
irb(main)> "((String1))"[/[^()]+/]
=> "String1"
^
- Matches anything NOT in the character class. Inside the charachter class, we have (
and )
Or with global substitution "AKA: gsub" like others have mentioned.
irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"
$song = DB::table('songs')->find($id);
here you use method find($id)
for Laravel, if you use this method, you should have column named 'id' and set it as primary key, so then you'll be able to use method find()
otherwise use where('SongID', $id)
instead of find($id)
I didn't see this "complete" answer anywhere; I just saw the one about changing port numbers after I posted this, so meh.
Make sure that in your project properties in visual studio that project url is not assigned to the same url or port that is being used in IIS for any site bindings.
I'm looking up the "why" for this, but my assumption off the top of my head is that both IIS and Visual Studio's IIS express use the same directory when creating virtual directories and Visual Studio can only create new virtual directories and cannot modify any that IIS has created when it applies it's bindings to the site.
feel free to correct me on the why.
I faced this issue, and that is when a Bean (@Bean) was not instantiated properly as it was not given the correct parameters in my test class.
array_walk()
can be used with trim()
to trim array
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
See 2nd example at http://www.php.net/manual/en/function.trim.php
You can do it this way:
object a = new StreamWriter("c:\\temp\\test.txt");
if (a is TextReader == false)
{
Console.WriteLine("failed");
}
A tool with a single solution for this I'm unaware of, but you can use Firebug and Web Developer extension at the same time.
Use Firebug to copy the html section you need (Inspect Element) and Web Developer to see which css is associated with an element (Calling Web Developer "View Style Information" - it works like Firebug's "Inspect Element", but instead of showing the html markup it shows the associated CSS with that markup).
It's not exactly what you want (one click for everything), but it's pretty close, and at least intuitive.
It could be that the gradle-2.1
distribution specified by the wrapper was not downloaded properly. This was the root cause of the same problem in my environment.
Look into this directory:
ls -l ~/.gradle/wrapper/dists/
In there you should find a gradle-2.1
folder.
Delete it like so:
rm -rf ~/.gradle/wrapper/dists/gradle-2.1-bin/
Restart IntelliJ, after that it will restart the download from the beginning and hopefully work.
Thanks, Ioannis
The git diffs have an extra path segment prepended to the file paths. You can strip the this entry in the path by specifying -p1 with patch, like so:
patch -p1 < save.patch
I think you can get it using subc1.text
.
>>> html = """
<p>
<strong class="offender">YOB:</strong> 1987<br />
<strong class="offender">RACE:</strong> WHITE<br />
<strong class="offender">GENDER:</strong> FEMALE<br />
<strong class="offender">HEIGHT:</strong> 5'05''<br />
<strong class="offender">WEIGHT:</strong> 118<br />
<strong class="offender">EYE COLOR:</strong> GREEN<br />
<strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.text
YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN
Or if you want to explore it, you can use .contents
:
>>> p = soup.find('p')
>>> from pprint import pprint
>>> pprint(p.contents)
[u'\n',
<strong class="offender">YOB:</strong>,
u' 1987',
<br/>,
u'\n',
<strong class="offender">RACE:</strong>,
u' WHITE',
<br/>,
u'\n',
<strong class="offender">GENDER:</strong>,
u' FEMALE',
<br/>,
u'\n',
<strong class="offender">HEIGHT:</strong>,
u" 5'05''",
<br/>,
u'\n',
<strong class="offender">WEIGHT:</strong>,
u' 118',
<br/>,
u'\n',
<strong class="offender">EYE COLOR:</strong>,
u' GREEN',
<br/>,
u'\n',
<strong class="offender">HAIR COLOR:</strong>,
u' BROWN',
<br/>,
u'\n']
and filter out the necessary items from the list:
>>> data = dict(zip([x.text for x in p.contents[1::4]], [x.strip() for x in p.contents[2::4]]))
>>> pprint(data)
{u'EYE COLOR:': u'GREEN',
u'GENDER:': u'FEMALE',
u'HAIR COLOR:': u'BROWN',
u'HEIGHT:': u"5'05''",
u'RACE:': u'WHITE',
u'WEIGHT:': u'118',
u'YOB:': u'1987'}
In many cases you're better off using CSS transitions for this, and in old browsers the easing will simply be instant. Most animations (like fade in/out) are very trivial to implement and the browser does all the legwork for you. https://developer.mozilla.org/en/docs/Web/CSS/transition
If you knew that the length of conditions you would care about would all be the same length then you could:
switch(mystring.substring(0, Math.Min(3, mystring.Length))
{
case "abc":
//do something
break;
case "xyz":
//do something else
break;
default:
//do a different thing
break;
}
The Math.Min(3, mystring.Length)
is there so that a string of less than 3 characters won't throw an exception on the sub-string operation.
There are extensions of this technique to match e.g. a bunch of 2-char strings and a bunch of 3-char strings, where some 2-char comparisons matching are then followed by 3-char comparisons. Unless you've a very large number of such strings though, it quickly becomes less efficient than simple if-else chaining for both the running code and the person who has to maintain it.
Edit: Added since you've now stated they will be of different lengths. You could do the pattern I mentioned of checking the first X chars and then the next Y chars and so on, but unless there's a pattern where most of the strings are the same length this will be both inefficient and horrible to maintain (a classic case of premature pessimisation).
The command pattern is mentioned in another answer, so I won't give details of that, as is that where you map string patterns to IDs, but they are option.
I would not change from if-else chains to command or mapping patterns to gain the efficiency switch sometimes has over if-else, as you lose more in the comparisons for the command or obtaining the ID pattern. I would though do so if it made code clearer.
A chain of if-else's can work pretty well, either with string comparisons or with regular expressions (the latter if you have comparisons more complicated than the prefix-matches so far, which would probably be simpler and faster, I'm mentioning reg-ex's just because they do sometimes work well with more general cases of this sort of pattern).
If you go for if-elses, try to consider which cases are going to happen most often, and make those tests happen before those for less-common cases (though of course if "starts with abcd" is a case to look for it would have to be checked before "starts with abc").
For my case, the exception was raised because I tried to mock a package-access
method. When I changed the method access level from package
to protected
the exception went away. E.g. inside below Java class,
public class Foo {
String getName(String id) {
return mMap.get(id);
}
}
the method String getName(String id)
has to be AT LEAST protected
level so that the mocking mechanism (sub-classing) can work.
function parseIt(){
return new Promise(function(res){
try{
var fs = require('fs');
const dirPath = 'K:\\merge-xml-junit\\xml-results\\master.json';
fs.readFile(dirPath,'utf8',function(err,data){
if(err) throw err;
res(data);
})}
catch(err){
res(err);
}
});
}
async function test(){
jsonData = await parseIt();
var parsedJSON = JSON.parse(jsonData);
var testSuite = parsedJSON['testsuites']['testsuite'];
console.log(testSuite);
}
test();
In ---- model:
Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
Change the class ----- extends Model
to class ----- extends Eloquent
Use:
Console.ReadKey();
For it to close when someone presses any key, or:
Console.ReadLine();
For when the user types something and presses enter.
Microsoft Visual Studio Express
It's a full IDE, with powerful debugging tools, syntax highlighting, etc.
this works: select * from table where column like '%(hit enter)%'
Ignore the brackets and hit enter to introduce new line.
It is easy to check for removable devices. However, there's no guarantee that it is a USB device:
var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
This will return a list of all removable devices that are currently accessible. More information:
DriveInfo
class (msdn documentation)DriveType
enumeration (msdn documentation)Write this in each "new activity" after you initialized your new intent->
Intent i = new Intent(this, yourClass.class);
startActivity(i);
finish();
Here is a function that takes as its arguments a DataFrame and a list of columns and coerces all data in the columns to numbers.
# df is the DataFrame, and column_list is a list of columns as strings (e.g ["col1","col2","col3"])
# dependencies: pandas
def coerce_df_columns_to_numeric(df, column_list):
df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')
So, for your example:
import pandas as pd
def coerce_df_columns_to_numeric(df, column_list):
df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col1','col2','col3'])
coerce_df_columns_to_numeric(df, ['col2','col3'])
To validate base64 image we can use this regex
/^data:image/(?:gif|png|jpeg|bmp|webp)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}
private validBase64Image(base64Image: string): boolean {
const regex = /^data:image\/(?:gif|png|jpeg|bmp|webp)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}/;
return base64Image && regex.test(base64Image);
}
You can make the query using convert to varbinary – it’s very easy. Example:
Select * from your_table where convert(varbinary, your_column) = convert(varbinary, 'aBcD')
os.path.exists
returns True
for folders as well as files. Consider using os.path.isfile
to check for whether the file exists instead.
Try the following 2 things...
1) Add this to your my.cnf / my.ini
in the [mysqld]
section
max_allowed_packet=32M
(you might have to set this value higher based on your existing database).
2) If the import still does not work, try it like this as well...
mysql -u <user> --password=<password> <database name> <file_to_import
Until I was really concerned about performance, I would use a function, that takes a base and returns its match:
char base_pair(char base)
{
switch(base) {
case 'T': return 'A';
... etc
default: // handle error
}
}
If I was concerned about performance, I would define a base as one fourth of a byte. 0 would represent A, 1 would represent G, 2 would represent C, and 3 would represent T. Then I would pack 4 bases into a byte, and to get their pairs, I would simply take the complement.
Try using Array.Reverse
public string Reverse(string str)
{
char[] array = str.ToCharArray();
Array.Reverse(array);
return new string(array);
}
to get the number of observations the number of rows from your Dataset would be more valid:
nrow(dat[dat$sCode == "CA",])
On MySQL 8.0.15 (maybe earlier than this too): the PASSWORD()
function does not work anymore, so you have to do:
Make sure you have stopped MySQL first (Go to: 'System Preferences' >> 'MySQL' and stop MySQL).
Run the server in safe mode with privilege bypass:
sudo mysqld_safe --skip-grant-tables
mysql -u root
UPDATE mysql.user SET authentication_string=null WHERE User='root';
FLUSH PRIVILEGES;
exit;
Then
mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';
Finally, start your MySQL again.
Enlighten by @OlatunjiYso in this GitHub issue.
The answer provided by rcs works and is simple. However, if you are handling larger datasets and need a performance boost there is a faster alternative:
library(data.table)
data = data.table(Category=c("First","First","First","Second","Third", "Third", "Second"),
Frequency=c(10,15,5,2,14,20,3))
data[, sum(Frequency), by = Category]
# Category V1
# 1: First 30
# 2: Second 5
# 3: Third 34
system.time(data[, sum(Frequency), by = Category] )
# user system elapsed
# 0.008 0.001 0.009
Let's compare that to the same thing using data.frame and the above above:
data = data.frame(Category=c("First","First","First","Second","Third", "Third", "Second"),
Frequency=c(10,15,5,2,14,20,3))
system.time(aggregate(data$Frequency, by=list(Category=data$Category), FUN=sum))
# user system elapsed
# 0.008 0.000 0.015
And if you want to keep the column this is the syntax:
data[,list(Frequency=sum(Frequency)),by=Category]
# Category Frequency
# 1: First 30
# 2: Second 5
# 3: Third 34
The difference will become more noticeable with larger datasets, as the code below demonstrates:
data = data.table(Category=rep(c("First", "Second", "Third"), 100000),
Frequency=rnorm(100000))
system.time( data[,sum(Frequency),by=Category] )
# user system elapsed
# 0.055 0.004 0.059
data = data.frame(Category=rep(c("First", "Second", "Third"), 100000),
Frequency=rnorm(100000))
system.time( aggregate(data$Frequency, by=list(Category=data$Category), FUN=sum) )
# user system elapsed
# 0.287 0.010 0.296
For multiple aggregations, you can combine lapply
and .SD
as follows
data[, lapply(.SD, sum), by = Category]
# Category Frequency
# 1: First 30
# 2: Second 5
# 3: Third 34
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
Is it possible (work only online and load only your page or file): https://w3schools.com/xml/xml_http.asp Try my code:
function load_page(){
qr=new XMLHttpRequest();
qr.open('get','YOUR_file_or_page.htm');
qr.send();
qr.onload=function(){YOUR_div_id.innerHTML=qr.responseText}
};load_page();
qr.onreadystatechange instead qr.onload also use.
try using the instr function?
select my_column from my_table where instr(?, ','||search_column||',') > 0
then
ps.setString(1, ",A,B,C,");
Admittedly this is a bit of a dirty hack, but it does reduce the opportunities for sql injection. Works in oracle anyway.
I cleaned up mido's post and then cleaned up the function that they found. This will either return false
or an array
. When testing remember that you need to collapse the array in the web developer console otherwise it's nonintuitive default behavior may deceive you in to thinking that it is returning an empty array
.
function ip_local()
{
var ip = false;
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || false;
if (window.RTCPeerConnection)
{
ip = [];
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
pc.createDataChannel('');
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function(event)
{
if (event && event.candidate && event.candidate.candidate)
{
var s = event.candidate.candidate.split('\n');
ip.push(s[0].split(' ')[4]);
}
}
}
return ip;
}
Additionally please keep in mind folks that this isn't something old-new like CSS border-radius
though one of those bits that is outright not supported by IE11 and older. Always use object detection, test in reasonably older browsers (e.g. Firefox 4, IE9, Opera 12.1) and make sure your newer scripts aren't breaking your newer bits of code. Additionally always detect standards compliant code first so if there is something with say a CSS prefix detect the standard non-prefixed code first and then fall back as in the long term support will eventually be standardized for the rest of it's existence.
most simple solution would be to set a boolean var. if to true where you do the insert statement and then in the outter loop check this and insert the tweet there if the boolean is true...
Just make sure to write the docker name correctly!
In my case, I wrote (notice the extra 'u'):
FROM ubunutu:16.04
The correct docker name is:
FROM ubuntu:16.04
Of course that works; when @item1 = N''
, it IS NOT NULL
.
You can define @item1
as NULL
by default at the top of your stored procedure, and then not pass in a parameter.
here is more simple way without StartCoroutine:
float t = 0f;
float waittime = 1f;
and inside Update/FixedUpdate:
if (t < 0){
t += Time.deltaTIme / waittime;
yield return t;
}
Raystorm had a good answer. I'm not a big fan of Rules either. I do something similar, except that I create the following utility class to help readability and usability, which is one of the big plus'es of annotations in the first place.
Add this utility class:
import org.junit.Assert;
public abstract class ExpectedRuntimeExceptionAsserter {
private String expectedExceptionMessage;
public ExpectedRuntimeExceptionAsserter(String expectedExceptionMessage) {
this.expectedExceptionMessage = expectedExceptionMessage;
}
public final void run(){
try{
expectException();
Assert.fail(String.format("Expected a RuntimeException '%s'", expectedExceptionMessage));
} catch (RuntimeException e){
Assert.assertEquals("RuntimeException caught, but unexpected message", expectedExceptionMessage, e.getMessage());
}
}
protected abstract void expectException();
}
Then for my unit test, all I need is this code:
@Test
public void verifyAnonymousUserCantAccessPrivilegedResourceTest(){
new ExpectedRuntimeExceptionAsserter("anonymous user can't access privileged resource"){
@Override
protected void expectException() {
throw new RuntimeException("anonymous user can't access privileged resource");
}
}.run(); //passes test; expected exception is caught, and this @Test returns normally as "Passed"
}
The filter option filters only the first level subkey below ansible_facts
You can use the required
html attribute if you want:
@Html.TextBoxFor(m => m.ShortName,
new { @class = "form-control", placeholder = "short name", required="required"})
or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute
can Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.
OR
You can get really advanced:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
@Html.TextBoxFor(m => m.ShortName, attributes)
}
or if you need it for multiple editor templates:
public static class ViewPageExtensions
{
public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
instance.Html.GetUnobtrusiveValidationAttributes(
instance.ViewData.TemplateInfo.HtmlFieldPrefix));
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
}
}
then in your templates:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = this.GetAttributes();
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
@Html.TextBoxFor(m => m.ShortName, attributes)
}
Update 1 (for Tomas who is unfamilar with ViewData).
What's the difference between ViewData and ViewBag?
Excerpt:
So basically it (ViewBag) replaces magic strings:
ViewData["Foo"]
with magic properties:
ViewBag.Foo
I currently follow the policy (that so many are saying) that classes shouldn't actively throw exceptions from their destructors but should instead provide a public "close" method to perform the operation that could fail...
...but I do believe destructors for container-type classes, like a vector, should not mask exceptions thrown from classes they contain. In this case, I actually use a "free/close" method that calls itself recursively. Yes, I said recursively. There's a method to this madness. Exception propagation relies on there being a stack: If a single exception occurs, then both the remaining destructors will still run and the pending exception will propagate once the routine returns, which is great. If multiple exceptions occur, then (depending on the compiler) either that first exception will propagate or the program will terminate, which is okay. If so many exceptions occur that the recursion overflows the stack then something is seriously wrong, and someone's going to find out about it, which is also okay. Personally, I err on the side of errors blowing up rather than being hidden, secret, and insidious.
The point is that the container remains neutral, and it's up to the contained classes to decide whether they behave or misbehave with regard to throwing exceptions from their destructors.
if all you need is the names, use xpath instead. No need to do the iteration yourself and check for null.
string xml = @"
<root>
<Employee name=""an"" />
<Employee name=""nobyd"" />
<Employee/>
</root>
";
var doc = new XmlDocument();
//doc.Load(path);
doc.LoadXml(xml);
var names = doc.SelectNodes("//Employee/@name");
It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.
There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit()
method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.
CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.
Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.
i solved this by following
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
hope it will help you
Adding my answer, because it elaborates the idea that you can SELECT multiple columns from the table from which you subquery.
Here I needed the the most recently cast cote and it's associated information.
I first tried simply to SELECT the max(votedate) along with vote, itemid, userid etc., but while the query would return the max votedate, it would also return the a random row for the other information. Hard to see among a bunch of 1s and 0s.
This worked well:
$query = "
SELECT t1.itemid, t1.itemtext, t2.vote, t2.votedate, t2.userid
FROM
(
SELECT itemid, itemtext FROM oc_item ) t1
LEFT JOIN
(
SELECT vote, votedate, itemid,userid FROM oc_votes
WHERE votedate IN
(select max(votedate) FROM oc_votes group by itemid)
AND userid=:userid) t2
ON (t1.itemid = t2.itemid)
order by itemid ASC
";
The subquery in the WHERE clause WHERE votedate IN (select max(votedate) FROM oc_votes group by itemid) returns one record - the record with the max vote date.
#include<stdio.h>
int main()
{
int arr[]={10,20,30,40,50,60};
int *p;
int count=0;
for(p=arr;p<&arr+1;p++)
count++;
printf("The no of elements in array=%d",count);
return 0;
}
OUTPUT=6
EXPLANATION
p
is a pointer to a 1-D array, and in the loop for(p=arr,p<&arr+1;p++)
I made p
point to the base address. Suppose its base address is 1000; if we increment p
then it points to 1002 and so on. Now coming to the concept of &arr
- It basically represents the whole array, and if we add 1 to the whole array i.e. &arr+1
, it gives the address 1012 i.e. the address of next 1-D array (in our case the size of int is 2), so the condition becomes 1000<1012.
So, basically the condition becomes
for(p=1000;p<1012;p++)
And now let's check the condition and count the value
p=1000
and p<1012
condition is true
: enter in the loop, increment the value of count
to 1.p=1002
and p<1012
condition is true
: enter in the loop, increment the value of count
to 2.p=1010
and p<1012
condition is true
: enter in the loop, increment the value of count
to 6.p=1012
and p<1012
condition is false: print the value of count=6
in printf
statement.Examining the cookies the site gives can reveal the underlying framework. CodeIgniter, for example defaults to a telltale ci_sessions cookie. Sites using PEAR Auth will do something similar.
Getting updatedb to work in cron on Cygwin -- debugging steps
1) Make sure cron is installed.
a) Type 'cron' tab tab and look for completion help.
You should see crontab.exe, cron-config, etc. If not install cron using setup.
2) Run cron-config. Be sure to read all the ways to diagnose cron.
3) Run crontab -e
a) Create a test entry of something simple, e.g.,
"* * * * * echo $HOME >> /tmp/mycron.log" and save it.
4) cat /tmp/mycron.log. Does it show cron environment variable HOME
every minute?
5) Is HOME correct? By default mine was /home/myusername; not what I wanted.
So, I added the entry
"HOME='/cygdrive/c/documents and settings/myusername'" to crontab.
6) Once assured the test entry works I moved on to 'updatedb' by
adding an entry in crontab.
7) Since updatedb is a script, errors of sed and find showed up in
my cron.log file. In the error line, the absolute path of sed referenced
an old version of sed.exe and not the one in /usr/bin. I tried changing my
cron PATH environment variable but because it was so long crontab
considered the (otherwise valid) change to be an error. I tried an
explicit much-shorter PATH command, including what I thought were the essential
WINDOWS paths but my cron.log file was empty. Eventually I left PATH alone and
replaced the old sed.exe in the other path with sed.exe from /usr/bin.
After that updatedb ran to completion. To reduce the number of
permission error lines I eventually ended up with this:
"# Run updatedb at 2:10am once per day skipping Sat and Sun'
"10 2 * * 1-5 /usr/bin/updatedb --localpaths='/cygdrive/c' --prunepaths='/cygdrive/c/WINDOWS'"
Notes: I ran cron-config several times throughout this process
to restart the cygwin cron daemon.
Best approach, no crazed values, distributed with respect to the representable intervals on the floating-point number line (removed "uniform" as with respect to a continuous number line it is decidedly non-uniform):
static float NextFloat(Random random)
{
double mantissa = (random.NextDouble() * 2.0) - 1.0;
// choose -149 instead of -126 to also generate subnormal floats (*)
double exponent = Math.Pow(2.0, random.Next(-126, 128));
return (float)(mantissa * exponent);
}
(*) ... check here for subnormal floats
Warning: generates positive infinity as well! Choose exponent of 127 to be on the safe side.
Another approach which will give you some crazed values (uniform distribution of bit patterns), potentially useful for fuzzing:
static float NextFloat(Random random)
{
var buffer = new byte[4];
random.NextBytes(buffer);
return BitConverter.ToSingle(buffer,0);
}
An improvement over the previous version is this one, which does not create "crazed" values (neither infinities nor NaN) and is still fast (also distributed with respect to the representable intervals on the floating-point number line):
public static float Generate(Random prng)
{
var sign = prng.Next(2);
var exponent = prng.Next((1 << 8) - 1); // do not generate 0xFF (infinities and NaN)
var mantissa = prng.Next(1 << 23);
var bits = (sign << 31) + (exponent << 23) + mantissa;
return IntBitsToFloat(bits);
}
private static float IntBitsToFloat(int bits)
{
unsafe
{
return *(float*) &bits;
}
}
Least useful approach:
static float NextFloat(Random random)
{
// Not a uniform distribution w.r.t. the binary floating-point number line
// which makes sense given that NextDouble is uniform from 0.0 to 1.0.
// Uniform w.r.t. a continuous number line.
//
// The range produced by this method is 6.8e38.
//
// Therefore if NextDouble produces values in the range of 0.0 to 0.1
// 10% of the time, we will only produce numbers less than 1e38 about
// 10% of the time, which does not make sense.
var result = (random.NextDouble()
* (Single.MaxValue - (double)Single.MinValue))
+ Single.MinValue;
return (float)result;
}
Floating point number line from: Intel Architecture Software Developer's Manual Volume 1: Basic Architecture. The Y-axis is logarithmic (base-2) because consecutive binary floating point numbers do not differ linearly.
As of PHP 7, you can use the Unicode codepoint escape syntax to do this.
echo "\u{00ed}";
outputs í
.
As stated earlier by Jamie Dixon, a floated <div>
is taken out of normal flow. All content that is still within normal flow will ignore it completely and not make space for it.
Try putting a different colored border border:solid 1px orange;
around each of your <div>
elements to see what they're doing. You might start by removing the floats and putting some dummy text inside the div. Then style them one at a time to get the desired layout.
That is not problem of IIS but the problem of WCF. WCF by default limits messages to 65KB to avoid denial of service attack with large messages. Also if you don't use MTOM it sends byte[] to base64 encoded string (33% increase in size) => 48KB * 1,33 = 64KB
To solve this issue you must reconfigure your service to accept larger messages. This issue previously fired 400 Bad Request error but in newer version WCF started to use 413 which is correct status code for this type of error.
You need to set maxReceivedMessageSize
in your binding. You can also need to set readerQuotas
.
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxReceivedMessageSize="10485760">
<readerQuotas ... />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
TLDR: simple defined variables (without var
, let
, const
) could be deleted with delete
. If you use var
, let
, const
- they could not be deleted neither with delete
nor with Reflect.deleteProperty
.
Chrome 55:
simpleVar = "1";
"1"
delete simpleVar;
true
simpleVar;
VM439:1 Uncaught ReferenceError: simpleVar is not defined
at <anonymous>:1:1
(anonymous) @ VM439:1
var varVar = "1";
undefined
delete varVar;
false
varVar;
"1"
let letVar = "1";
undefined
delete letVar;
true
letVar;
"1"
const constVar="1";
undefined
delete constVar;
true
constVar;
"1"
Reflect.deleteProperty (window, "constVar");
true
constVar;
"1"
Reflect.deleteProperty (window, "varVar");
false
varVar;
"1"
Reflect.deleteProperty (window, "letVar");
true
letVar;
"1"
FF Nightly 53.0a1 shows same behaviour.
For future googlers searching for a solution to this problem when you don't know the keys of all circular references, you could use a wrapper around the JSON.stringify function to rule out circular references. See an example script at https://gist.github.com/4653128.
The solution essentially boils down to keeping a reference to previously printed objects in an array, and checking that in a replacer function before returning a value. It's more constrictive than only ruling out circular references, because it also rules out ever printing an object twice, one of the side affects of which is to avoid circular references.
Example wrapper:
function stringifyOnce(obj, replacer, indent){
var printedObjects = [];
var printedObjectKeys = [];
function printOnceReplacer(key, value){
var printedObjIndex = false;
printedObjects.forEach(function(obj, index){
if(obj===value){
printedObjIndex = index;
}
});
if(printedObjIndex && typeof(value)=="object"){
return "(see " + value.constructor.name.toLowerCase() + " with key " + printedObjectKeys[printedObjIndex] + ")";
}else{
var qualifiedKey = key || "(empty key)";
printedObjects.push(value);
printedObjectKeys.push(qualifiedKey);
if(replacer){
return replacer(key, value);
}else{
return value;
}
}
}
return JSON.stringify(obj, printOnceReplacer, indent);
}
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
You need to return your promise to the calling function.
islogged:function(){
var cUid=sessionService.get('uid');
alert("in loginServce, cuid is "+cUid);
var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
$checkSessionServer.then(function(){
alert("session check returned!");
console.log("checkSessionServer is "+$checkSessionServer);
});
return $checkSessionServer; // <-- return your promise to the calling function
}
Well, depending on your needs you can choose any of the following. Out put is written against each method
You can choose the one you need
This will round
decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
This will ensure that 2 decimal places are written.
d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
if you want to write commas you can use this
d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
if you want to return the rounded of decimal value you can do this
d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
Use os.path.abspath()
:
os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
sys.argv[0]
in your case is just a script name, no directory, so os.path.dirname()
returns an empty string.
os.path.abspath()
turns that into a proper absolute path with directory name.