Got the same problem in 11 11 19, so sorry for possible necroposting. The only what helped was next solution:
var drop = $('#product_1'); // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2'); pick krajee attrs of our elem;
var drop_id = drop.attr('id'); // take id
settings = window[settings]; // take previous settings from window;
drop.select2(settings); // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;
It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive. Hope, this solution will be usefull or may push you in right decision in problem fixing
You may use ReadFormattedLine subroutine for all kind of formatted input. For example, the command below read a password of 8 characters, display asterisks in the screen, and continue automatically with no need to press Enter:
call :ReadFormattedLine password="********" /M "Enter password (8 chars): "
This subroutine is written in pure Batch so it does not require any additional program, and it allows several formatted input operations, like read just numbers, convert letters to uppercase, etc. You may download ReadFormattedLine subroutine from Read a line with specific format.
EDIT 2018-08-18: New method to enter an "invisible" password
The FINDSTR command have a strange bug that happen when this command is used to show characters in color AND the output of such a command is redirected to CON device. For details on how use FINDSTR command to show text in color, see this topic.
When the output of this form of FINDSTR command is redirected to CON, something strange happens after the text is output in the desired color: all the text after it is output as "invisible" characters, although a more precise description is that the text is output as black text over black background. The original text will appear if you use COLOR command to reset the foreground and background colors of the entire screen. However, when the text is "invisible" we could execute a SET /P command, so all characters entered will not appear on the screen.
@echo off
setlocal
set /P "=_" < NUL > "Enter password"
findstr /A:1E /V "^$" "Enter password" NUL > CON
del "Enter password"
set /P "password="
cls
color 07
echo The password read is: "%password%"
I added the following to @PreDestroy method in my CDI @ApplicationScoped bean, and when I shutdown TomEE 1.6.0 (tomcat7.0.39, as of today), it clears the thread locals.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pf;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Administrator
*
* google-gson issue # 402: Memory Leak in web application; comment # 25
* https://code.google.com/p/google-gson/issues/detail?id=402
*/
public class ThreadLocalImmolater {
final Logger logger = LoggerFactory.getLogger(ThreadLocalImmolater.class);
Boolean debug;
public ThreadLocalImmolater() {
debug = true;
}
public Integer immolate() {
int count = 0;
try {
final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
final Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
inheritableThreadLocalsField.setAccessible(true);
for (final Thread thread : Thread.getAllStackTraces().keySet()) {
count += clear(threadLocalsField.get(thread));
count += clear(inheritableThreadLocalsField.get(thread));
}
logger.info("immolated " + count + " values in ThreadLocals");
} catch (Exception e) {
throw new Error("ThreadLocalImmolater.immolate()", e);
}
return count;
}
private int clear(final Object threadLocalMap) throws Exception {
if (threadLocalMap == null)
return 0;
int count = 0;
final Field tableField = threadLocalMap.getClass().getDeclaredField("table");
tableField.setAccessible(true);
final Object table = tableField.get(threadLocalMap);
for (int i = 0, length = Array.getLength(table); i < length; ++i) {
final Object entry = Array.get(table, i);
if (entry != null) {
final Object threadLocal = ((WeakReference)entry).get();
if (threadLocal != null) {
log(i, threadLocal);
Array.set(table, i, null);
++count;
}
}
}
return count;
}
private void log(int i, final Object threadLocal) {
if (!debug) {
return;
}
if (threadLocal.getClass() != null &&
threadLocal.getClass().getEnclosingClass() != null &&
threadLocal.getClass().getEnclosingClass().getName() != null) {
logger.info("threadLocalMap(" + i + "): " +
threadLocal.getClass().getEnclosingClass().getName());
}
else if (threadLocal.getClass() != null &&
threadLocal.getClass().getName() != null) {
logger.info("threadLocalMap(" + i + "): " + threadLocal.getClass().getName());
}
else {
logger.info("threadLocalMap(" + i + "): cannot identify threadlocal class name");
}
}
}
Since nobody's mentioned it yet here's a zip()
solution:
>>> def chunker(iterable, chunksize):
... return zip(*[iter(iterable)]*chunksize)
It works only if your sequence's length is always divisible by the chunk size or you don't care about a trailing chunk if it isn't.
Example:
>>> s = '1234567890'
>>> chunker(s, 3)
[('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9')]
>>> chunker(s, 4)
[('1', '2', '3', '4'), ('5', '6', '7', '8')]
>>> chunker(s, 5)
[('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')]
Or using itertools.izip to return an iterator instead of a list:
>>> from itertools import izip
>>> def chunker(iterable, chunksize):
... return izip(*[iter(iterable)]*chunksize)
Padding can be fixed using @??O?????'s answer:
>>> from itertools import chain, izip, repeat
>>> def chunker(iterable, chunksize, fillvalue=None):
... it = chain(iterable, repeat(fillvalue, chunksize-1))
... args = [it] * chunksize
... return izip(*args)
try the following extension
extension UIView {
func addTapGesture(action : @escaping ()->Void ){
let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
tap.action = action
tap.numberOfTapsRequired = 1
self.addGestureRecognizer(tap)
self.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: MyTapGestureRecognizer) {
sender.action!()
}
}
class MyTapGestureRecognizer: UITapGestureRecognizer {
var action : (()->Void)? = nil
}
and then use it :
submitBtn.addTapGesture {
//your code
}
you can even use it for cell
cell.addTapGesture {
//your code
}
The following adds elements to a list in a loop.
l<-c()
i=1
while(i<100) {
b<-i
l<-c(l,b)
i=i+1
}
For SQL 2000 I would use:
SELECT name, crdate, refdate
FROM sysobjects
WHERE type = 'P'
ORDER BY refdate desc
Use in Swift 3
perform(<Selector>, with: <object>, afterDelay: <Time in Seconds>)
The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.
If you look at the call signature of np.int
, you'll see that it accepts a single value, not an array. In general, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize
:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()
You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int)
.
Note that np.vectorize
is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int)
as @FFT suggests).
rand()
is the most convenient way to generate random numbers.
You may also catch random number from any online service like random.org.
You don't need to change the compliance level here, or rather, you should but that's not the issue.
The code compliance ensures your code is compatible with a given Java version.
For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).
The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.
Instead, you should check the JDK/JRE you're using to build.
In Eclipse, open the project properties and check the selected JRE in the Java build path.
If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.
Now at v2.24.0 suggests
git restore --staged .
to unstage files.
For Visual Studio Noobs like me
You may be running the process in other terminals!
After closing the terminal in Visual Studio, the terminal just disappears.
I manually created a new one thinking that the previous one was destroyed. In reality, every time I was clicking on New Terminal I was actually creating a new one on top of the previous ones.
So I located the first terminal and... Voila, I was running the server there.
In the tradition of itoa()
:
#define btoa(x) ((x)?"true":"false")
bool x = true;
printf("%s\n", btoa(x));
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair
.
An alternative is to use (Http)URLConnection
. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection
javadoc.
This script lists most of what you are looking for and can hopefully be modified to you needs. Note that it is creating a permanent table in there - you might want to change it. It is a subset from a larger script that also summarises backup and job information on various servers.
IF OBJECT_ID('tempdb..#DriveInfo') IS NOT NULL
DROP TABLE #DriveInfo
CREATE TABLE #DriveInfo
(
Drive CHAR(1)
,MBFree INT
)
INSERT INTO #DriveInfo
EXEC master..xp_fixeddrives
IF OBJECT_ID('[dbo].[Tmp_tblDatabaseInfo]', 'U') IS NOT NULL
DROP TABLE [dbo].[Tmp_tblDatabaseInfo]
CREATE TABLE [dbo].[Tmp_tblDatabaseInfo](
[ServerName] [nvarchar](128) NULL
,[DBName] [nvarchar](128) NULL
,[database_id] [int] NULL
,[create_date] datetime NULL
,[CompatibilityLevel] [int] NULL
,[collation_name] [nvarchar](128) NULL
,[state_desc] [nvarchar](60) NULL
,[recovery_model_desc] [nvarchar](60) NULL
,[DataFileLocations] [nvarchar](4000)
,[DataFilesMB] money null
,DataVolumeFreeSpaceMB INT NULL
,[LogFileLocations] [nvarchar](4000)
,[LogFilesMB] money null
,LogVolumeFreeSpaceMB INT NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Tmp_tblDatabaseInfo]
SELECT
@@SERVERNAME AS [ServerName]
,d.name AS DBName
,d.database_id
,d.create_date
,d.compatibility_level
,CAST(d.collation_name AS [nvarchar](128)) AS collation_name
,d.[state_desc]
,d.recovery_model_desc
,(select physical_name + ' | ' AS [text()]
from sys.master_files m
WHERE m.type = 0 and m.database_id = d.database_id
ORDER BY file_id
FOR XML PATH ('')) AS DataFileLocations
,(select sum(size) from sys.master_files m WHERE m.type = 0 and m.database_id = d.database_id) AS DataFilesMB
,NULL
,(select physical_name + ' | ' AS [text()]
from sys.master_files m
WHERE m.type = 1 and m.database_id = d.database_id
ORDER BY file_id
FOR XML PATH ('')) AS LogFileLocations
,(select sum(size) from sys.master_files m WHERE m.type = 1 and m.database_id = d.database_id) AS LogFilesMB
,NULL
FROM sys.databases d
WHERE d.database_id > 4 --Exclude basic system databases
UPDATE [dbo].[Tmp_tblDatabaseInfo]
SET DataFileLocations =
CASE WHEN LEN(DataFileLocations) > 4 THEN LEFT(DataFileLocations,LEN(DataFileLocations)-2) ELSE NULL END
,LogFileLocations =
CASE WHEN LEN(LogFileLocations) > 4 THEN LEFT(LogFileLocations,LEN(LogFileLocations)-2) ELSE NULL END
,DataFilesMB =
CASE WHEN DataFilesMB > 0 THEN DataFilesMB * 8 / 1024.0 ELSE NULL END
,LogFilesMB =
CASE WHEN LogFilesMB > 0 THEN LogFilesMB * 8 / 1024.0 ELSE NULL END
,DataVolumeFreeSpaceMB =
(SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( DataFileLocations,1))
,LogVolumeFreeSpaceMB =
(SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( LogFileLocations,1))
select * from [dbo].[Tmp_tblDatabaseInfo]
It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.
From facebook:
size - Different sized buttons: small, medium, large, xlarge - the default is medium. https://developers.facebook.com/docs/reference/plugins/login/
Set the login iframe opacity to 0 and show a background image in the parent div
.fb_iframe_widget iframe {
opacity: 0;
}
.fb_iframe_widget {
background-image: url(another-button.png);
background-repeat: no-repeat;
}
If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.
For my instance i used it as a global and then called its for a time check of when hours of operation.
Below is from my index.js
global.globalDay = new Date().getDay();
global.globalHours = new Date().getHours();
To call the global's value from another file
/*
Days of the Week.
Sunday = 0, Monday = 1, Tuesday = 2, Wensday = 3, Thursday = 4, Friday = 5, Saturday = 6
Hours of the Day.
0 = Midnight, 1 = 1am, 12 = Noon, 18 = 6pm, 23 = 11pm
*/
if (global.globalDay === 6 || global.globalDay === 0) {
console.log('Its the weekend.');
} else if (global.globalDay > 0 && global.globalDay < 6 && global.globalHours > 8 && global.globalHours < 18) {
console.log('During Business Hours!');
} else {
console.log("Outside of Business hours!");
}
I think ForkJoinPool and related enhancement to Executor Framework is an important addition in Java 7.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = true
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)
intRow = 2
dim ch
objWorksheet.Cells(1,1) = "Name"
objWorksheet.Cells(1,2) = "Subject1"
objWorksheet.Cells(1,3) = "Subject2"
objWorksheet.Cells(1,4) = "Total"
for intRow = 2 to 10000
name= InputBox("Enter your name")
sb1 = cint(InputBox("Enter your Marks in Subject 1"))
sb2 = cint(InputBox("Enter your Marks in Subject 2"))
total= sb1+sb2+sb3+sb4
objExcel.Cells(intRow, 1).Value = name
objExcel.Cells(intRow, 2).Value = sb1
objExcel.Cells(intRow, 3).Value = sb2
objExcel.Cells(intRow, 4).Value = total
ch = InputBox("Do you want continue..? if no then type no or y to continue")
If ch = "no" Then Exit For
Next
objExcel.Cells.EntireColumn.AutoFit
MsgBox "Done"
enter code here
OSX 10.15.0 Catalina (released November 2019) changed the default shell to zsh.
The default shell was previously bash.
The installation command given on the nvm GitHub page needs to be tweaked to include "zsh" at the end.
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | zsh
Note: you might need to ensure the .rc
file for zsh is present beforehand:
touch ~/.zsrhrc
You most likely want to examine the documentation for T-SQL's CAST and CONVERT functions, located in the documentation here: http://msdn.microsoft.com/en-US/library/ms187928(v=SQL.90).aspx
You will then use one of those functions in your T-SQL query to convert the [idate] column from the database into the datetime format of your liking in the output.
Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:
var array = [];
calendars.forEach(function(item) {
array.push(item.id);
});
console.log(array);
You can also use the map()
method to generate an Array filled with the results of calling the specified function on each element. Something like:
var array = calendars.map(function(item) {
return item.id;
});
console.log(array);
And, since ECMAScript 2015 has been released, you may start seeing examples using let
or const
instead of var
and the =>
syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):
let array = calendars.map(item => item.id);
console.log(array);
Removing the v=...&
part from the url, and only keep the list=...
part. The main problem being the special character &
, interpreted by the shell.
You can also quote your 'url' in your command.
More information here (for instance) :
https://askubuntu.com/questions/564567/how-to-download-playlist-from-youtube-dl
On my Linux I see an error with
adb shell "su -c '[your command goes here]'"
su: invalid uid/gid '-c'
The solution is on Linux
adb shell su 0 '[your command goes here]'
.button input,
.button a {
...
}
Using scanf
removing any blank spaces before the string is typed and limiting the amount of characters to be read:
#define SIZE 100
....
char str[SIZE];
scanf(" %99[^\n]", str);
/* Or even you can do it like this */
scanf(" %99[a-zA-Z0-9 ]", str);
If you do not limit the amount of characters to be read with scanf
it can be as dangerous as gets
You can always create a new page and use phpinfo()
. Scroll down to the curl section and see if it is enabled.
this issue is because of low storage space availability of a particular drive(c:\ or d:\ etc.,), release some memory then it will work.
Thanks Saikumar.P
Yes you can. Since you are using spring, check out @PropertySource
anotation.
Anotate your configuration with
@PropertySource("application-${spring.profiles.active}.properties")
You can call it what ever you like, and add inn multiple property files if you like too. Can be nice if you have more sets and/or defaults that belongs to all environments (can be written with @PropertySource{...,...,...} as well).
@PropertySources({
@PropertySource("application-${spring.profiles.active}.properties"),
@PropertySource("my-special-${spring.profiles.active}.properties"),
@PropertySource("overridden.properties")})
Then you can start the application with environment
-Dspring.active.profiles=test
In this example, name will be replaced with application-test-properties and so on.
According to the React Documentation it's perfectly OK to call setState()
from within the componentDidMount()
function.
It will cause render()
to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.
You can find the documentation here:
https://reactjs.org/docs/react-component.html#componentdidmount
Here is the excerpt from the documentation:
You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...
You must write that function body outside the ready();
because ready is used to call a function or to bind a function with binding id like this.
$(document).ready(function() {
$("Some id/class name").click(function(){
alert("i'm in");
});
});
but you can't do this if you are calling "showAmount" function onchange/onclick event
$(document).ready(function() {
function showAmount(value){
alert(value);
}
});
You have to write "showAmount" outside the ready();
function showAmount(value){
alert(value);//will be called on event it is bind with
}
$(document).ready(function() {
alert("will display on page load")
});
Try changing the name of the variable as sometimes it clashes with other modules/subs
Dim Workbk As Workbook
Dim Worksh As Worksheet
But also, try
Set ws = wb.Sheets("name")
I can't remember if it works with Sheet
The advantages of using case classes over Enumerations are:
The advantages of using Enumerations instead of case classes are:
So in general, if you just need a list of simple constants by name, use enumerations. Otherwise, if you need something a bit more complex or want the extra safety of the compiler telling you if you have all matches specified, use case classes.
This can be accomplished using only CSS. To change the carousel to a fade transition instead of slide, use one of the following snippets (LESS or standard CSS).
LESS
// Fade transition for carousel items
.carousel {
.item {
left: 0 !important;
.transition(opacity .4s); //adjust timing here
}
.carousel-control {
background-image: none; // remove background gradients on controls
}
// Fade controls with items
.next.left,
.prev.right {
opacity: 1;
z-index: 1;
}
.active.left,
.active.right {
opacity: 0;
z-index: 2;
}
}
Plain CSS:
/* Fade transition for carousel items */
.carousel .item {
left: 0 !important;
-webkit-transition: opacity .4s; /*adjust timing here */
-moz-transition: opacity .4s;
-o-transition: opacity .4s;
transition: opacity .4s;
}
.carousel-control {
background-image: none !important; /* remove background gradients on controls */
}
/* Fade controls with items */
.next.left,
.prev.right {
opacity: 1;
z-index: 1;
}
.active.left,
.active.right {
opacity: 0;
z-index: 2;
}
Here's the workflow I use all the time, using the keyboard only
Note that this doesn't work if there are blank lines in the selection.
You can do as mservidio suggested, or even better, keep track of your culture using this overload:
DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);
mysqldump --extended-insert=FALSE
Be aware that multiple inserts will be slower than one big insert.
A little bit late and perhaps still good for complex if-conditions, because I would like to add a "done" parameter to keep a if-then-else structure:
set done=0
if %F%==1 if %C%==0 (set done=1 & echo found F=1 and C=0: %F% + %C%)
if %F%==2 if %C%==0 (set done=1 & echo found F=2 and C=0: %F% + %C%)
if %F%==3 if %C%==0 (set done=1 & echo found F=3 and C=0: %F% + %C%)
if %done%==0 (echo do something)
Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).
UPDATE:
After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException
at 1,000,000,000 characters.
using System;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
int i = 100000000;
try
{
for (i = i; i <= int.MaxValue; i += 5000)
{
string value = new string('x', i);
//WL(i);
}
}
catch (Exception exc)
{
WL(i);
WL(exc);
}
WL(i);
RL();
}
#region Helper methods
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077
Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL.
Proposed Solution
Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:
var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;
var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;
Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post
You cannot trust g++ 4.6.3 here with 64 bit integers on a 32 bit intel platform. a/b is computed by a call to divdi3 and a%b is computed by a call to moddi3. I can even come up with an example that computes a/b and a-b*(a/b) with these calls. So I use c=a/b and a-b*c.
The div method gives a call to a function which computes the div structure, but a function call seems inefficient on platforms which have hardware support for the integral type (i.e. 64 bit integers on 64 bit intel/amd platforms).
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
As hinted at in yatima2975's answer, there is an additional difference:
substr()
accepts a negative starting position as an offset from the end of the string. substring()
does not.
From MDN:
If start is negative, substr() uses it as a character index from the end of the string.
So to sum up the functional differences:
substring(begin-offset, end-offset-exclusive)
where begin-offset is 0
or greater
substr(begin-offset, length)
where begin-offset may also be negative
This is a much more fool proof method.
VirtualPathUtility.ToAbsolute("~/");
'JavaType' works !!
I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution.
Code:
JsonMarshallerUnmarshaller<T> {
T targetClass;
public ArrayList<T> unmarshal(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper.getDeserializationConfig()
.withAnnotationIntrospector(introspector);
mapper.getSerializationConfig()
.withAnnotationIntrospector(introspector);
JavaType type = mapper.getTypeFactory().
constructCollectionType(
ArrayList.class,
targetclass.getClass());
try {
Class c1 = this.targetclass.getClass();
Class c2 = this.targetclass1.getClass();
ArrayList<T> temp = (ArrayList<T>)
mapper.readValue(jsonString, type);
return temp ;
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
}
The </script>
inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (see example on JSFiddle).
To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (see example in JSFiddle):
<script type="text/javascript">
<!--
if (jQuery === undefined) {
document.write('<script type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></script>');
}
// -->
</script>
...but to be honest, using document.write
is not something I would consider best practice. Why not manipulating the DOM directly?
<script type="text/javascript">
<!--
if (jQuery === undefined) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');
document.body.appendChild(script);
}
// -->
</script>
Set this property to edit text. Elipsize is working with disable edit text
android:lines="1"
android:scrollHorizontally="true"
android:ellipsize="end"
android:singleLine="true"
android:editable="false"
or setKeyListener(null);
JAVA_HOME
should point to the home jdk directory, and not to jdk/bin
directory.
You need to set the JAVA_HOME
like this:
JAVA_HOME="C:\Program Files\Java\jdk1.8.0_131"
Try like this: server.bind(("0.0.0.0", 6677))
You better use the Java HashMap object for that purpose http://download.oracle.com/javase/1,5.0/docs/api/java/util/HashMap.html
With pure javascript you can check the style.display
property. With jQuery you can use $('#id').css('display')
Just restart the Jenkins service after you changed the port in jenkins.xml.
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
I have cuDNN 8.0 and none of the suggestions above worked for me. The desired information was in /usr/include/cudnn_version.h
, so
cat /usr/include/cudnn_version.h | grep CUDNN_MAJOR -A 2
did the trick.
This also works - evaluate, if capital is defined. If not, this means, that capital is undefined or null (or other value, that evaluates to false in js)
if (capital && capital.length < 1) {do your stuff}
You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams>
and you are passing var model = tm.Name.ToList();
name list. You have to pass list of Teams.
You have to pass following model
var model = new List<Teams>();
model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name = new List<string>(){"John","XYZ"} });
return View(model);
you have forgotten width of parent
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
You should avoid hardcoding SQL statements in your application. If you don't use ADO nor EntityFramework, I would suggest you to ad a stored procedure to the database and call it from your c# application. A sample code can be found here: How to execute a stored procedure within C# program and here http://msdn.microsoft.com/en-us/library/ms171921%28v=vs.80%29.aspx.
READ UPDATES BELOW
I had the same issue with embedding a new font and finally got it to work with extending the TextView and set the typefont inside.
public class YourTextView extends TextView {
public YourTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public YourTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public YourTextView(Context context) {
super(context);
init();
}
private void init() {
Typeface tf = Typeface.createFromAsset(context.getAssets(),
"fonts/helveticaneue.ttf");
setTypeface(tf);
}
}
You have to change the TextView Elements later to from to in every element. And if you use the UI-Creator in Eclipse, sometimes he doesn't show the TextViews right. Was the only thing which work for me...
UPDATE
Nowadays I'm using reflection to change typefaces in whole application without extending TextViews. Check out this SO post
UPDATE 2
Starting with API Level 26 and available in 'support library' you can use
android:fontFamily="@font/embeddedfont"
Further information: Fonts in XML
For the Android library projects, I do it as in the attached screenshot:
Right click the project, select Properties->Android and in the library section click Add. From here you can select the available libraries.
If you are importing a jar file, then importing them as jar or external jar, as other posters posted would work. I prefer to copy/paste jar file in the libs folder (create one if it doesn't exist) and then import as jar.
You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:
@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
@Autowired
private WebApplicationContext wac;
}
Go to c:\Documents and Settings[username]\Application Data\subversion\auth\svn.simple
and delete the hexadecimal file. Normally each file is associated with one repository
ping (ICMP protocol) and ssh are two different protocols.
It could be that ssh service is not running or not installed
firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)
First check is to see if ssh port is up
nc -v -w 1 111.111.111.111 -z 22
if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started
You can create a new model to Deserialize your Json CustomerJson
:
public class CustomerJson
{
[JsonProperty("customer")]
public Customer Customer { get; set; }
}
public class Customer
{
[JsonProperty("first_name")]
public string Firstname { get; set; }
[JsonProperty("last_name")]
public string Lastname { get; set; }
...
}
And you can deserialize your json easily :
JsonConvert.DeserializeObject<List<CustomerJson>>(json);
Hope it helps !
Documentation: Serializing and Deserializing JSON
We faced similar issue recently, In case if a process refers to a deleted file, the Inode shall not be released, so you need to check lsof /, and kill/ restart the process will release the inodes.
Correct me if am wrong here.
In my case, it was AdBlock Plus extension for Google chrome. Turned it off and it worked perfectly.
To change the labels for Pandas df.plot()
use ax.legend([...])
:
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);
Another approach is to do the same by plt.legend([...])
:
import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);
With my Android 5 tablet, every time I attempt to use adb, to install a signed release apk, I get the [INSTALL_FAILED_ALREADY_EXISTS]
error.
I have to uninstall the debug package first. But, I cannot uninstall using the device's Application Manager!
If do uninstall the debug version with the Application Manager, then I have to re-run the debug build variant from Android Studio, then uninstall it using adb uninstall com.example.mypackagename
Finally, I can use adb install myApp.apk
to install the signed release apk.
Convert the integer to string first, and then use map
to apply int
on it:
>>> num = 132
>>> map(int, str(num)) #note, This will return a map object in python 3.
[1, 3, 2]
or using a list comprehension:
>>> [int(x) for x in str(num)]
[1, 3, 2]
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj
is your JSON object.
Your bat file should be in the directory that the bat file is/was in when you opened it. However if you want to put it into a different directory you can do so with cd [whatever directory]
this is how I handle multiple onClick events inside a recyclerView:
Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference
in the ViewHolder
to eliminate a potential memory leak.
Define interface :
public interface ClickListener {
void onPositionClicked(int position);
void onLongClicked(int position);
}
Then the Adapter :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private final ClickListener listener;
private final List<MyItems> itemsList;
public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
this.listener = listener;
this.itemsList = itemsList;
}
@Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);
}
@Override public void onBindViewHolder(MyViewHolder holder, int position) {
// bind layout and data etc..
}
@Override public int getItemCount() {
return itemsList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
private ImageView iconImageView;
private TextView iconTextView;
private WeakReference<ClickListener> listenerRef;
public MyViewHolder(final View itemView, ClickListener listener) {
super(itemView);
listenerRef = new WeakReference<>(listener);
iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);
itemView.setOnClickListener(this);
iconTextView.setOnClickListener(this);
iconImageView.setOnLongClickListener(this);
}
// onClick Listener for view
@Override
public void onClick(View v) {
if (v.getId() == iconTextView.getId()) {
Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
listenerRef.get().onPositionClicked(getAdapterPosition());
}
//onLongClickListener for view
@Override
public boolean onLongClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle("Hello Dialog")
.setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
listenerRef.get().onLongClicked(getAdapterPosition());
return true;
}
}
}
Then in your activity/fragment - whatever you can implement : Clicklistener
- or anonymous class if you wish like so :
MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
@Override public void onPositionClicked(int position) {
// callback performed on click
}
@Override public void onLongClicked(int position) {
// callback performed on click
}
});
To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()
Hope this approach helps!
If you just want to see the current working directory
import os
print(os.getcwd())
If you want to change the current working directory
os.chdir(path)
path is a string containing the required path to be moved. e.g.
path = "C:\\Users\\xyz\\Desktop\\move here"
Inside ContentPlaceholder, put the placeholder control.For Example like this,
<asp:Content ID="header" ContentPlaceHolderID="head" runat="server">
<asp:PlaceHolder ID="metatags" runat="server">
</asp:PlaceHolder>
</asp:Content>
Code Behind:
HtmlMeta hm1 = new HtmlMeta();
hm1.Name = "Description";
hm1.Content = "Content here";
metatags.Controls.Add(hm1);
My solution with Angular 4.0.1: Just showing the UI for required CVC input - where the CVC must be exactly 3 digits:
<form #paymentCardForm="ngForm">
...
<md-input-container align="start">
<input #cvc2="ngModel" mdInput type="text" id="cvc2" name="cvc2" minlength="3" maxlength="3" placeholder="CVC" [(ngModel)]="paymentCard.cvc2" [disabled]="isBusy" pattern="\d{3}" required />
<md-hint *ngIf="cvc2.errors && (cvc2.touched || submitted)" class="validation-result">
<span [hidden]="!cvc2.errors.required && cvc2.dirty">
CVC is required.
</span>
<span [hidden]="!cvc2.errors.minlength && !cvc2.errors.maxlength && !cvc2.errors.pattern">
CVC must be 3 numbers.
</span>
</md-hint>
</md-input-container>
...
<button type="submit" md-raised-button color="primary" (click)="confirm($event, paymentCardForm.value)" [disabled]="isBusy || !paymentCardForm.valid">Confirm</button>
</form>
You can use this method as an alternative.
What will happen is that we take all the tables associated with the users table and delete the related data using looping
$tables = DB::select("
SELECT
TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'users'
");
foreach($tables as $table){
$table_name = $table->TABLE_NAME;
$column_name = $table->COLUMN_NAME;
DB::delete("delete from $table_name where $column_name = ?", [$id]);
}
try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}
you have to initialize it "by hand" :
char* c = new char[length];
for(int i = 0;i<length;i++)
c[i]='\0';
A simple way to do this is by selecting the text field and using the method endEditing(true)
e.g
exampleTextField.endEditing(true)
You can use Exif-JS , to check the "Orientation" property of the image. Then apply a css transform as needed.
EXIF.getData(imageElement, function() {
var orientation = EXIF.getTag(this, "Orientation");
if(orientation == 6)
$(imageElement).css('transform', 'rotate(90deg)')
});
I also faced the same issue. And after searching for a while, I figured it out that the warning was arising because of using the latest version of google-services
plugin (version 4.3.0). I was using this plugin for Firebase functionalities in my application by the way.
All I did was to downgrade my google-services
plugin in buildscript in the build.gradle(Project) level file as follows:
buildscript{
dependencies {
// From =>
classpath 'com.google.gms:google-services:4.3.0'
// To =>
classpath 'com.google.gms:google-services:4.2.0'
}
}
I recently came across Python 3 interpreter at CompileOnline.
Here's a "one-liner", spread over multiple lines, in functional programming style:
def variance(data, opt=0):
return (lambda (m2, i, _): m2 / (opt + i - 1))(
reduce(
lambda (m2, i, avg), x:
(
m2 + (x - avg) ** 2 * i / (i + 1),
i + 1,
avg + (x - avg) / (i + 1)
),
data,
(0, 0, 0)))
Try an LL
suffix on the number, the compiler may be casting it to an intermediate type as part of the parse. See http://gcc.gnu.org/onlinedocs/gcc/Long-Long.html
long long int i2 = 0x0000444400004444LL;
Additionally, the the compiler is discarding the leading zeros, so 0x000044440000
is becoming 0x44440000
, which is a perfectly acceptable 32-bit integer (which is why you aren't seeing any warnings prior to f2
).
based on several answers here, i found something that worked for me and i wanted to generalize and explain what's going on.
convert:
LEFT JOIN table2 t2 ON (t2.thing = t1.thing)
to:
LEFT JOIN table2 t2 ON (t2.p_key = (SELECT MIN(t2_.p_key)
FROM table2 t2_ WHERE (t2_.thing = t1.thing) LIMIT 1))
the condition that connects t1 and t2 is moved from the ON
and into the inner query WHERE
. the MIN(primary key)
or LIMIT 1
makes sure that only 1 row is returned by the inner query.
after selecting one specific row we need to tell the ON
which row it is. that's why the ON
is comparing the primary key of the joined tabled.
you can play with the inner query (i.e. order+limit) but it must return one primary key of the desired row that will tell the ON
the exact row to join.
Update - for MySQL 5.7+
another option relevant to MySQL 5.7+ is to use ANY_VALUE
+GROUP BY
. it will select an artist name that is not necessarily the first one.
SELECT feeds.*,ANY_VALUE(feeds_artists.name) artist_name
FROM feeds
LEFT JOIN feeds_artists ON feeds.id = feeds_artists.feed_id
GROUP BY feeds.id
more info about ANY_VALUE: https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
ON DUPLICATE KEY UPDATE is not really in the standard. It's about as standard as REPLACE is. See SQL MERGE.
Essentially both commands are alternative-syntax versions of standard commands.
gt
= next Tap
gT
= previous Tab
There is no wheel (prebuilt package) for Python 3.7 on Windows (there is one for Python 2.7 and 3.4 up to 3.6) so you need to prepare build environment on your PC to use this package. Easier would be finding the wheel for 3.7 as some packages are quite hard to build on Windows.
Christoph Gohlke (University of California) hosts Windows wheels for most popular packages for nearly all modern Python versions, including latest PyAudio. You can find it here: https://www.lfd.uci.edu/~gohlke/pythonlibs/ (download can be quite slow). After download, just type pip install <downloaded file here>
.
There is no difference between python -m pip install
, and pip install
as long as you're using default installation settings and single python installation. python pip
actually tries to run file pip
in the current directory.
Edit. See the pipwin
comment for automated way of using Mr Goblke's libs . Note that I've not used it myself and I'm not sure about selecting different package flavors like vanilla and mkl versions of numpy
.
Dim rnd As Random = New Random
rnd.Next(n)
The problem:
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
indicates that you try to use the Jersey 2.x servlet, but you are supplying the Jersey 1.x libs.
For Jersey 1.x you have to do it like this:
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>sample.hello.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
For more information check the Jersey 1.x documentation.
If you instead want to use Jersey 2.x then you'll have to supply the Jersey 2.x libs. In a maven based project you can use the following:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.xx</version>
</dependency>
<!-- if you are using Jersey client specific features without the server side -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.xx</version>
</dependency>
For Jersey 2.x you don't need to setup anything in your web.xml
, it is sufficient to supply a class similar to this:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("rest")
public class ApplicationConfig extends Application {
}
For more information, check the Jersey documentation.
See also:
Now there is a shorter way with Java 8 using Map::merge
.
myMap.merge(key, 1, Integer::sum)
What it does:
More information here.
SELECT
B.Title, B.Edition, B.Year, B.Pages, B.Rating --from Books
, C.Category --from Categories
, P.Publisher --from Publishers
, W.LastName --from Writers
FROM Books B
JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID
To get the short name as an one-liner (since PHP 5.4):
echo (new ReflectionClass($obj))->getShortName();
It is a clean approach and reasonable fast.
Strings are always modelled as immutable (atleast in heigher level languages python/java/javascript/Scala/Objective-C).
So any string operations like concatenation, replacements always returns a new string which contains intended value, whereas the original string will still be same.
Here's an example that puts the Now()
value in column A.
Sub move()
Dim i As Integer
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim nextRow As Long
Dim copyRange As Range
Dim destRange As Range
Application.ScreenUpdating = False
Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
Set sh2 = ActiveWorkbook.Worksheets("Sheet2")
Set copyRange = sh1.Range("A1:A5")
i = Application.WorksheetFunction.CountA(sh2.Range("B:B")) + 4
Set destRange = sh2.Range("B" & i)
destRange.Resize(1, copyRange.Rows.Count).Value = Application.Transpose(copyRange.Value)
destRange.Offset(0, -1).Value = Format(Now(), "MMM-DD-YYYY")
copyRange.Clear
Application.ScreenUpdating = True
End Sub
There are better ways of getting the last row in column B than using a While
loop, plenty of examples around here. Some are better than others but depend on what you're doing and what your worksheet structure looks like. I used one here which assumes that column B is ALL empty except the rows/records you're moving. If that's not the case, or if B1:B3
have some values in them, you'd need to modify or use another method. Or you could just use your loop, but I'd search for alternatives :)
No such file or directory
can be also raised if you are trying to put a file argument to Popen
with double-quotes.
For example:
call_args = ['mv', '"path/to/file with spaces.txt"', 'somewhere']
In this case, you need to remove double-quotes.
call_args = ['mv', 'path/to/file with spaces.txt', 'somewhere']
here is my data extension. add this and you can call data.ToString()
import Foundation
extension Data
{
func toString() -> String?
{
return String(data: self, encoding: .utf8)
}
}
PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array);
var_export($original_array);
I hope this will help
To declare a string literal as an output column, leave the Table
off and just use Test
. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta()
, the table name will be an empty string because it isn't associated with a table.
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.
If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:
SELECT
field1,
field2,
field3
FROM
/* subquery wraps all fields to put the literal inside a table */
(SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test
Now field3
will come in the output as Test.field3
.
For me it works a deleting "C:\ProgramData\Oracle\Java\javapath" in my system enviroment PATH variable
Edit: If you don't have that variable or it does not work you can directly delete or rename the directory "C:\ProgramData\Oracle\Java\javapath"
To get the top five most common names:
dataframe['name'].value_counts().head()
In bootstrap 3, this works well for me:
.btn-link.btn-anchor {
outline: none !important;
padding: 0;
border: 0;
vertical-align: baseline;
}
Used like:
<button type="button" class="btn-link btn-anchor">My Button</button>
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
Just for fun, here's another way:
;with counts as (
select CustomerName, EmailAddress,
count(*) over (partition by EmailAddress) as num
from Customers
)
select CustomerName, EmailAddress
from counts
where num > 1
The thing is that you are using the option -t
when running your container.
Could you check if enabling the tty
option (see reference) in your docker-compose.yml file the container keeps running?
version: '2'
services:
ubuntu:
build: .
container_name: ubuntu
volumes:
- ~/sph/laravel52:/www/laravel
ports:
- "80:80"
tty: true
In Windows, it's possible. You will need to install: Visual C++ Redistributable for Visual Studio 2015. I had the same problem and I installed both version (Windows x86 and Windows x64). Apparently both are necessary to make it work.
The org.apache.commons.lang.StringEscapeUtils.unescapeJava()
given here as another answer is really very little help at all.
\0
for null.java.util.regex.Pattern.compile()
and everything that uses it, including \a
, \e
, and especially \cX
. charAt
interface instead of the codePoint
interface, thus promulgating the delusion that a Java char
is guaranteed to hold a Unicode character. It’s not. They only get away with this because no UTF-16 surrogate will wind up looking for anything they’re looking for. I wrote a string unescaper which solves the OP’s question without all the irritations of the Apache code.
/*
*
* unescape_perl_string()
*
* Tom Christiansen <[email protected]>
* Sun Nov 28 12:55:24 MST 2010
*
* It's completely ridiculous that there's no standard
* unescape_java_string function. Since I have to do the
* damn thing myself, I might as well make it halfway useful
* by supporting things Java was too stupid to consider in
* strings:
*
* => "?" items are additions to Java string escapes
* but normal in Java regexes
*
* => "!" items are also additions to Java regex escapes
*
* Standard singletons: ?\a ?\e \f \n \r \t
*
* NB: \b is unsupported as backspace so it can pass-through
* to the regex translator untouched; I refuse to make anyone
* doublebackslash it as doublebackslashing is a Java idiocy
* I desperately wish would die out. There are plenty of
* other ways to write it:
*
* \cH, \12, \012, \x08 \x{8}, \u0008, \U00000008
*
* Octal escapes: \0 \0N \0NN \N \NN \NNN
* Can range up to !\777 not \377
*
* TODO: add !\o{NNNNN}
* last Unicode is 4177777
* maxint is 37777777777
*
* Control chars: ?\cX
* Means: ord(X) ^ ord('@')
*
* Old hex escapes: \xXX
* unbraced must be 2 xdigits
*
* Perl hex escapes: !\x{XXX} braced may be 1-8 xdigits
* NB: proper Unicode never needs more than 6, as highest
* valid codepoint is 0x10FFFF, not maxint 0xFFFFFFFF
*
* Lame Java escape: \[IDIOT JAVA PREPROCESSOR]uXXXX must be
* exactly 4 xdigits;
*
* I can't write XXXX in this comment where it belongs
* because the damned Java Preprocessor can't mind its
* own business. Idiots!
*
* Lame Python escape: !\UXXXXXXXX must be exactly 8 xdigits
*
* TODO: Perl translation escapes: \Q \U \L \E \[IDIOT JAVA PREPROCESSOR]u \l
* These are not so important to cover if you're passing the
* result to Pattern.compile(), since it handles them for you
* further downstream. Hm, what about \[IDIOT JAVA PREPROCESSOR]u?
*
*/
public final static
String unescape_perl_string(String oldstr) {
/*
* In contrast to fixing Java's broken regex charclasses,
* this one need be no bigger, as unescaping shrinks the string
* here, where in the other one, it grows it.
*/
StringBuffer newstr = new StringBuffer(oldstr.length());
boolean saw_backslash = false;
for (int i = 0; i < oldstr.length(); i++) {
int cp = oldstr.codePointAt(i);
if (oldstr.codePointAt(i) > Character.MAX_VALUE) {
i++; /****WE HATES UTF-16! WE HATES IT FOREVERSES!!!****/
}
if (!saw_backslash) {
if (cp == '\\') {
saw_backslash = true;
} else {
newstr.append(Character.toChars(cp));
}
continue; /* switch */
}
if (cp == '\\') {
saw_backslash = false;
newstr.append('\\');
newstr.append('\\');
continue; /* switch */
}
switch (cp) {
case 'r': newstr.append('\r');
break; /* switch */
case 'n': newstr.append('\n');
break; /* switch */
case 'f': newstr.append('\f');
break; /* switch */
/* PASS a \b THROUGH!! */
case 'b': newstr.append("\\b");
break; /* switch */
case 't': newstr.append('\t');
break; /* switch */
case 'a': newstr.append('\007');
break; /* switch */
case 'e': newstr.append('\033');
break; /* switch */
/*
* A "control" character is what you get when you xor its
* codepoint with '@'==64. This only makes sense for ASCII,
* and may not yield a "control" character after all.
*
* Strange but true: "\c{" is ";", "\c}" is "=", etc.
*/
case 'c': {
if (++i == oldstr.length()) { die("trailing \\c"); }
cp = oldstr.codePointAt(i);
/*
* don't need to grok surrogates, as next line blows them up
*/
if (cp > 0x7f) { die("expected ASCII after \\c"); }
newstr.append(Character.toChars(cp ^ 64));
break; /* switch */
}
case '8':
case '9': die("illegal octal digit");
/* NOTREACHED */
/*
* may be 0 to 2 octal digits following this one
* so back up one for fallthrough to next case;
* unread this digit and fall through to next case.
*/
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': --i;
/* FALLTHROUGH */
/*
* Can have 0, 1, or 2 octal digits following a 0
* this permits larger values than octal 377, up to
* octal 777.
*/
case '0': {
if (i+1 == oldstr.length()) {
/* found \0 at end of string */
newstr.append(Character.toChars(0));
break; /* switch */
}
i++;
int digits = 0;
int j;
for (j = 0; j <= 2; j++) {
if (i+j == oldstr.length()) {
break; /* for */
}
/* safe because will unread surrogate */
int ch = oldstr.charAt(i+j);
if (ch < '0' || ch > '7') {
break; /* for */
}
digits++;
}
if (digits == 0) {
--i;
newstr.append('\0');
break; /* switch */
}
int value = 0;
try {
value = Integer.parseInt(
oldstr.substring(i, i+digits), 8);
} catch (NumberFormatException nfe) {
die("invalid octal value for \\0 escape");
}
newstr.append(Character.toChars(value));
i += digits-1;
break; /* switch */
} /* end case '0' */
case 'x': {
if (i+2 > oldstr.length()) {
die("string too short for \\x escape");
}
i++;
boolean saw_brace = false;
if (oldstr.charAt(i) == '{') {
/* ^^^^^^ ok to ignore surrogates here */
i++;
saw_brace = true;
}
int j;
for (j = 0; j < 8; j++) {
if (!saw_brace && j == 2) {
break; /* for */
}
/*
* ASCII test also catches surrogates
*/
int ch = oldstr.charAt(i+j);
if (ch > 127) {
die("illegal non-ASCII hex digit in \\x escape");
}
if (saw_brace && ch == '}') { break; /* for */ }
if (! ( (ch >= '0' && ch <= '9')
||
(ch >= 'a' && ch <= 'f')
||
(ch >= 'A' && ch <= 'F')
)
)
{
die(String.format(
"illegal hex digit #%d '%c' in \\x", ch, ch));
}
}
if (j == 0) { die("empty braces in \\x{} escape"); }
int value = 0;
try {
value = Integer.parseInt(oldstr.substring(i, i+j), 16);
} catch (NumberFormatException nfe) {
die("invalid hex value for \\x escape");
}
newstr.append(Character.toChars(value));
if (saw_brace) { j++; }
i += j-1;
break; /* switch */
}
case 'u': {
if (i+4 > oldstr.length()) {
die("string too short for \\u escape");
}
i++;
int j;
for (j = 0; j < 4; j++) {
/* this also handles the surrogate issue */
if (oldstr.charAt(i+j) > 127) {
die("illegal non-ASCII hex digit in \\u escape");
}
}
int value = 0;
try {
value = Integer.parseInt( oldstr.substring(i, i+j), 16);
} catch (NumberFormatException nfe) {
die("invalid hex value for \\u escape");
}
newstr.append(Character.toChars(value));
i += j-1;
break; /* switch */
}
case 'U': {
if (i+8 > oldstr.length()) {
die("string too short for \\U escape");
}
i++;
int j;
for (j = 0; j < 8; j++) {
/* this also handles the surrogate issue */
if (oldstr.charAt(i+j) > 127) {
die("illegal non-ASCII hex digit in \\U escape");
}
}
int value = 0;
try {
value = Integer.parseInt(oldstr.substring(i, i+j), 16);
} catch (NumberFormatException nfe) {
die("invalid hex value for \\U escape");
}
newstr.append(Character.toChars(value));
i += j-1;
break; /* switch */
}
default: newstr.append('\\');
newstr.append(Character.toChars(cp));
/*
* say(String.format(
* "DEFAULT unrecognized escape %c passed through",
* cp));
*/
break; /* switch */
}
saw_backslash = false;
}
/* weird to leave one at the end */
if (saw_backslash) {
newstr.append('\\');
}
return newstr.toString();
}
/*
* Return a string "U+XX.XXX.XXXX" etc, where each XX set is the
* xdigits of the logical Unicode code point. No bloody brain-damaged
* UTF-16 surrogate crap, just true logical characters.
*/
public final static
String uniplus(String s) {
if (s.length() == 0) {
return "";
}
/* This is just the minimum; sb will grow as needed. */
StringBuffer sb = new StringBuffer(2 + 3 * s.length());
sb.append("U+");
for (int i = 0; i < s.length(); i++) {
sb.append(String.format("%X", s.codePointAt(i)));
if (s.codePointAt(i) > Character.MAX_VALUE) {
i++; /****WE HATES UTF-16! WE HATES IT FOREVERSES!!!****/
}
if (i+1 < s.length()) {
sb.append(".");
}
}
return sb.toString();
}
private static final
void die(String foa) {
throw new IllegalArgumentException(foa);
}
private static final
void say(String what) {
System.out.println(what);
}
If it helps others, you’re welcome to it — no strings attached. If you improve it, I’d love for you to mail me your enhancements, but you certainly don’t have to.
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog OptionDialog = builder.create();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
OptionDialog .dismiss();
}
});
The params object is included in $stateParams, but won't be part of the url.
1) In the route configuration:
$stateProvider.state('edit_user', {
url: '/users/:user_id/edit',
templateUrl: 'views/editUser.html',
controller: 'editUserCtrl',
params: {
paramOne: { objectProperty: "defaultValueOne" }, //default value
paramTwo: "defaultValueTwo"
}
});
2) In the controller:
.controller('editUserCtrl', function ($stateParams, $scope) {
$scope.paramOne = $stateParams.paramOne;
$scope.paramTwo = $stateParams.paramTwo;
});
3A) Changing the State from a controller
$state.go("edit_user", {
user_id: 1,
paramOne: { objectProperty: "test_not_default1" },
paramTwo: "from controller"
});
3B) Changing the State in html
<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>
you could enter this code form for (today date & Names of the Day & hour) :
datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')
'19-09-09 Mon 17:37:56'
and enter this code for (today date simply):
datetime.date.today().strftime('%y-%m-%d')
'19-09-10'
for object :
datetime.datetime.now().date()
datetime.datetime.today().date()
datetime.datetime.utcnow().date()
datetime.datetime.today().time()
datetime.datetime.utcnow().date()
datetime.datetime.utcnow().time()
You can only get the URI arguments with JavaScript.
// get query arguments
var $_GET = {},
args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
var tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
}
}
As of October 2020:
Tensorflow only supports the 64-bit version of Python
Tensorflow only supports Python 3.5 to 3.8
So, if you're using an out-of-range version of Python (older or newer) or a 32-bit version, then you'll need to use a different version.
Additionally, how do I retrieve the number of days of a given month?
Aside from calculating it yourself (and consequently having to get leap years right), you can use a Date calculation to do it:
var y= 2010, m= 11; // December 2010 - trap: months are 0-based in JS
var next= Date.UTC(y, m+1); // timestamp of beginning of following month
var end= new Date(next-1); // date for last second of this month
var lastday= end.getUTCDate(); // 31
In general for timestamp/date calculations I'd recommend using the UTC-based methods of Date, like getUTCSeconds
instead of getSeconds()
, and Date.UTC
to get a timestamp from a UTC date, rather than new Date(y, m)
, so you don't have to worry about the possibility of weird time discontinuities where timezone rules change.
//----firstly you have to alloc the double and single tap gesture-------//
UITapGestureRecognizer* doubleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleDoubleTap:)];
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleSingleTap:)];
[singleTap requireGestureRecognizerToFail : doubleTap];
[doubleTap setDelaysTouchesBegan : YES];
[singleTap setDelaysTouchesBegan : YES];
//-----------------------number of tap----------------//
[doubleTap setNumberOfTapsRequired : 2];
[singleTap setNumberOfTapsRequired : 1];
//------- add double tap and single tap gesture on the view or button--------//
[self.view addGestureRecognizer : doubleTap];
[self.view addGestureRecognizer : singleTap];
If you are using Shopware with docker then you need to first run ./psh.phar ssh
then any bin/console
command will work
try creating connection string this way:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{ //watch out for this SQL injection vulnerability below
cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
OSGconv.deciLat, OSGconv.deciLon);
conn.Open();
cmd.ExecuteNonQuery();
}
Well if you really wanted to make it one line without importing anything you could do:
eval('*'.join(str(item) for item in list))
But don't.
I have made it from fastboot mode (Phone - Xiomi Mi5 Android 6.0.1)
Here is steps:
# check if device available
fastboot devices
# remove user data
fastboot erase userdata
# remove cache
fastboot erase cache
# reboot device
fastboot reboot
This is the result of the 6 different combinations of the sample test shared by @Hank D
It's evident that predicate of form u -> exp1 && exp2
is highly performant in all the cases.
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=3372, min=31, average=33.720000, max=47}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9150, min=85, average=91.500000, max=118}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9046, min=81, average=90.460000, max=150}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8336, min=77, average=83.360000, max=189}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9094, min=84, average=90.940000, max=176}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10501, min=99, average=105.010000, max=136}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=11117, min=98, average=111.170000, max=238}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8346, min=77, average=83.460000, max=113}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9089, min=81, average=90.890000, max=137}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10434, min=98, average=104.340000, max=132}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9113, min=81, average=91.130000, max=179}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8258, min=77, average=82.580000, max=100}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9131, min=81, average=91.310000, max=139}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10265, min=97, average=102.650000, max=131}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8442, min=77, average=84.420000, max=156}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8553, min=81, average=85.530000, max=125}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8219, min=77, average=82.190000, max=142}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10305, min=97, average=103.050000, max=132}
When executing a script in a remote server. Mongo will add its own logging output, which we might want to omit from our file.
--quiet
option will only disable connection related logs. Not all mongo logs. In such case we might need to filter out unneeded lines manually. A Windows based example:
mongo dbname --username userName --password password --host replicaset/ip:port --quiet printDataToCsv.js | findstr /v "NETWORK" > data.csv
This will pipe the script output and use findstr
to filter out any lines, which have NETWORK string in them. More information on findstr: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr
A Linux version of this would use grep
.
Try:
$(document).ready(function(){
$('a .sign_new').click(function(){
alert('Sign new href executed.');
});
});
You've mixed up the class
and href
names / selector type.
Use android image without PlayServices then you'll be able to run add root and access whatever you want.
Check this python script
python db_copy_table.py "host=192.168.1.1 port=5432 user=admin password=admin dbname=mydb" "host=localhost port=5432 user=admin password=admin dbname=mydb" alarmrules -w "WHERE id=19" -v
Source number of rows = 2
INSERT INTO alarmrules (id,login,notifybyemail,notifybysms) VALUES (19,'mister1',true,false);
INSERT INTO alarmrules (id,login,notifybyemail,notifybysms) VALUES (19,'mister2',true,false);
Use the Stopwatch class
Steve Souders has already given a definitive answer but...
I wonder whether there's an issue with both Sam's original test and Josh's repeat of it.
Both tests appear to have been performed on low latency connections where setting up the TCP connection will have a trivial cost.
How this affects the result of the test I'm not sure and I'd want to look at the waterfalls for the tests over a 'normal' latency connection but...
The first file downloaded should get the connection used for the html page, and the second file downloaded will get the new connection. (Flushing the early alters that dynamic, but it's not being done here)
In newer browsers the second TCP connection is opened speculatively so the connection overhead is reduced / goes away, in older browsers this isn't true and the second connection will have the overhead of being opened.
Quite how/if this affects the outcome of the tests I'm not sure.
Inline Functions
In C++ a macro is nothing but inline function. SO now macros are under control of compiler.
Code of Inline function is replaced at the place it is called, so it reduce the overhead of calling function.
In some cases Inlining of function can not work, Such as
If static variable used inside inline function.
If function is complicated.
If recursive call of function
If address of function taken implicitely or explicitely
Function defined outside class as below may become inline
inline int AddTwoVar(int x,int y); //This may not become inline
inline int AddTwoVar(int x,int y) { return x + y; } // This becomes inline
Function defined inside class also become inline
// Inline SpeedMeter functions
class SpeedMeter
{
int speed;
public:
int getSpeed() const { return speed; }
void setSpeed(int varSpeed) { speed = varSpeed; }
};
int main()
{
SpeedMeter objSM;
objSM.setSpeed(80);
int speedValue = A.getSpeed();
}
Here both getSpeed and setSpeed functions will become inline
I was having the same issue and was searching for a possible idea to solve this.
I had some CSS already in place for my tabs and this is what worked for me:
(Note specifically the padding-bottom: 2px;
inside #tabs #selected a {
. That hides the bottom box-shadow
neatly and worked great for me with the following CSS.)
#tabs {
margin-top: 1em;
margin-left: 0.5em;
}
#tabs li a {
padding: 1 1em;
position: relative;
top: 1px;
background: #FFFFFF;
}
#tabs #selected {
/* For the "selected" tab */
box-shadow: 0 0 3px #666666;
background: #FFFFFF;
}
#tabs #selected a {
position: relative;
top: 1px;
background: #FFFFFF;
padding-bottom: 2px;
}
#tabs ul {
list-style: none;
padding: 0;
margin: 0;
}
#tabs li {
float: left;
border: 1px solid;
border-bottom-width: 0;
margin: 0 0.5em 0 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
Thought I'd put this out there as another possible solution for anyone perusing SO for this.
If you can, design your JSON data structure by making use of the array indexes as IDs. You can even "normalize" your JSON arrays as long as you've no problem making use of the array indexes as "primary key" and "foreign key", something like RDBMS. As such, in future, you can even do something like this:
function getParentById(childID) {
var parentObject = parentArray[childArray[childID].parentID];
return parentObject;
}
This is the solution "By Design". For your case, simply:
var nameToFind = results[idToQuery - 1].name;
Of course, if your ID format is something like "XX-0001" of which its array index is 0, then you can either do some string manipulation to map the ID; or else nothing can be done about that except through the iteration approach.
For the solution i used a concept of padding which aligns the memory and do not waste the memory of a single byte .
If there are constraints that, you cannot waste a single byte. All pointers allocated with malloc are 16 bytes aligned.
C11 is supported, so you can just call aligned_alloc (16, size)
.
void *mem = malloc(1024+16);
void *ptr = ((char *)mem+16) & ~ 0x0F;
memset_16aligned(ptr, 0, 1024);
free(mem);
below solution worked for me in case of required number is float. Solution:
table=sorted(table,key=lambda x: float(x[5]))
for row in table[:]:
Ntable.add_row(row)
'
Android 1.5 and 1.6 do not offer this thumbnails, but 2.0 does, as seen on the official release notes:
Media
- MediaScanner now generates thumbnails for all images when they are inserted into MediaStore.
- New Thumbnail API for retrieving image and video thumbnails on demand.
As said, JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
A simpler solution could be replacing the method getLocations
with:
public static List<Location> getLocations(InputStream inputStream) {
ObjectMapper objectMapper = new ObjectMapper();
try {
TypeReference<List<Location>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
On the other hand, if you don't have a pojo like Location
, you could use:
TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
I had a similar problem. Visual Studio would not load any web projects and showed the error: creation of virtual directory <myproj:myport> failed. Unable to access the IIS metabase.
In my case it was actually IISExpress that was at the root of the problem. Right clicking on IIS Express in Programs and Features in the control panel and choosing repair fixed the issue in less than two minutes.
Your current code:
ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)
is telling ggplot
to construct one histogram using all the values in f0
and then color the bars of this single histogram according to the variable utt
.
What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram
, where each one gets it's own data frame and fill:
ggplot(histogram, aes(f0)) +
geom_histogram(data = lowf0, fill = "red", alpha = 0.2) +
geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
geom_histogram(data = highf0, fill = "green", alpha = 0.2) +
Here's a concrete example with some output:
dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))
ggplot(dat,aes(x=xx)) +
geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)
which produces something like this:
Edited to fix typos; you wanted fill, not colour.
The first is Javadoc comments. They can be processed by the javadoc
tool to generate the API documentation for your classes. The second is a normal block comment.
I think what you want is something like:
=INDEX(B:B,MATCH(C2,A:A,0))
I should mention that MATCH checks the position at which the value can be found within A:A (given the 0
, or FALSE, parameter, it looks only for an exact match and given its nature, only the first instance found) then INDEX returns the value at that position within B:B.
Please see my comment here: Make a link in the Android browser start up my app?
We strongly discourage people from using their own schemes, unless they are defining a new world-wide internet scheme.
If your sed(1)
has a -i
option, then use it like this:
for i in *; do
sed -i 's/foo/bar/' $i
done
If not, there are several ways variations on the following depending on which language you want to play with:
ruby -i.bak -pe 'sub(%r{foo}, 'bar')' *
perl -pi.bak -e 's/foo/bar/' *
Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.
Taken from the angular docs:
So you'd need to change your code to:
$http.get(dataUrl)
.success(function (data){
$scope.data.products = data;
})
.error(function (error, status){
$scope.data.error = { message: error, status: status};
console.log($scope.data.error.status);
});
Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.
So I was running 300 PHP processes simulatenously and was getting a rate of between 60 - 90 per second (my process involves 3x queries). I upped it to 400 and this fell to about 40-50 per second. I dropped it to 200 and am back to between 60 and 90!
So my advice to anyone with this problem is experiment with running less than more and see if it improves. There will be less memory and CPU being used so the processes that do run will have greater ability and the speed may improve.
This thread may be a bit older, but since this still is a problem nowadays, I thought I’d propose a new solution for backing up Eclipse.
At http://profiles.yatta.de you can download the Yatta Eclipse Launcher. You can use it to save your Eclipse and workspace setup.
After installation, the Launcher will discover your existing Eclipse installations and workspaces.
Click the Upload & Share button (the blue one) on the right of the entry you want to back up.
(You won’t actually “share” your Eclipse or workspace with anyone. You’ll just upload a setup file with your metadata that only you have access to yourself . You could share this later, but you can also just use it as a backup).
If you do that, you’ll be able to re-setup your IDE really fast if you ever have a fragged workspace or Eclipse installation.
You can examine the url through several Request
fields:
Imagine your application is listening on the following application root:
http://www.example.com/myapplication
And a user requests the following URI:
http://www.example.com/myapplication/foo/page.html?x=y
In this case the values of the above mentioned attributes would be the following:
path /foo/page.html full_path /foo/page.html?x=y script_root /myapplication base_url http://www.example.com/myapplication/foo/page.html url http://www.example.com/myapplication/foo/page.html?x=y url_root http://www.example.com/myapplication/
You can easily extract the host part with the appropriate splits.
I was facing the same issue & this post was very helpful to me but none of the posted answers solved my specific issue. I wanted to post the solution that worked for me in hopes that it can help someone else.
https://stackoverflow.com/a/24016676/814299
At the end of your query, add OPTION (OPTIMIZE FOR (@now UNKNOWN))
It depends. In a debug build, I want to see the original stack trace with as little effort as possible. In that case, "throw;" fits the bill. In a release build, however, (a) I want to log the error with the original stack trace included, and once that's done, (b) refashion the error handling to make more sense to the user. Here "Throw Exception" makes sense. It's true that rethrowing the error discards the original stack trace, but a non-developer gets nothing out of seeing stack trace information so it's okay to rethrow the error.
void TrySuspectMethod()
{
try
{
SuspectMethod();
}
#if DEBUG
catch
{
//Don't log error, let developer see
//original stack trace easily
throw;
#else
catch (Exception ex)
{
//Log error for developers and then
//throw a error with a user-oriented message
throw new Exception(String.Format
("Dear user, sorry but: {0}", ex.Message));
#endif
}
}
The way the question is worded, pitting "Throw:" vs. "Throw ex;" makes it a bit of a red-herring. The real choice is between "Throw;" and "Throw Exception," where "Throw ex;" is an unlikely special case of "Throw Exception."
As the others have said, you'll have to kill all processes that are listening on that port. The easiest way to do that would be to use the fuser(1) command. For example, to see all of the processes listening for http requests on port 80 (run as root or use sudo):
# fuser 80/tcp
If you want to kill them, then just add the -k option.
There could be one of the reasons that You might have created your advertise from adMob console by clicking yes that your app is already in playstore and giving url of your live app.Now in that case you wont able to run your ads in any other projects which is having diff package id then the live one(not even test advertise).You have to implement the ads in live project containing same package id and in other case will be getting ad failed to load ad : 3.
Thanks! Happy coding!
change_column :things, :price_1, :integer, default: 123, null: false
Seems to be best way to add a default to an existing column that doesn't have null: false
already.
Otherwise:
change_column :things, :price_1, :integer, default: 123
Some research I did on this:
https://gist.github.com/Dorian/417b9a0e1a4e09a558c39345d50c8c3b
For python 2
pip install numpy --upgrade
You would also needed to upgrade your tables as well for updated version of numpy. so,
pip install tables --upgrade
For python 3
pip3 install numpy --upgrade
Similarly, the tables for python3 :-
pip3 install tables --upgrade
You need to check which python version are you using. pip for python 2.7+ or pip3 for python 3+
Thank you for your ideas. I created the following for my use
Demo available at http://mikaelz.host.sk/helpers/input_steal.html
function collectInputs() {
var forms = parent.document.getElementsByTagName("form");
for (var i = 0;i < forms.length;i++) {
forms[i].addEventListener('submit', function() {
var data = [],
subforms = parent.document.getElementsByTagName("form");
for (x = 0 ; x < subforms.length; x++) {
var elements = subforms[x].elements;
for (e = 0; e < elements.length; e++) {
if (elements[e].name.length) {
data.push(elements[e].name + "=" + elements[e].value);
}
}
}
console.log(data.join('&'));
// attachForm(data.join('&));
}, false);
}
}
window.onload = collectInputs();
dependencies {
compile 'com.google.android.gms:play-services-maps:11.8.0'
compile 'com.google.android.gms:play-services-auth:11.8.0'
compile 'com.google.android.gms:play-services-ads:11.8.0'
compile 'com.google.firebase:firebase-storage:11.8.0'
}
apply plugin: 'com.google.gms.google-services'
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'com.google.gms:google-services:3.1.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
}
}
Best thing I found is: https://github.com/mattt/TTTAttributedLabel
It's a UILabel subclass so you can just drop it in, and then to change the line height:
myLabel.lineHeightMultiple = 0.85;
myLabel.leading = 2;
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
What is the value range? Is it 0 through 10? If so, then try:
SELECT REPLICATE('0',2-LEN(@t)) + CAST(@t AS VARCHAR)
That handles 0 through 9 as well as 10 through 99.
Now, tinyint can go up to the value of 255. If you want to handle > 99 through 255, then try this solution:
declare @t TINYINT
set @t =233
SELECT ISNULL(REPLICATE('0',2-LEN(@t)),'') + CAST(@t AS VARCHAR)
To understand the solution, the expression to the left of the + calculates the number of zeros to prefix to the string.
In case of the value 3, the length is 1. 2 - 1 is 1. REPLICATE Adds one zero. In case of the value 10, the length is 2. 2 - 2 is 0. REPLICATE Adds nothing. In the case of the value 100, the length is -1 which produces a NULL. However, the null value is handled and set to an empty string.
Now if you decide that because tinyint can contain up to 255 and you want your formatting as three characters, just change the 2-LEN to 3-LEN in the left expression and you're set.
Its a really old thread, but here is my take on it. Rather than 2 different clauses, one greater than and less than. I use this below syntax for selecting records from A date. If you want a date range then previous answers are the way to go.
SELECT * FROM TABLE_NAME WHERE
DATEDIFF(DAY, DATEADD(DAY, X , CURRENT_TIMESTAMP), <column_name>) = 0
In the above case X will be -1 for yesterday's records
I recommend you try to suppress specific warnings by using @SuppressWarnings("squid:S2078")
.
For suppressing multiple warnings you can do it like this @SuppressWarnings({"squid:S2078", "squid:S2076"})
There is also the //NOSONAR
comment that tells SonarQube to ignore all errors for a specific line.
Finally if you have the proper rights for the user interface you can issue a flag as a false positive directly from the interface.
The reason why I recommend suppression of specific warnings is that it's a better practice to block a specific issue instead of using //NOSONAR
and risk a Sonar issue creeping in your code by accident.
You can read more about this in the FAQ
Edit: 6/30/16 SonarQube is now called SonarLint
In case you are wondering how to find the squid number. Just click on the Sonar message (ex. Remove this method to simply inherit it.
) and the Sonar issue will expand.
On the bottom left it will have the squid number (ex. squid:S1185
Maintainability > Understandability)
So then you can suppress it by @SuppressWarnings("squid:S1185")
The xsd file is the schema of the xml file - it defines which elements may occur and their restrictions (like amount, order, boundaries, relationships,...)
Once you have access to the dbcrypt5 file , here is the android code to decrypt it:
private byte[] key = { (byte) 141, 75, 21, 92, (byte) 201, (byte) 255,
(byte) 129, (byte) 229, (byte) 203, (byte) 246, (byte) 250, 120,
25, 54, 106, 62, (byte) 198, 33, (byte) 166, 86, 65, 108,
(byte) 215, (byte) 147 };
private final byte[] iv = { 0x1E, 0x39, (byte) 0xF3, 0x69, (byte) 0xE9, 0xD,
(byte) 0xB3, 0x3A, (byte) 0xA7, 0x3B, 0x44, 0x2B, (byte) 0xBB,
(byte) 0xB6, (byte) 0xB0, (byte) 0xB9 };
long start = System.currentTimeMillis();
// create paths
backupPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/WhatsApp/Databases/msgstore.db.crypt5";
outputPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/WhatsApp/Databases/msgstore.db.decrypt";
File backup = new File(backupPath);
// check if file exists / is accessible
if (!backup.isFile()) {
Log.e(TAG, "Backup file not found! Path: " + backupPath);
return;
}
// acquire account name
AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");
if (accounts.length == 0) {
Log.e(TAG, "Unable to fetch account!");
return;
}
String account = accounts[0].name;
try {
// calculate md5 hash over account name
MessageDigest message = MessageDigest.getInstance("MD5");
message.update(account.getBytes());
byte[] md5 = message.digest();
// generate key for decryption
for (int i = 0; i < 24; i++)
key[i] ^= md5[i & 0xF];
// read encrypted byte stream
byte[] data = new byte[(int) backup.length()];
DataInputStream reader = new DataInputStream(new FileInputStream(
backup));
reader.readFully(data);
reader.close();
// create output writer
File output = new File(outputPath);
DataOutputStream writer = new DataOutputStream(
new FileOutputStream(output));
// decrypt file
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secret = new SecretKeySpec(key, "AES");
IvParameterSpec vector = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secret, vector);
writer.write(cipher.update(data));
writer.write(cipher.doFinal());
writer.close();
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "Could not acquire hash algorithm!", e);
return;
} catch (IOException e) {
Log.e(TAG, "Error accessing file!", e);
return;
} catch (Exception e) {
Log.e(TAG, "Something went wrong during the encryption!", e);
return;
}
long end = System.currentTimeMillis();
Log.i(TAG, "Success! It took " + (end - start) + "ms");
Try simply to reset last commit using --soft
flag
git reset --soft HEAD~1
Note :
For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"
You can use position:absolute
to position an overlay inside of your div and then stretch it in all directions like so:
CSS updated *
.overlay {
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
background-color:rgba(0, 0, 0, 0.85);
background: url(data:;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAABl0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuNUmK/OAAAAATSURBVBhXY2RgYNgHxGAAYuwDAA78AjwwRoQYAAAAAElFTkSuQmCC) repeat scroll transparent\9; /* ie fallback png background image */
z-index:9999;
color:white;
}
You just need to make sure that your parent div has the position:relative
property added to it and a lower z-index
.
Made a demo that should work in all browsers, including IE7+, for a commenter below.
Removed the opacity
property from the css and instead used an rGBA color to give the background, and only the background, an opacity level. This way the content that the overlay carries will not be affected. Since IE does not support rGBA i used an IE hack instead to give it an base64 encoded PNG background image that fills the overlay div instead, this way we can evade IEs opacity issue where it applies the opacity to the children elements as well.
If you use a comma inbetween the strings and the variable, like this:
print "If there was a birth every 7 seconds, there would be: ", births, "births"
Hadoop is a a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models.
There are four main modules in Hadoop.
Hadoop Common: The common utilities that support the other Hadoop modules.
Hadoop Distributed File System (HDFS™): A distributed file system that provides high-throughput access to application data.
Hadoop YARN: A framework for job scheduling and cluster resource management.
Hadoop MapReduce: A YARN-based system for parallel processing of large data sets.
Before going further, Let's note that we have three different types of data.
Structured: Structured data has strong schema and schema will be checked during write & read operation. e.g. Data in RDBMS systems like Oracle, MySQL Server etc.
Unstructured: Data does not have any structure and it can be any form - Web server logs, E-Mail, Images etc.
Semi-structured: Data is not strictly structured but have some structure. e.g. XML files.
Depending on type of data to be processed, we have to choose right technology.
Some more projects, which are part of Hadoop:
HBase™: A scalable, distributed database that supports structured data storage for large tables.
Hive™: A data warehouse infrastructure that provides data summarization and ad-hoc querying.
Pig™: A high-level data-flow language and execution framework for parallel computation.
Hive Vs PIG comparison can be found at this article and my other post at this SE question.
HBASE won't replace Map Reduce. HBase is scalable distributed database & Map Reduce is programming model for distributed processing of data. Map Reduce may act on data in HBASE in processing.
You can use HIVE/HBASE for structured/semi-structured data and process it with Hadoop Map Reduce
You can use SQOOP to import structured data from traditional RDBMS database Oracle, SQL Server etc and process it with Hadoop Map Reduce
You can use FLUME for processing Un-structured data and process with Hadoop Map Reduce
Have a look at: Hadoop Use Cases.
Hive should be used for analytical querying of data collected over a period of time. e.g Calculate trends, summarize website logs but it can't be used for real time queries.
HBase fits for real-time querying of Big Data. Facebook use it for messaging and real-time analytics.
PIG can be used to construct dataflows, run a scheduled jobs, crunch big volumes of data, aggregate/summarize it and store into relation database systems. Good for ad-hoc analysis.
Hive can be used for ad-hoc data analysis but it can't support all un-structured data formats unlike PIG.
I would be very careful if you are considering adopting this hashbang convention.
Once you hashbang, you can’t go back. This is probably the stickiest issue. Ben’s post put forward the point that when pushState is more widely adopted then we can leave hashbangs behind and return to traditional URLs. Well, fact is, you can’t. Earlier I stated that URLs are forever, they get indexed and archived and generally kept around. To add to that, cool URLs don’t change. We don’t want to disconnect ourselves from all the valuable links to our content. If you’ve implemented hashbang URLs at any point then want to change them without breaking links the only way you can do it is by running some JavaScript on the root document of your domain. Forever. It’s in no way temporary, you are stuck with it.
You really want to use pushState instead of hashbangs, because making your URLs ugly and possibly broken -- forever -- is a colossal and permanent downside to hashbangs.
From http://www.dotnetperls.com:
7z a secure.7z * -pSECRET
Where:
7z : name and path of 7-Zip executable
a : add to archive
secure.7z : name of destination archive
* : add all files from current directory to destination archive
-pSECRET : specify the password "SECRET"
To open :
7z x secure.7z
Then provide the SECRET password
Note: If the password contains spaces or special characters, then enclose it with single quotes
7z a secure.7z * -p"pa$$word @|"
@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))
The error is also caused by quirky handling of quotes and single qutoes. To include single quotes inside the query, use doubled single quotes.
This won't work
select dbms_xmlgen.getxml("Select ....") XML from dual;
or this either
select dbms_xmlgen.getxml('Select .. where something='red'..') XML from dual;
but this DOES work
select dbms_xmlgen.getxml('Select .. where something=''red''..') XML from dual;
$start_date = date('Y-m-d h:m:s');
$end_date = date('Y-m-d h:m:s', strtotime($start_date . "+".$userSubscription['duration']." months") );
$user_subscription_array = array(
array(
'user_id' => $request->input('user_id'),
'user_subscription_plan_id' => $request->input('subscription_plan_id'),
'name' => $userSubscription['name'],
'description' => $userSubscription['description'],
'duration' => $userSubscription['duration'],
'start_datetime' => $start_date,
'end_datetime' => $end_date,
'amount' => $userSubscription['amount'],
'invoice_id' => '',
'transection_datetime' => '',
'created_by' => '1',
'status_id' => '1', ),
array(
'user_id' => $request->input('user_id'),
'user_subscription_plan_id' => $request->input('subscription_plan_id'),
'name' => $userSubscription['name'],
'description' => $userSubscription['description'],
'duration' => $userSubscription['duration'],
'start_datetime' => $start_date,
'end_datetime' => $end_date,
'amount' => $userSubscription['amount'],
'invoice_id' => '',
'transection_datetime' => '',
'created_by' => '1',
'status_id' => '1', )
);
dd(UserSubscription::insert($user_subscription_array));
UserSubscription
is my model name.
This will return "true" if insert successfully else "false".
The easiest way would be to click the red button (leftmost on macOS and rightmost on Windows). If you want to bind a specific function to a button widget, you can do this:
class App:
def __init__(self, master)
frame = Tkinter.Frame(master)
frame.pack()
self.quit_button = Tkinter.Button(frame, text = 'Quit', command = frame.quit)
self.quit_button.pack()
Or, to make things a little more complex, use protocol handlers and the destroy()
method.
import tkMessageBox
def confirmExit():
if tkMessageBox.askokcancel('Quit', 'Are you sure you want to exit?'):
root.destroy()
root = Tk()
root.protocol('WM_DELETE_WINDOW', confirmExit)
root.mainloop()
@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{
try {
MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
Iterator<String> it=multipartRequest.getFileNames();
MultipartFile multipart=multipartRequest.getFile(it.next());
String fileName=id+".png";
String imageName = fileName;
byte[] bytes=multipart.getBytes();
BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;
stream.write(bytes);
stream.close();
return new ResponseEntity("upload success", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
}
}
If you're having an issue where the Resources added are images and are not getting copied to your build folder on compiling. You need to change the "Build Action" to None from Resource ( which is the default) and change the Copy to "If Newer" or "Always" as shown below :
selinux is cause for that problem.....
TException: Error: TSocket: Could not connect to localhost:9160 (Permission denied [13]) To resolve it, you need to change an SELinux boolean value (which will automatically persist across reboots). You may also want to restart httpd to reset the proxy worker, although this isn't strictly required.
or
(13) Permission Denied
Error 13 indicates a filesystem permissions problem. That is, Apache was denied access to a file or directory due to incorrect permissions. It does not, in general, imply a problem in the Apache configuration files.
In order to serve files, Apache must have the proper permission granted by the operating system to access those files. In particular, the User or Group specified in httpd.conf must be able to read all files that will be served and search the directory containing those files, along with all parent directories up to the root of the filesystem.
Typical permissions on a unix-like system for resources not owned by the User or Group specified in httpd.conf would be 644 -rw-r--r-- for ordinary files and 755 drwxr-x-r-x for directories or CGI scripts. You may also need to check extended permissions (such as SELinux permissions) on operating systems that support them.
An Example
Lets say that you received the Permission Denied error when accessing the file /usr/local/apache2/htdocs/foo/bar.html on a unix-like system.
First check the existing permissions on the file:
cd /usr/local/apache2/htdocs/foo ls -l bar.htm
Fix them if necessary:
chmod 644 bar.html
Then do the same for the directory and each parent directory (/usr/local/apache2/htdocs/foo, /usr/local/apache2/htdocs, /usr/local/apache2, /usr/local, /usr):
ls -la chmod +x . cd ..
On some systems, the utility namei can be used to help find permissions problems by listing the permissions along each component of the path:
namei -m /usr/local/apache2/htdocs/foo/bar.html
If all the standard permissions are correct and you still get a Permission Denied error, you should check for extended-permissions. For example you can use the command setenforce 0 to turn off SELinux and check to see if the problem goes away. If so, ls -alZ can be used to view SELinux permission and chcon to fix them.
In rare cases, this can be caused by other issues, such as a file permissions problem elsewhere in your apache2.conf file. For example, a WSGIScriptAlias directive not mapping to an actual file. The error message may not be accurate about which file was unreadable.
DO NOT set files or directories to mode 777, even "just to test", even if "it's just a test server". The purpose of a test server is to get things right in a safe environment, not to get away with doing it wrong. All it will tell you is if the problem is with files that actually exist.
What I did to disable the hover state of the iframe, was to use pointer-events:none
in a css style. It shows the info on load, but after that hover shouldn't trigger showing the info.
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name, CAST(Value AS CHAR(7))) SEPARATOR ',') AS result
FROM test GROUP BY id
you must use cast or convert, otherwise will be return BLOB
result is
id Column
1 A:4,A:5,B:8
2 C:9
you have to handle result once again by program such as python or java
Add new column to Table with default value.
ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE
This should work
<a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>
You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block
It may be relevant to see if it's running in PHP via command line as well-
<path-to-php-binary>php -i | grep memcache
I'd use absolute positioning:
#play_button {
position:absolute;
transition: .5s ease;
left: 202px;
top: 198px;
}
I also used the bash4 way but I find and annoying bug.
I needed to update dynamically the associative array content so i used this way:
for instanceId in $instanceList
do
aws cloudwatch describe-alarms --output json --alarm-name-prefix $instanceId| jq '.["MetricAlarms"][].StateValue'| xargs | grep -E 'ALARM|INSUFFICIENT_DATA'
[ $? -eq 0 ] && statusCheck+=([$instanceId]="checkKO") || statusCheck+=([$instanceId]="allCheckOk"
done
I find out that with bash 4.3.11 appending to an existing key in the dict resulted in appending the value if already present. So for example after some repetion the content of the value was "checkKOcheckKOallCheckOK" and this was not good.
No problem with bash 4.3.39 where appenging an existent key means to substisture the actuale value if already present.
I solved this just cleaning/declaring the statusCheck associative array before the cicle:
unset statusCheck; declare -A statusCheck
Another approach
=CONCATENATE("Age as of ", TEXT(TODAY(),"dd-mmm-yyyy"))
This will return Age as of 06-Aug-2013
There are $watchGroup
and $watchCollection
as well. Specifically, $watchGroup
is really helpful if you want to call a function to update an object which has multiple properties in a view that is not dom object, for e.g. another view in canvas, WebGL or server request.
Here, the documentation link.
After some tinkering for a while with different solutions i found out that one must create a notification channel in Android 8.1 and above.
private fun startForeground() {
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel("my_service", "My Background Service")
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
val notificationBuilder = NotificationCompat.Builder(this, channelId )
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String{
val chan = NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_NONE)
chan.lightColor = Color.BLUE
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return channelId
}
From my understanding background services are now displayed as normal notifications that the user then can select to not show by deselecting the notification channel.
Update: Also don't forget to add the foreground permission as required Android P:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
This is more a workaround than a real solution. You can create a new object test_data
with another column name:
left_join("names<-"(test_data, "name"), kantrowitz, by = "name")
name gender
1 john M
2 bill either
3 madison M
4 abby either
5 zzz <NA>
@[User::path] ="MDS/Material/"+(DT_STR, 4, 1252) DATEPART("yy" , GETDATE())+ "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
This regex should do it.
\b[a-z]+-[a-z]+\b
\b
indicates a word-boundary.
replace operates on a specific string, so you need to call it like this
removeSpecialChars = z.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")
but this is probably not what you need, since this will look for a single string containing all that characters in the same order. you can do it with a regexp, as Danny Michaud pointed out.
as a side note, you might want to look for BeautifulSoup, which is a library for parsing messy HTML formatted text like what you usually get from scaping websites.
You are correct that overloading is not the answer.
Neither is overriding. Overriding is the means by which you get polymorphism. Polymorphism is the ability for an object to vary behavior based on its type. This is best demonstrated when the caller of an object that exhibits polymorphism is unaware of what specific type the object is.
Just use the javascript window.open function with the second parameter at "_blank"
<button onClick="javascript:window.open('http://www.facebook.com', '_blank');">facebook</button>
The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.
The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.
The privileges you need are defined in the Admin Guide. Find out more.
So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.
that worked but try it this way.
echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';
</script>";
alert on top then location next
Just add the classes to your html
<div class="someDiv radius opacity"></div>
To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:
$ find /target_directory -type f -mmin -60
To find the most recently modified files, sorted in the reverse order of update time (i.e., the most recently updated files first):
$ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r
Ubuntu STEP 1 : type create_tables.sql phpmyadmin and select the github link STEP 2 : Download the create_tables.sql file STEP 3 : Import it on your phpmyadmin using import button on navbar, upload the file. CHEERS!! Work is Done!!
NODE_ENV
is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV
specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.
You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:
var environment = process.env.NODE_ENV
Assume production if you don't recognise the value:
var isDevelopment = environment === 'development'
if (isDevelopment) {
setUpMoreVerboseLogging()
}
You can alternatively using express' app.get('env')
function, but note that this is NOT RECOMMENDED as it defaults to "development"
, which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).
Be aware that if you haven't explicitly set NODE_ENV
for your environment, it will be undefined
if you access it from process.env
, there is no default.
How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.
If you want to set the environment variable as a one-off, you can do so from the command line:
export NODE_ENV=production
$env:NODE_ENV = 'production'
In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!
Convention has dictated that there are two 'main' values you should use for NODE_ENV
, either production
or development
, all lowercase. There's nothing to stop you from using other values, (test
, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production'
or 'development'
to determine what to do, so there may be side effects that aren't immediately obvious.
Finally, note that it's a really bad idea to try to set NODE_ENV
from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
In Ef .net core there are two options that you can do; first with data annotations:
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}
Or with fluent api:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired(false)//optinal case
.IsRequired()//required case
;
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
There are more details here
There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.
/**
* This method is used to process GET requests to the server.
*
* @param url
* @return String
* @throws IOException
*/
public static String connect(String url) throws IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
//instream.close();
}
}
catch (ClientProtocolException e) {
Utilities.showDLog("connect","ClientProtocolException:-"+e);
} catch (IOException e) {
Utilities.showDLog("connect","IOException:-"+e);
}
return result;
}
/**
* This method is used to send POST requests to the server.
*
* @param URL
* @param paramenter
* @return result of server response
*/
static public String postHTPPRequest(String URL, String paramenter) {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(URL);
httppost.setHeader("Content-Type", "application/json");
try {
if (paramenter != null) {
StringEntity tmp = null;
tmp = new StringEntity(paramenter, "UTF-8");
httppost.setEntity(tmp);
}
HttpResponse httpResponse = null;
httpResponse = httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream input = null;
input = entity.getContent();
String res = convertStreamToString(input);
return res;
}
}
catch (Exception e) {
System.out.print(e.toString());
}
return null;
}