You can use git show
with a path from the root of the repository (./
or ../
for relative pathing):
$ git show REVISION:path/to/file
Replace REVISION
with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)
For example, to view the version of file <repository-root>/src/main.c
from 4 commits ago, use:
$ git show HEAD~4:src/main.c
Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show
.
I suggest you cast all columns before you concat them
cast('data1' as varchar) + cast('data2' as varchar) + cast('data3' as varchar)
This should work for you.
Similar to @Sijmen's answer, this is what worked for me on OSX when renaming a directory (inspired by this answer from another post):
git mv CSS CSS2
git mv CSS2 css
Simply doing git mv CSS css
gave the invalid argument error: fatal: renaming '/static/CSS' failed: Invalid argument
perhaps because OSX's file system is case insensitive
p.s BTW if you are using Django, collectstatic also wouldn't recognize the case difference and you'd have to do the above, manually, in the static root directory as well
Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")
Call the replace
method and be sure to pass it a Unicode string as its first argument:
str.decode("utf-8").replace(u"\u2022", "*")
Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str
shadows the built-in type str
.)
//do the edit in your javascript
$('.signinform').submit(function() {
$(this).ajaxSubmit({
type : "POST",
//set the data type
dataType:'json',
url: 'index.php/user/signin', // target element(s) to be updated with server response
cache : false,
//check this in Firefox browser
success : function(response){ console.log(response); alert(response)},
error: onFailRegistered
});
return false;
});
//controller function
public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
//add the header here
header('Content-Type: application/json');
echo json_encode( $arr );
}
Delete the project named Servers (or Servers1, Servers2 which contains your server.xml), find it in Package Explorer(workspace)
Remove server from Eclipse : Go to Window > Preferences > Server > Runtime Environment, here remove the server your are using from eclipse and add it again(doing this will create a new Server project folder in Eclipse) ,
Remove server from Project : Also remove the server in your project(Build path > configuration path > Java Build path) and add again.
now you got a fresh Server project which will not have Multiple Context on its server.xml, only deleting duplicate path in server.xml solved the existing issue but still server dint start, by doing this Server started(Apache Tomcat v7) and worked normal
And I don't know whether this is good practice or not, I am a starter in programming.
There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.
The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.
I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.
The following works for me in Gradle / Groovy for build.gradle
for an Android project, without having to import groovy.io.FileType
(NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):
FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
println "Proguard file located and processed: " + it
}
My explanation uses elementary building blocks that helped me to understand. Note I am leveraging @Deepak Goyal's answer above since he provided clarity:
We were given a logical 32-bit address space (i.e. We have a 32 bit computer)
Consider a system with a 32-bit logical address space
We were also told that
each page size is 4 KB
As Depaak said, we calculate the number of pages in the page table with this formula:
Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size
Num_Pages_in_PgTable = 2^32 / 2^12
Num_Pages_in_PgTable = 2^20 (i.e. 1 million)
The authors go on to give the case where each entry in the page table takes 4 bytes. That means that the total size of the page table in physical memory will be 4MB:
Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable
Memory_Required_Per_Page = 4 x 2^20
Memory_Required_Per_Page = 4 MB (Megabytes)
So yes, each process would require at least 4MB of memory to run, in increments of 4MB.
Now if a professor wanted to make the question a bit more challenging than the explanation from the book, they might ask about a 64-bit computer. Let's say they want memory in bits. To solve the question, we'd follow the same process, only being sure to convert MB to Mbits.
Let's step through this example.
- Logical address space: 64-bit
- Page Size: 4KB
- Entry_Size_Per_Page: 4 bytes
Recall: A 64-bit entry can point to one of 2^64 physical page frames - Since Page size is 4 KB, then we still have 2^12 byte page sizes
- 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
- Size of each page = 4 x 1024 bytes = 2^2 x 2^10 bytes = 2^12 bytes
`Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size
Num_Pages_in_PgTable = 2^64 / 2^12
Num_Pages_in_PgTable = 2^52
Num_Pages_in_PgTable = 2^2 x 2^50
Num_Pages_in_PgTable = 4 x 2^50 `
Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable
Memory_Required_Per_Page = 4 bytes x 8 bits/byte x 2^52
Memory_Required_Per_Page = 32 bits x 2^2 x 2^50
Memory_Required_Per_Page = 32 bits x 4 x 2^50
Memory_Required_Per_Page = 128 Petabits
[2]: Operating System Concepts (9th Ed) - Gagne, Silberschatz, and Galvin
I think that if you stick strictly with TSQL
that this is the fastest way to truncate the time:
select convert(datetime,convert(int,convert(float,[Modified])))
I found this truncation method to be about 5% faster than the DateAdd
method. And this can be easily modified to round to the nearest day like this:
select convert(datetime,ROUND(convert(float,[Modified]),0))
Try invoking your command with Invoke-Expression
:
Invoke-Expression $cmd1
Here is a working example on my machine:
$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd
iex
is an alias for Invoke-Expression
so you could do:
iex $cmd1
For a full list :
Visit https://ss64.com/ps/ for more Powershell
stuff.
Good Luck...
I bumped with this issue a few days ago. I tried many solutions and none really worked for me on the end i ended up creating an extenion/override of the dropdown code of bootstrap. It is a copy of the original code with changes to the closeMenus function.
I think it is a good solution since it doesn't affects the core classes of bootstrap js.
You can check it out on gihub: https://github.com/djokodonev/bootstrap-multilevel-dropdown
One possible solution is to encode the data in your app and use decoding at runtime (when you want to use that data). I also recommend to use progaurd to make it hard to read and understand the decompiled source code of your app . for example I put a encoded key in the app and then used a decode method in my app to decode my secret keys at runtime:
// "the real string is: "mypassword" ";
//encoded 2 times with an algorithm or you can encode with other algorithms too
public String getClientSecret() {
return Utils.decode(Utils
.decode("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
Decompiled source code of a proguarded app is this:
public String c()
{
return com.myrpoject.mypackage.g.h.a(com.myrpoject.mypackage.g.h.a("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
At least it's complicated enough for me. this is the way I do when I have no choice but store a value in my application. Of course we all know It's not the best way but it works for me.
/**
* @param input
* @return decoded string
*/
public static String decode(String input) {
// Receiving side
String text = "";
try {
byte[] data = Decoder.decode(input);
text = new String(data, "UTF-8");
return text;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "Error";
}
Decompiled version:
public static String a(String paramString)
{
try
{
str = new String(a.a(paramString), "UTF-8");
return str;
}
catch (UnsupportedEncodingException localUnsupportedEncodingException)
{
while (true)
{
localUnsupportedEncodingException.printStackTrace();
String str = "Error";
}
}
}
and you can find so many encryptor classes with a little search in google.
Sorry this answer sucks, but you can't launch an just any external application via a click, as this would be a serious security issue, this functionality isn't available in HTML or javascript. Think of just launching cmd.exe
with args...you want to launch WinMerge with arguments, but you can see the security problems introduced by allowing this for anything.
The only possibly viable exception I can think of would be a protocol handler (since these are explicitly defined handlers), like winmerge://
, though the best way to pass 2 file parameters I'm not sure of, if it's an option it's worth looking into, but I'm not sure what you are or are not allowed to do to the client, so this may be a non-starter solution.
In case anyone is using the delegated approach for their listener, use e.target
(it will refer to the select element).
$('#myform').on('change', 'select', function (e) {
var val = $(e.target).val();
var text = $(e.target).find("option:selected").text(); //only time the find is required
var name = $(e.target).attr('name');
}
I prefer to use <limits>
to check for an int
until it is passed.
#include <iostream> #include <limits> //std::numeric_limits using std::cout, std::endl, std::cin; int main() { int num; while(!(cin >> num)){ //check the Input format for integer the right way cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); cout << "Invalid input. Reenter the number: "; }; cout << "output= " << num << endl; return 0; }
Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
// u can try giving int i=100 but is useless as that value is not passed into
// the method. Only variable goes into the method and gets changed its
// value and comes out.
int i;
a.abc(out i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(out int i)
{
i = 10;
}
}
}
Output:
10
===============================================
Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.
namespace outreftry
{
class outref
{
static void Main(string[] args)
{
yyy a = new yyy(); ;
int i = 0;
a.abc(ref i);
System.Console.WriteLine(i);
}
}
class yyy
{
public void abc(ref int i)
{
System.Console.WriteLine(i);
i = 10;
}
}
}
Output:
0 10
=================================
Hope its clear now.
Use this.
$('#mydiv').load(document.URL + ' #mydiv');
Note, include a space before the hastag.
If none of the above work, double-check your code. Sometimes the reason why the breakpoint appears to not be hitting is due to the block of code containing the breakpoint is not being executed for sometimes inadvertant reasons.
For example, forgetting the "Handles Me.Load" has gotten me a few times when copying and pasting code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
--this block of code will not execute
End Sub
vs
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
--this block executes
End Sub
For Netbeans 11 users, this works for me:
apply plugin: 'java'
apply plugin: 'application'
// This comes out to package + '.' + mainClassName
mainClassName = 'com.hello.JavaApplication1'
Here generally is my tree:
C:\...\NETBEANSPROJECTS\JAVAAPPLICATION1
¦ build.gradle
+---src
¦ +---main
¦ ¦ +---java
¦ ¦ +---com
¦ ¦ +---hello
¦ ¦ JavaApplication1.java
¦ ¦
¦ +---test
¦ +---java
+---test
document.onkeypress = function(event){
alert(event.key)
}
Example
public class myThread extends Thread{
@override
public void run(){
while(true){
threadCondWait();// Circle waiting...
//bla bla bla bla
}
}
public synchronized void threadCondWait(){
while(myCondition){
wait();//Comminucate with notify()
}
}
}
public class myAnotherThread extends Thread{
@override
public void run(){
//Bla Bla bla
notify();//Trigger wait() Next Step
}
}
I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:
ProjectNamespace.Properties.Resources.file
Use the IDE's resource manager to add resources.
The documentation states several ways to do this.
If you want to replace the default
ObjectMapper
completely, define a@Bean
of that type and mark it as@Primary
.Defining a
@Bean
of typeJackson2ObjectMapperBuilder
will allow you to customize both defaultObjectMapper
andXmlMapper
(used inMappingJackson2HttpMessageConverter
andMappingJackson2XmlHttpMessageConverter
respectively).
7-Zip should do the trick.
With it, you can extract all the files inside the EXE (thus, also an MSI file).
Although you can do it with 7-Zip, the better way is the administrative installation as pointed out by Stein Åsmul.
max_allowed_packet
is set in mysql config, not on php side
[mysqld]
max_allowed_packet=16M
You can see it's curent value in mysql like this:
SHOW VARIABLES LIKE 'max_allowed_packet';
You can try to change it like this, but it's unlikely this will work on shared hosting:
SET GLOBAL max_allowed_packet=16777216;
You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html
EDIT
The [mysqld] is necessary to make the max_allowed_packet
working since at least mysql version 5.5.
Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet
. It you set the value under [mysqld_safe]
(which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld]
and restarted the mysqld, it worked.
Another way, which is a little bit easier for me is to use named pipes. Named pipes provided a way to synchronize and sending messages between different processes.
A.bash:
#!/bin/bash
msg="The Message"
echo $msg > A.pipe
B.bash:
#!/bin/bash
msg=`cat ./A.pipe`
echo "message from A : $msg"
Usage:
$ mkfifo A.pipe #You have to create it once
$ ./A.bash & ./B.bash # you have to run your scripts at the same time
B.bash will wait for message and as soon as A.bash sends the message, B.bash will continue its work.
An APK is just in zip
format. You can unzip it like any other .zip
file.
You can decompile .dex
files using the dexdump
tool, which is provided in the Android SDK.
See https://stackoverflow.com/a/7750547/116938 for more dex info.
convert your inputs to ints:
width = int(input())
height = int(input())
You want a parameter source:
Set<Integer> ids = ...;
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);
List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
parameters, getRowMapper());
This only works if getJdbcTemplate()
returns an instance of type NamedParameterJdbcTemplate
I found a solution for ajax issue noted by Lion_cl.
global.asax:
protected void Application_Error()
{
if (HttpContext.Current.Request.IsAjaxRequest())
{
HttpContext ctx = HttpContext.Current;
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
rc.RouteData.Values["action"] = "AjaxGlobalError";
// TODO: distinguish between 404 and other errors if needed
rc.RouteData.Values["newActionName"] = "WrongRequest";
rc.RouteData.Values["controller"] = "ErrorPages";
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(rc, "ErrorPages");
controller.Execute(rc);
ctx.Server.ClearError();
}
}
ErrorPagesController
public ActionResult AjaxGlobalError(string newActionName)
{
return new AjaxRedirectResult(Url.Action(newActionName), this.ControllerContext);
}
AjaxRedirectResult
public class AjaxRedirectResult : RedirectResult
{
public AjaxRedirectResult(string url, ControllerContext controllerContext)
: base(url)
{
ExecuteResult(controllerContext);
}
public override void ExecuteResult(ControllerContext context)
{
if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
{
JavaScriptResult result = new JavaScriptResult()
{
Script = "try{history.pushState(null,null,window.location.href);}catch(err){}window.location.replace('" + UrlHelper.GenerateContentUrl(this.Url, context.HttpContext) + "');"
};
result.ExecuteResult(context);
}
else
{
base.ExecuteResult(context);
}
}
}
AjaxRequestExtension
public static class AjaxRequestExtension
{
public static bool IsAjaxRequest(this HttpRequest request)
{
return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
It's compiler dependent. That said, in general using "
prioritizes headers in the current working directory over system headers. <>
usually is used for system headers. From to the specification (Section 6.10.2):
A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the
<
and>
delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"
delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read# include <h-char-sequence> new-line
with the identical contained sequence (including
>
characters, if any) from the original directive.
So on most compilers, using the ""
first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <>
starts the search with system headers.
You cannot cast an int to a char* to get a string. Try this:
std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();
1.
first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)
2.
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Order Allow,Deny
Allow from all
if "Allow from all" line not work for your then use "Require all granted" then it will work for you.
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80
3. Dont forget to restart All Services of Wamp or Apache after making this change
Due to https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables :
Some options, such as --opt (which is enabled by default), automatically enable --lock-tables. If you want to override this, use --skip-lock-tables at the end of the option list.
$find="Topsite";
$list=array("Tope","Ajayi","Topsite","Infotech");
$list_count=count($list);
sort($list);
for($i=0;$i<$list_count;$i++)
{
if($list[$i]==$find){
$position=$i;
}
}
echo $position;
Use bootstrap class vh-100 for exp:
<div class="vh-100">
Add private constructor:
private FilePathHelper(){
super();
}
This is because strings are immutable in Python.
Which means that X.replace("hello","goodbye")
returns a copy of X
with replacements made. Because of that you need replace this line:
X.replace("hello", "goodbye")
with this line:
X = X.replace("hello", "goodbye")
More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace
,strip
,translate
,lower
/upper
,join
,...
You must assign their output to something if you want to use it and not throw it away, e.g.
X = X.strip(' \t')
X2 = X.translate(...)
Y = X.lower()
Z = X.upper()
A = X.join(':')
B = X.capitalize()
C = X.casefold()
and so on.
Not sure if this is helpful or exactly relevant to your question, but if you are trying to fetch and checkout only a single branch from the remote repository, then the following git commands will do the trick:
url= << URL TO REPOSITORY >>
branch= << BRANCH NAME >>
git init
git remote add origin $url
git fetch origin $branch:origin/$branch
git checkout -b $branch --track origin/$branch
I'm new to node.js (about 2 weeks), but I've just created a module that recursively reports to the console the contents of an object. It will list all or search for a specific item and then drill down by a given depth if need be.
Perhaps you can customize this to fit your needs. Keep It Simple! Why complicate?...
'use strict';
//console.log("START: AFutils");
// Recusive console output report of an Object
// Use this as AFutils.reportObject(req, "", 1, 3); // To list all items in req object by 3 levels
// Use this as AFutils.reportObject(req, "headers", 1, 10); // To find "headers" item and then list by 10 levels
// yes, I'm OLD School! I like to see the scope start AND end!!! :-P
exports.reportObject = function(obj, key, level, deep)
{
if (!obj)
{
return;
}
var nextLevel = level + 1;
var keys, typer, prop;
if(key != "")
{ // requested field
keys = key.split(']').join('').split('[');
}
else
{ // do for all
keys = Object.keys(obj);
}
var len = keys.length;
var add = "";
for(var j = 1; j < level; j++)
{
// I would normally do {add = add.substr(0, level)} of a precreated multi-tab [add] string here, but Sublime keeps replacing with spaces, even with the ["translate_tabs_to_spaces": false] setting!!! (angry)
add += "\t";
}
for (var i = 0; i < len; i++)
{
prop = obj[keys[i]];
if(!prop)
{
// Don't show / waste of space in console window...
//console.log(add + level + ": UNDEFINED [" + keys[i] + "]");
}
else
{
typer = typeof(prop);
if(typer == "function")
{
// Don't bother showing fundtion code...
console.log(add + level + ": [" + keys[i] + "] = {" + typer + "}");
}
else
if(typer == "object")
{
console.log(add + level + ": [" + keys[i] + "] = {" + typer + "}");
if(nextLevel <= deep)
{
// drop the key search mechanism if first level item has been found...
this.reportObject(prop, "", nextLevel, deep); // Recurse into
}
}
else
{
// Basic report
console.log(add + level + ": [" + keys[i] + "] = {" + typer + "} = " + prop + ".");
}
}
}
return ;
};
//console.log("END: AFutils");
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"/Beans.xml"}) public class DemoTest{}
To expand on John's answer you can also use the Dockerfile
CMD
command as following (in case you want it to self start without additional args)
CMD ["nginx", "-g", "daemon off;"]
for you objects override clone() method
class You_class {
int a;
@Override
public You_class clone() {
You_class you_class = new You_class();
you_class.a = this.a;
return you_class;
}
}
and call .clone() for Vector obj or ArraiList obj....
I prefer to extend the map
export class UtilMap extends Map {
constructor(...args) { super(args); }
public map(supplier) {
const mapped = new UtilMap();
this.forEach(((value, key) => mapped.set(key, supplier(value, key)) ));
return mapped;
};
}
I think the officially preferred way is now to use Less, and either dynamically override the bootstrap.css (using less.js), or recompile bootstrap.css (using Node or the Less compiler).
From the Bootstrap docs, here's how to override bootstrap.css styles dynamically:
Download the latest Less.js and include the path to it (and Bootstrap) in the
<head>
.<link rel="stylesheet/less" href="/path/to/bootstrap.less"> <script src="/path/to/less.js"></script>
To recompile the .less files, just save them and reload your page. Less.js compiles them and stores them in local storage.
Or if you prefer to statically compile a new bootstrap.css with your custom styles (for production environments):
Install the LESS command line tool via Node and run the following command:
$ lessc ./less/bootstrap.less > bootstrap.css
Generic Extension method :
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
HashSet<TSource> set = new HashSet<TSource>(comparer);
foreach (TSource item in source)
{
if (set.Add(item))
{
yield return item;
}
}
}
Try this:
using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
one-liner:
(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name
It is from Get Calling Method using Reflection [C#].
On Mac OS X Mavericks (10.9.3), I solved this by doing the follows:
Install libjpeg by brew (package management system)
brew install libjpeg
reinstall pillow (I use pillow instead of PIL)
pip install -I pillow
The simplest way to accomplish this is to use filter on the array.
let result = elements.filter { $0==5 }
result
will have the found element if it exists and will be empty if the element does not exist. So simply checking if result
is empty will tell you whether the element exists in the array. I would use the following:
if result.isEmpty {
// element does not exist in array
} else {
// element exists
}
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
"Access violation reading location 0x00000000" means that you're derefrencing a pointer that hasn't been initialized and therefore has garbage values. Those garbage values could be anything, but usually it happens to be 0
and so you try to read from the memory address 0x0
, which the operating system detects and prevents you from doing.
Check and make sure that the array invaders[]
is what you think it should be.
Also, you don't seem to be updating i
ever - meaning that you keep placing the same Invader
object into location 0
of invaders[]
at every loop iteration.
I would rather create a map
export class item{
name: string;
id: string
}
let caches = new Map<string, item>();
and then you can simply
this.caches[newitem.id] = newitem;
even
this.caches.set(newitem.id, newitem);
array is so 1999. :)
For each iteration of the ng-repeat loop, line
is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}
.
Similarly, to databind to the text, databind to the same: ng-model="line.text"
. You don't need to use value
when using ng-model (actually you shouldn't).
For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.
The main difference from other solutions here is that this one reuses logic in RequiredAttribute
on the server side, and uses required
's validation method depends
property on the client side:
public class RequiredIf : RequiredAttribute, IClientValidatable
{
public string OtherProperty { get; private set; }
public object OtherPropertyValue { get; private set; }
public RequiredIf(string otherProperty, object otherPropertyValue)
{
OtherProperty = otherProperty;
OtherPropertyValue = otherPropertyValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult($"Unknown property {OtherProperty}");
}
object otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (Equals(OtherPropertyValue, otherValue)) // if other property has the configured value
return base.IsValid(value, validationContext);
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "requiredif"; // data-val-requiredif
rule.ValidationParameters.Add("other", OtherProperty); // data-val-requiredif-other
rule.ValidationParameters.Add("otherval", OtherPropertyValue); // data-val-requiredif-otherval
yield return rule;
}
}
$.validator.unobtrusive.adapters.add("requiredif", ["other", "otherval"], function (options) {
var value = {
depends: function () {
var element = $(options.form).find(":input[name='" + options.params.other + "']")[0];
return element && $(element).val() == options.params.otherval;
}
}
options.rules["required"] = value;
options.messages["required"] = options.message;
});
Use document.documentElement
.
Same Question answered here: https://stackoverflow.com/a/7289396/2164160
Starting from express v4.16 there is no need to require any additional modules, just use the built-in JSON middleware:
app.use(express.json())
Like this:
const express = require('express')
app.use(express.json()) // <==== parse request body as JSON
app.listen(8080)
app.post('/test', (req, res) => {
res.json({requestBody: req.body}) // <==== req.body will be a parsed JSON object
})
Note - body-parser
, on which this depends, is already included with express.
Also don't forget to send the header Content-Type: application/json
Check-all checkbox should be updated itself under certain conditions. Try to click on '#select-all-teammembers' then untick few items and click select-all again. You can see inconsistency. To prevent it use the following trick:
var checkBoxes = $('input[name=recipients\\[\\]]');
$('#select-all-teammembers').click(function() {
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
$(this).prop("checked", checkBoxes.is(':checked'));
});
BTW all checkboxes DOM-object should be cached as described above.
wait
waits for a process to finish; sleep
sleeps for a certain amount of seconds.
I always use this code, which print the year to second in a tuple
import datetime
now = datetime.datetime.now()
time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)
print(time_now)
You can get a subset of the np.set_printoptions
functionality from the np.array_str
command, which applies only to a single print statement.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html
For example:
In [27]: x = np.array([[1.1, 0.9, 1e-6]]*3)
In [28]: print x
[[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]
[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]
[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]]
In [29]: print np.array_str(x, precision=2)
[[ 1.10e+00 9.00e-01 1.00e-06]
[ 1.10e+00 9.00e-01 1.00e-06]
[ 1.10e+00 9.00e-01 1.00e-06]]
In [30]: print np.array_str(x, precision=2, suppress_small=True)
[[ 1.1 0.9 0. ]
[ 1.1 0.9 0. ]
[ 1.1 0.9 0. ]]
This expression should do what you want to achieve.
dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))
Just check my scripts it's working well:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
#list img{
width: auto;
height: 100px;
margin: 10px ;
}
If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
End If
This is probably what you need:
$text = str_replace(' ', '_', substr($text, 0, 10));
import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');
keep it as simple as possible
function sree(){
console.log('hey');
window.sree = _=>{};
}
You can see the result
Cross Join: http://www.dba-oracle.com/t_garmany_9_sql_cross_join.htm
TLDR; Generates a all possible combinations between 2 tables (Carthesian product)
(Full) Outer Join: http://www.w3schools.com/Sql/sql_join_full.asp
TLDR; Returns every row in both tables and also results that have the same values (matches in CONDITION)
Try this query:
SELECT *
FROM table
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())
i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”
The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.
# GRANT SELECT ON table_name TO "walters-ro";
That solved the problem.
You are right that greediness is an issue:
--A--Z--A--Z--
^^^^^^^^^^
A.*Z
If you want to match both A--Z
, you'd have to use A.*?Z
(the ?
makes the *
"reluctant", or lazy).
There are sometimes better ways to do this, though, e.g.
A[^Z]*+Z
This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.
In your case, the regex would be:
/(\[[^\]]++\])/
Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:
/(\[[^\]]+\])/
* Zero or more, greedy
*? Zero or more, reluctant
*+ Zero or more, possessive
+ One or more, greedy
+? One or more, reluctant
++ One or more, possessive
? Zero or one, greedy
?? Zero or one, reluctant
?+ Zero or one, possessive
Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m}
constructs.
Examples in Java:
System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!")); // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"
System.out.println("xxxxxx".replaceAll("x{3,5}", "Y")); // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"
Multi joins in SQL work by progressively creating derived tables one after the other. See this link explaining the process:
https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/
EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply serialize the two arrays to JSON and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to each of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend MochiKit.
EDIT: The answer kamens gave deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).
Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
The assumption is that both objects have the same exact list of properties.
Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)
location.reload();
You can use the reload
function in your if
condition for success and the page will reload after the condition is successful.
I think the order has to do with the way the files are indexed on your FileSystem. If you really want to make it adhere to some order you can always sort the list after getting the files.
Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.
Of course friend functions throw this out the window, but oh well.
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
You get this error, despite everything being in line, because of a conflict caused by one of the packages that are currently loaded in your R environment.
So, to solve this issue, detach all the packages that are not needed from the R environment. For example, when I had the same issue, I did the following:
detach(package:neuralnet)
bottom line: detach all the libraries no longer needed for execution... and the problem will be solved.
I'm thinking unload is called all but at hard exist in 4.7. But, if you are playing around with older versions of .Net, try doing this in your loading method:
e.Handled = true;
I don't think older versions will unload until loading is handled. Just posting because I see others still asking this question, and haven't seen this proposed as a solution. I only touch .Net a few times a year, and ran into this a few years back. But, I wonder if it's as simple as unload not being called until loading has finished. Seems like it works for me, but again in newer .Net it seems to always call unload even if loading isn't marked as handled.
For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str
to int
) so you must do this yourself. You'll like that in the long-run, trust me!
RatingBar mRating=(RatingBar)findViewById(R.id.rating);
LayerDrawable layerDrawable=(LayerDrawable)mRating.getProgressDrawable();
layerDrawable.getDrawable(2).setColorFilter(Color.parseColor
("#32CD32"), PorterDuff.Mode.SRC_ATOP);
for me its working....
Since JavaScript doesn't have function overload options object can be used instead. If there are one or two required arguments, it's better to keep them separate from the options object. Here is an example on how to use options object and populated values to default value in case if value was not passed in options object.
function optionsObjectTest(x, y, opts) {
opts = opts || {}; // default to an empty options object
var stringValue = opts.stringValue || "string default value";
var boolValue = !!opts.boolValue; // coerces value to boolean with a double negation pattern
var numericValue = opts.numericValue === undefined ? 123 : opts.numericValue;
return "{x:" + x + ", y:" + y + ", stringValue:'" + stringValue + "', boolValue:" + boolValue + ", numericValue:" + numericValue + "}";
}
here is an example on how to use options object
Using 2.7:
from functools import partial
from random import randint
for roll in iter(partial(randint, 1, 8), 1):
print 'you rolled: {}'.format(roll)
print 'oops you rolled a 1!'
you rolled: 7
you rolled: 7
you rolled: 8
you rolled: 6
you rolled: 8
you rolled: 5
oops you rolled a 1!
Then change the "oops" print to a raise SystemExit
In the simplest case, with Swift 3, you can use Array
's init(_:)
initializer to get an Array
from a Set
. init(_:)
has the following declaration:
init<S>(_ s: S) where S : Sequence, Element == S.Iterator.Element
Creates an array containing the elements of a sequence.
Usage:
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")
let stringArray = Array(stringSet)
print(stringArray)
// may print ["toy", "car", "bike", "boat"]
However, if you also want to perform some operations on each element of your Set
while transforming it into an Array
, you can use map
, flatMap
, sort
, filter
and other functional methods provided by Collection
protocol:
let stringSet = Set(["car", "boat", "bike", "toy"])
let stringArray = stringSet.sorted()
print(stringArray)
// will print ["bike", "boat", "car", "toy"]
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")
let stringArray = stringSet.filter { $0.characters.first != "b" }
print(stringArray)
// may print ["car", "toy"]
let intSet = Set([1, 3, 5, 2])
let stringArray = intSet.flatMap { String($0) }
print(stringArray)
// may print ["5", "2", "3", "1"]
let intSet = Set([1, 3, 5, 2])
// alternative to `let intArray = Array(intSet)`
let intArray = intSet.map { $0 }
print(intArray)
// may print [5, 2, 3, 1]
This is just a guess .. but
Because they are strings, they have some semantic value (the compiler doesn't get rid of them), therefore it makes sense for them to be used as docstrings. They actually become part of the AST, so extracting documentation becomes easier.
If you want to do this in a single line, try:
Object.keys(a).map(function(key){return a[key]})
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
For me SpeedTrace is the best tool on the market because it does not only help you to find bottlenecks inside your applications. It also helps you in troubleshooting scenarios to find out why your application was crashing, your setup did not install, your application hung up, your application performance is sometimes poor depending on the data input, e.g. to identify slow db transactions.
I would say no, because the Developer docs on RAM usage state:
...
GC_EXPLICIT
An explicit GC, such as when you call gc() (which you should avoid calling and instead trust the GC to run when needed).
...
I've highlighted the relevant part in bold.
Have a look at the YouTube series, Android Performance Patterns - it will show you tips on managing your app's memory usage (such as using Android's ArrayMap
s and SparseArray
s instead of HashMap
s).
Use the following code
$("#modal").trigger('click');
function limitText($string,$limit){
if(strlen($string) > $limit){
$string = substr($string, 0,$limit) . "...";
}
return $string;
}
this will return 20 words. I hope it will help
The HTML parser simply doesn't interpret the inlined javascript like this.
You may do this :
<td><input type="checkbox" id="repriseCheckBox" name="repriseCheckBox"/></td>
<script>document.getElementById("repriseCheckBox").disabled=checkStat == 1 ? true : false;</script>
For my situation, it was a naming conflict problem. Adding $J solves it.
//Old code:
function () {
var extractionDialog;
extractionDialog = $j("#extractWindowDialog").dialog({
autoOpen: false,
appendTo: "form",
height: "100",
width: "250",
modal: true
});
$("extractBomInfoBtn").button().on("click", function () {
extractionDialog.dialog("open");
}
And the following is new code.
$j(function () {
var extractionDialog;
extractionDialog = $j("#extractWindowDialog").dialog({
autoOpen: false,
appendTo: "form",
height: "100",
width: "250",
modal: true
});
$j("extractBomInfoBtn").button().on("click", function () {
extractionDialog.dialog("open");
});
});
Hope it could help someone.
To time task in CMD is as simple as
echo %TIME% && your_command && cmd /v:on /c echo !TIME!
few Unicode alternatives
var s = "0";
var s1 = string.Concat(s.Select(c => $"{(int)c:x4}")); // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"
var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", ""); // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"
// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");
Log into the Twitter Developers section.
Go to "Create an app"
Fill in the details of the application you'll be using to connect with the API
Click on Create your Twitter application
Details of your new app will be shown along with your consumer key and consumer secret.
If you need access tokens, scroll down and click Create my access token
By default your apps will be granted for read-only access. To change this, go to the Settings tab and change the access level required in the "Application Type" section.
To get the consumer and access tokens for an existing application, go to My applications (which is available from the menu in the upper-right).
- Where does
user.id
go afterpassport.serializeUser
has been called?
The user id (you provide as the second argument of the done
function) is saved in the session and is later used to retrieve the whole object via the deserializeUser
function.
serializeUser
determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}
. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}
- We are calling
passport.deserializeUser
right after it where does it fit in the workflow?
The first argument of deserializeUser
corresponds to the key of the user object that was given to the done
function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc).
In deserializeUser
that key is matched with the in memory array / database or any data resource.
The fetched object is attached to the request object as req.user
Visual Flow
passport.serializeUser(function(user, done) {
done(null, user.id);
}); ¦
¦
¦
+--------------------? saved to session
¦ req.session.passport.user = {id: '..'}
¦
?
passport.deserializeUser(function(id, done) {
+---------------+
¦
?
User.findById(id, function(err, user) {
done(err, user);
}); +--------------? user object attaches to the request as req.user
});
You're getting that error because the default value current_time
is not valid for the type DATETIME
. That's what it says, and that's whats going on.
The only field you can use current_time
on is a timestamp.
You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.
Date.prototype.getISOTimezoneOffset = function () {
const offset = this.getTimezoneOffset();
return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}
Date.prototype.toISOLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
this.getMilliseconds().leftPad(3);
}
Number.prototype.leftPad = function (size) {
var s = String(this);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
}
Example usage:
var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"
I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.
(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString
method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString
for anyone without said library.)
For accessibility reason, I could not pull it off with multiple type=submit
buttons. The only way to work natively with a form
with multiple buttons but ONLY one can submit the form when hitting the Enter
key is to ensure that only one of them is of type=submit
while others are in other type such as type=button
. By this way, you can benefit from the better user experience in dealing with a form on a browser in terms of keyboard support.
The reason is that php cannot find the correct path of mysql.sock
.
Please make sure that your mysql is running first.
Then, please confirm that which path is the mysql.sock
located, for example /tmp/mysql.sock
then add this path string to php.ini:
Finally, restart Apache.
I fixed this by simply deleting the app from my device and rebuild.
try with this simple line... add this line in your xml code in image view tag with out adding any dependency android:scaleType="fitXY"
I am late to the party, but since this question turns up often in search results, I would just like to add a solution that I consider to be the best in terms of readability while not being long (which is ideal for any codebase IMO). It mutates, but I'd make that tradeoff for KISS principles.
let times = 5
while( times-- )
console.log(times)
// logs 4, 3, 2, 1, 0
Singleton beans in Spring and classes based on Singleton design pattern are quite different.
Singleton pattern ensures that one and only one instance of a particular class will ever be created per classloader where as the scope of a Spring singleton bean is described as 'per container per bean'. Singleton scope in Spring means that this bean will be instantiated only once by Spring. Spring container merely returns the same instance again and again for subsequent calls to get the bean.
More flexible.. Here's an example printing rows of right-justified numbers with fixed widths, and space-padding.
//---- Header
std::string getFmt ( int wid, long val )
{
char buf[64];
sprintf ( buf, "% *ld", wid, val );
return buf;
}
#define FMT (getFmt(8,x).c_str())
//---- Put to use
printf ( " COUNT USED FREE\n" );
printf ( "A: %s %s %s\n", FMT(C[0]), FMT(U[0]), FMT(F[0]) );
printf ( "B: %s %s %s\n", FMT(C[1]), FMT(U[1]), FMT(F[1]) );
printf ( "C: %s %s %s\n", FMT(C[2]), FMT(U[2]), FMT(F[2]) );
//-------- Output
COUNT USED FREE
A: 354 148523 3283
B: 54138259 12392759 200391
C: 91239 3281 61423
The function and macro are designed so the printfs are more readable.
const double pi = boost::math::constants::pi<double>();
cv::Mat distance2ellipse(cv::Mat image, cv::RotatedRect ellipse){
float distance = 2.0f;
float angle = ellipse.angle;
cv::Point ellipse_center = ellipse.center;
float major_axis = ellipse.size.width/2;
float minor_axis = ellipse.size.height/2;
cv::Point pixel;
float a,b,c,d;
for(int x = 0; x < image.cols; x++)
{
for(int y = 0; y < image.rows; y++)
{
auto u = cos(angle*pi/180)*(x-ellipse_center.x) + sin(angle*pi/180)*(y-ellipse_center.y);
auto v = -sin(angle*pi/180)*(x-ellipse_center.x) + cos(angle*pi/180)*(y-ellipse_center.y);
distance = (u/major_axis)*(u/major_axis) + (v/minor_axis)*(v/minor_axis);
if(distance<=1)
{
image.at<cv::Vec3b>(y,x)[1] = 255;
}
}
}
return image;
}
It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.
Find the table in SQL manager right click it and select design, then right click the little key icon and select remove primary key.
I had the same issue and deleting the store and reading didn't work. I had to do the following.
Get a copy of OpenSSL. It is available for Windows. Or use a Linux box as they all pretty much all have it.
Run the following to export to a key file:
openssl pkcs12 -in certfile.pfx -out backupcertfile.key
openssl pkcs12 -export -out certfiletosignwith.pfx -keysig -in backupcertfile.key
Then in the project properties you can use the PFX file.
To add to the existing posts, sometimes coding to interfaces helps on large projects when developers work on separate components simultaneously. All you need is to define interfaces upfront and write code to them while other developers write code to the interface you are implementing.
Add following inside head tag
<script type="text/javascript">
angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
</script>
This will prevent the reload.
The language
attribute has been deprecated for a long time, and should not be used.
When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type
, so they standardized it to be the default value. Hence, you don't need type
either.
For pages in XHTML 1.0 or HTML 4.01 omitting type
is considered invalid. Try validating the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>
You will be informed of the following error:
Line 4, Column 41: required attribute "type" not specified
So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.
I have got the same error after removing eclipse
and installing it again.
Deleting the .metadata
directory and running eclipse -clean
does not work for me, but the following works for me:
sudo cp /usr/lib/jni/libswt-*3740.so ~/.swt/lib/linux/x86_64/
if you have a 32 bits based system do:
sudo cp /usr/lib/jni/libswt-*3740.so ~/.swt/lib/linux/x86/
If all the solutions above don't work, try to :
Add $i = 1; after /* Servers configuration */
in place of $i = 0 in your phpmyadmin config.inc.php file
Running XAMPP on local windows server, my mysql data files are not under the usual install path (C:\Xampp), but on another disk.
So now I have the phpmyadmin tables with the double __ like pma__table... and $i = 1;
There's a ViewportRuler service in angular CDK. It runs outside of the zone, and works with server side rendering too.
Here in simpler words:
DOM
Tree model parser (Object based) (Tree of nodes).
DOM loads the file into the memory and then parse- the file.
Has memory constraints since it loads the whole XML file before parsing.
DOM is read and write (can insert or delete nodes).
If the XML content is small, then prefer DOM parser.
Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.
Slower at run time.
SAX
Event based parser (Sequence of events).
SAX parses the file as it reads it, i.e. parses node by node.
No memory constraints as it does not store the XML content in the memory.
SAX is read only i.e. can’t insert or delete the node.
Use SAX parser when memory content is large.
SAX reads the XML file from top to bottom and backward navigation is not possible.
Faster at run time.
Success!
After checking the log files and making sure the permissions on php_openssl.dll were correct, I googled the warning and found more things to try.
So I:
I'm not sure which of these fixed my problem, but it's definately fixed now! :)
I found these things to try on this page: http://php.net/manual/en/install.windows.extensions.php
Thanks for your help!
I had a similar problem and solve it using the function encodeURIComponent
from JavaScript (documentation)
For example, in your case if you use:
<input id='hiddenId' type='hidden' value='chalk & cheese' />
and
encodeURIComponent($('#hiddenId').attr('value'))
you will get chalk%20%26%20cheese
. Even spaces are kept.
In my case, I had to encode one backslash and this code works perfectly
encodeURIComponent('name/surname')
and I got name%2Fsurname
This seems to restore the normal onResume()
behavior that you would expect. It plays well with pressing the home key to leave the app and then re-entering the app. onResume()
is not called twice in a row.
@Override
public void setUserVisibleHint(boolean visible)
{
super.setUserVisibleHint(visible);
if (visible && isResumed())
{
//Only manually call onResume if fragment is already visible
//Otherwise allow natural fragment lifecycle to call onResume
onResume();
}
}
@Override
public void onResume()
{
super.onResume();
if (!getUserVisibleHint())
{
return;
}
//INSERT CUSTOM CODE HERE
}
The error that you get does not seem to be related to the RequestHeader.
And you seem to be confusing Spring REST services with JAX-RS, your method signature should be something like:
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @RequestParam(value = "ID", defaultValue = "") String id) {
// your code goes here
}
And your REST class should have annotations like:
@Controller
@RequestMapping("/rest/")
Regarding the actual question, another way to get HTTP headers is to insert the HttpServletRequest into your method and then get the desired header from there.
Example:
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(HttpServletRequest request, @RequestParam(value = "ID", defaultValue = "") String id) {
String userAgent = request.getHeader("user-agent");
}
Don't worry about the injection of the HttpServletRequest because Spring does that magic for you ;)
1:
[{value:5}, {value:10}].reduce((previousValue, currentValue) => { return {value: previousValue.value + currentValue.value}})
>> Object {value: 15}
2:
[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })
>> 15
3:
[{value:5}, {value:10}].reduce(function (previousValue, currentValue) {
return {value: previousValue.value + currentValue.value};
})
>> Object {value: 15}
Try this;
var data = "";
data = "<option value = Some value> Some Option </option>";
options = [];
options.push(data);
select = document.getElementById("drop_down_id");
select.innerHTML = optionsHTML.join('\n');
Add Internet permission in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
In your Layout:
<?xml version="1.0" encoding="utf-8"?>
<WebView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
/>
In your Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
progressDialog = new ProgressDialog(this);
url_Api = "https://docs.microsoft.com/en-us/learn";
webView = this.findViewById(R.id.webView);
progressDialog.setMessage(getString(R.string.connection_Wait));
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
LoadUrlWebView( url_Api );
}catch (Exception e){
Log.w(TAG, "onCreate", e);
}
}
private void LoadUrlWebView( String url_api ) {
try {
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new MyWebChromeClient( url_api ));
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.loadUrl(url_api);
} catch (Exception e) {
Log.w(TAG, "setUpNavigationView", e);
}
}
private class MyWebChromeClient extends WebChromeClient {
private String urlAccount;
public MyWebChromeClient( String urlAccount ) {
this.urlAccount = urlAccount;
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
try {
//Tools.LogCat(context, "INSIDE MyWebChromeClient | onProgressChanged / newProgress1:" + newProgress);
progressDialog.setMessage(newProgress + "% " + getString(R.string.connection_Wait));
if (newProgress < 100 && !progressDialog.isShowing()) {
if (progressDialog != null)
progressDialog.show();
}
if (newProgress == 100) {
if (progressDialog != null)
progressDialog.dismiss();
}
}catch (Exception e){
Log.w( "onProgressChanged", e);
}
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
sharedPreferences = new Shared_Preferences( context );
sharedPreferences.setPageWebView(view.getUrl());
}
}
You can also install Git Credential Manager for Windows to save Git passwords in Windows credentials manager instead of _netrc
. This is a more secure way to store passwords.
Best way to customize Action bar onClickListener is onSupportNavigateUp()
This code will be helpful link for helping code
Newer versions: (from 8.4 - mentioned in release notes)
TABLE mytablename;
Longer but works on all versions:
SELECT * FROM mytablename;
You may wish to use \x
first if it's a wide table, for readability.
For long data:
SELECT * FROM mytable LIMIT 10;
or similar.
For wide data (big rows), in the psql
command line client, it's useful to use \x
to show the rows in key/value form instead of tabulated, e.g.
\x
SELECT * FROM mytable LIMIT 10;
Note that in all cases the semicolon at the end is important.
Double check if you are not able to use keys.
Otherwise use expect:
#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact
In theory, maven does not allow to use a property to set a parent version.
In your case, maven can simply not figure out that the 0.0.1-SNAPSHOT version of your parent pom is the one that is currently in your project, and so it tries to find it in your local repo. It probably finds one since it is a snapshot, but it is an old version that probably not contains your Dependency Management section.
There is a workaround though :
Simply change the parent section in the child pom with this :
<parent>
<groupId>com.sw.system4</groupId>
<artifactId>system4-parent</artifactId>
<version>${system4.version}</version>
<relativePath>../pom.xml</relativePath> <!-- this must match your parent pom location -->
</parent>
It all depends how you use Java or C# enums. How you use it will dictate the solution you'll choose in Ruby.
Try the native Set
type, for instance:
>> enum = Set['a', 'b', 'c']
=> #<Set: {"a", "b", "c"}>
>> enum.member? "b"
=> true
>> enum.member? "d"
=> false
>> enum.add? "b"
=> nil
>> enum.add? "d"
=> #<Set: {"a", "b", "c", "d"}>
Using the onclick
attribute or applying a function to your JS onclick
properties will erase your onclick
initialization in <head>
.
What you need to do is add click events on your button. To do that you’ll need the addEventListener
or attachEvent
(IE) method.
<!DOCTYPE html>
<html>
<head>
<script>
function addEvent(obj, event, func) {
if (obj.addEventListener) {
obj.addEventListener(event, func, false);
return true;
} else if (obj.attachEvent) {
obj.attachEvent('on' + event, func);
} else {
var f = obj['on' + event];
obj['on' + event] = typeof f === 'function' ? function() {
f();
func();
} : func
}
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1()">click</td></tr></table>
<script>
addEvent(document.getElementById('Save'), 'click', function() {
alert('hello');
});
</script>
</body>
</html>
You need to update the package list in your Ubuntu:
$ sudo apt-get update
$ sudo apt-get install <package_name>
Have implemented @Micah 's solution to generate a trendline with a few changes and thought I'd share:
order=2
)Rval=True
)Code:
def trendline(xd, yd, order=1, c='r', alpha=1, Rval=False):
"""Make a line of best fit"""
#Calculate trendline
coeffs = np.polyfit(xd, yd, order)
intercept = coeffs[-1]
slope = coeffs[-2]
power = coeffs[0] if order == 2 else 0
minxd = np.min(xd)
maxxd = np.max(xd)
xl = np.array([minxd, maxxd])
yl = power * xl ** 2 + slope * xl + intercept
#Plot trendline
plt.plot(xl, yl, c, alpha=alpha)
#Calculate R Squared
p = np.poly1d(coeffs)
ybar = np.sum(yd) / len(yd)
ssreg = np.sum((p(xd) - ybar) ** 2)
sstot = np.sum((yd - ybar) ** 2)
Rsqr = ssreg / sstot
if not Rval:
#Plot R^2 value
plt.text(0.8 * maxxd + 0.2 * minxd, 0.8 * np.max(yd) + 0.2 * np.min(yd),
'$R^2 = %0.2f$' % Rsqr)
else:
#Return the R^2 value:
return Rsqr
If you're trying to find the first count
multiples of m
, something like this would work:
def multiples(m, count):
for i in range(count):
print(i*m)
Alternatively, you could do this with range:
def multiples(m, count):
for i in range(0,count*m,m):
print(i)
Note that both of these start the multiples at 0
- if you wanted to instead start at m
, you'd need to offset it by that much:
range(m,(count+1)*m,m)
enumerate is trivial, and so is re-implementing it to accept a start:
def enumerate(iterable, start = 0):
n = start
for i in iterable:
yield n, i
n += 1
Note that this doesn't break code using enumerate without start argument. Alternatively, this oneliner may be more elegant and possibly faster, but breaks other uses of enumerate:
enumerate = ((index+1, item) for index, item)
The latter was pure nonsense. @Duncan got the wrapper right.
Loads n scripts one by one (useful if for example 2nd file needs the 1st one):
(function self(a,cb,i){
i = i || 0;
cb = cb || function(){};
if(i==a.length)return cb();
$.getScript(a[i++],self.bind(0,a,cb,i));
})(['list','of','script','urls'],function(){console.log('done')});
Okku's post worked for me in Edge. In order to get desired result on the iPhone, I had to use:
<thead class="sticky-top">
which didn't effect Edge.
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.
JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.
prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.
Subtract from another date object
var d = new Date();
d.setHours(d.getHours() - 2);
I had to transfer texts from an Excel file to an xliff file. We had some texts that were originally in uppercase but those translators didn't use uppercase so I used notepad++ as intermediate to do the conversion.
Since I had the mouse in one hand (to mark in Excel and activate the different windows) I disliked the predefined shortcut (Ctrl+Shift+U) as "U" is too far away for my left hand. I first switched it to Ctrl+Shift+X which worked.
Then I realized, that you can create macros easily, so I recorded one doing:
That macro got assigned that very shortcut (Ctrl+Shift+X) and made my life easy :)
@Howard Hinnant's answer is both correct and comprehensive. But it might be misunderstood if it's read too quickly, because std::terminate()
(whole process) happens to have the same name as the "terminating" that @Alexander V had in mind (1 thread).
Summary: "terminate 1 thread + forcefully (target thread doesn't cooperate) + pure C++11 = No way."
Developing from Hugues BR answer but using method swizzling I've arrived to a solution that is successfully changing all the fonts to a desired font in my app.
An approach with Dynamic Type should be what you should look for on iOS 7. The following solution is not using Dynamic Type.
Notes:
- initWithCoder:
override. However that won't cover all the cases;This solution uses two different methods to achieve the final result. The first is override the UIFont class methods + systemFontWithSize:
and similar with ones that use my alternatives (here I use "Zapfino" to leave no doubts that the replacement was successful).
The other method is to override - initWithCoder:
method on UIFont to replace any occurrence of CTFontRegularUsage
and similar by my alternatives.
This last method was necessary because I've found that UILabel
objects encoded in NIB files don't check the + systemFontWithSize:
methods to get their system font and instead encode them as UICTFontDescriptor
objects.
I've tried to override - awakeAfterUsingCoder:
but somehow it was getting called for every encoded object in my storyboard and causing crashes. Overriding - awakeFromNib
wouldn't allow me to read the NSCoder
object.
#import <objc/runtime.h>
NSString *const FORegularFontName = @"Zapfino";
NSString *const FOBoldFontName = @"Zapfino";
NSString *const FOItalicFontName = @"Zapfino";
#pragma mark - UIFont category
@implementation UIFont (CustomFonts)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+ (void)replaceClassSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector {
Method originalMethod = class_getClassMethod(self, originalSelector);
Method modifiedMethod = class_getClassMethod(self, modifiedSelector);
method_exchangeImplementations(originalMethod, modifiedMethod);
}
+ (void)replaceInstanceSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector {
Method originalDecoderMethod = class_getInstanceMethod(self, originalSelector);
Method modifiedDecoderMethod = class_getInstanceMethod(self, modifiedSelector);
method_exchangeImplementations(originalDecoderMethod, modifiedDecoderMethod);
}
+ (UIFont *)regularFontWithSize:(CGFloat)size
{
return [UIFont fontWithName:FORegularFontName size:size];
}
+ (UIFont *)boldFontWithSize:(CGFloat)size
{
return [UIFont fontWithName:FOBoldFontName size:size];
}
+ (UIFont *)italicFontOfSize:(CGFloat)fontSize
{
return [UIFont fontWithName:FOItalicFontName size:fontSize];
}
- (id)initCustomWithCoder:(NSCoder *)aDecoder {
BOOL result = [aDecoder containsValueForKey:@"UIFontDescriptor"];
if (result) {
UIFontDescriptor *descriptor = [aDecoder decodeObjectForKey:@"UIFontDescriptor"];
NSString *fontName;
if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontRegularUsage"]) {
fontName = FORegularFontName;
}
else if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontEmphasizedUsage"]) {
fontName = FOBoldFontName;
}
else if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontObliqueUsage"]) {
fontName = FOItalicFontName;
}
else {
fontName = descriptor.fontAttributes[@"NSFontNameAttribute"];
}
return [UIFont fontWithName:fontName size:descriptor.pointSize];
}
self = [self initCustomWithCoder:aDecoder];
return self;
}
+ (void)load
{
[self replaceClassSelector:@selector(systemFontOfSize:) withSelector:@selector(regularFontWithSize:)];
[self replaceClassSelector:@selector(boldSystemFontOfSize:) withSelector:@selector(boldFontWithSize:)];
[self replaceClassSelector:@selector(italicSystemFontOfSize:) withSelector:@selector(italicFontOfSize:)];
[self replaceInstanceSelector:@selector(initWithCoder:) withSelector:@selector(initCustomWithCoder:)];
}
#pragma clang diagnostic pop
@end
Add below code to styles.xml
file
<style name="LayoutPageTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
<item name="android:windowActionBarOverlay">true</item>
<!-- Support library compatibility -->
<item name="windowActionBarOverlay">true</item>
<item name="android:actionBarStyle">@style/TransparentActionBar</item>
</style>
<!-- ActionBar styles -->
<style name="TransparentActionBar"
parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">@android:color/transparent</item>
</style>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/transparent"
app:popupTheme="@style/AppTheme.PopupOverlay" />
Don't forget to write: android:background="@android:color/transparent"
Is there a way to have placeholders, like ? for column names? For example SELECT ? FROM TABLEA GROUP BY ?
Use dynamic query as below:
String queryString = "SELECT "+ colName+ " FROM TABLEA GROUP BY "+ colName;
If I want to simply run the above query and get a List what is the best way?
List<String> data = getJdbcTemplate().query(query, new RowMapper<String>(){
public String mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getString(1);
}
});
EDIT: To Stop SQL Injection, check for non word characters in the colName as :
Pattern pattern = Pattern.compile("\\W");
if(pattern.matcher(str).find()){
//throw exception as invalid column name
}
My problem was that I wanted all the columns in a row to have the same background. I grouped both by row and by column, and with the top two solutions here I got all the rows in column 1 with a colored background, all the rows in column 2 with a white background, all the rows in column 3 with a colored background, and so on. It's as if RowNumber
and bOddRow
(of Catch22's solution) pay attention to my column group instead of ignoring that and only alternating with a new row.
What I wanted is for all the columns in row 1 to have a white background, then all the columns in row 2 to have a colored background, then all the columns in row 3 to have a white background, and so on. I got this effect by using the selected answer but instead of passing Nothing
to RowNumber
, I passed the name of my column group, e.g.
=IIf(RowNumber("MyColumnGroupName") Mod 2 = 0, "AliceBlue", "Transparent")
Thought this might be useful to someone else.
This is commonly caused by running out of file descriptors.
There is the systems total file descriptor limit, what do you get from the command:
sysctl fs.file-nr
This returns counts of file descriptors:
<in_use> <unused_but_allocated> <maximum>
To find out what a users file descriptor limit is run the commands:
sudo su - <username>
ulimit -Hn
To find out how many file descriptors are in use by a user run the command:
sudo lsof -u <username> 2>/dev/null | wc -l
So now if you are having a system file descriptor limit issue you will need to edit your /etc/sysctl.conf file and add, or modify it it already exists, a line with fs.file-max and set it to a value large enough to deal with the number of file descriptors you need and reboot.
fs.file-max = 204708
I don't like ActionView
based solutions,
my idea is:
TextView
, that TextView
will be populated by
applicationwhen you need to draw a MenuItem
:
2.1. inflate layout
2.2. call measure()
& layout()
(otherwise view
will be 0px x 0px, it's too small for most use cases)
2.3. set the TextView
's text
2.4. make "screenshot" of the view
2.6. set MenuItem
's icon based on bitmap created on 2.4
profit!
so, result should be something like
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/counterPanel" android:layout_width="32dp" android:layout_height="32dp" android:background="@drawable/ic_menu_gallery"> <RelativeLayout android:id="@+id/counterValuePanel" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/counterBackground" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/unread_background" /> <TextView android:id="@+id/count" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:textSize="8sp" android:layout_centerInParent="true" android:textColor="#FFFFFF" /> </RelativeLayout> </FrameLayout>
@drawable/unread_background
is that green TextView
's background,
@drawable/ic_menu_gallery
is not really required here, it's just to preview layout's result in IDE.
add code into onCreateOptionsMenu
/onPrepareOptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.testAction);
menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_menu_gallery));
return true;
}
Implement build-the-icon method:
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
TextView textView = (TextView) view.findViewById(R.id.count);
textView.setText("" + count);
}
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
The complete code is here: https://github.com/cvoronin/ActionBarMenuItemCounter
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
For this we could straight away use String classe's
input.codePointAt(index);
I would like to give one more suggestion as to get whole of string converted to corresponding ascii codes, using java 8 for example, "abcde" to "979899100101".
String input = "abcde";
System.out.println(
input.codePoints()
.mapToObj((t) -> "" + t)
.collect(joining()));
Except for adding the following to sqlnet.ora
SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8
I also added the following to both the Client and Server, which resolved my issue
SQLNET.AUTHENTICATION_SERVICES = (NONE)
Also see post ORA-28040: No matching authentication protocol
A single method is all you need for all your random enums:
public static <T extends Enum<?>> T randomEnum(Class<T> clazz){
int x = random.nextInt(clazz.getEnumConstants().length);
return clazz.getEnumConstants()[x];
}
Which you'll use:
randomEnum(MyEnum.class);
I also prefer to use SecureRandom as:
private static final SecureRandom random = new SecureRandom();
In my case I have 3 params, one of them is string (mensaje):
exec("C:\wamp\bin\php\php5.5.12\php.exe C:/test/N/trunk/api/v1/Process.php $idTest2 $idTest3 \"$mensaje\" >> c:/log.log &");
In my Process.php I have this code:
if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3]))
{
die("Error.");
}
$idCurso = $argv[1];
$idDestino = $argv[2];
$mensaje = $argv[3];
Download and include this plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>
and use like
if(CryptoJS.MD5($("#txtOldPassword").val())) != oldPassword) {
}
//Following lines shows md5 value
//var hash = CryptoJS.MD5("Message");
//alert(hash);
Had the same problem, thanks mikej.
In WLS 10.3 this configuration can be found in Services > JTA menu, or if you click on the domain name (first item in the menu) - on the Configuration > JTA tabs.
quit()
: Quits this driver, closing every associated window that was open.
close()
: Close the current window, quitting the browser if it's the last window currently open.
Problem Solved,
I edited the file /etc/postfix/master.cf
and commented
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject
and changed the line from
-o smtpd_tls_security_level=encrypt
to
-o smtpd_tls_security_level=may
And worked on fine
Which Mac version are you using? try these paths
/System/Library/Frameworks/JavaVM.framework/ OR
/usr/libexec/java_home
This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X
You can use like this
$(".jsgrid-cell").each(function(i,v){
var txt=$(v).text();
if(txt.length>100){
var shortText=txt.substring(0, 100)+
"<span onclick='$(this).hide();$(this).next().toggle();'>"+
"..."+
"</span>"+
"<span style='display:none'>"+
txt.substring(100, txt.length)+
"</span>";
$(v).html(shortText );
}
});
After enough googling I found the answer from controller you need only a backslash like return \Response::json(['success' => 'hi, atiq']);
. Or you can just return the array return array('success' => 'hi, atiq');
which will be rendered as json in Laravel version 5.2 .
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
This is called a correlated update
UPDATE table1 t1
SET (name, desc) = (SELECT t2.name, t2.desc
FROM table2 t2
WHERE t1.id = t2.id)
WHERE EXISTS (
SELECT 1
FROM table2 t2
WHERE t1.id = t2.id )
Assuming the join results in a key-preserved view, you could also
UPDATE (SELECT t1.id,
t1.name name1,
t1.desc desc1,
t2.name name2,
t2.desc desc2
FROM table1 t1,
table2 t2
WHERE t1.id = t2.id)
SET name1 = name2,
desc1 = desc2
There is also EXISTS
:
SELECT count(*) AS post_ct
FROM posts p
WHERE EXISTS (SELECT FROM votes v WHERE v.post_id = p.id);
In Postgres and with multiple entries on the n-side like you probably have, it's generally faster than count(DISTINCT post_id)
:
SELECT count(DISTINCT p.id) AS post_ct
FROM posts p
JOIN votes v ON v.post_id = p.id;
The more rows per post there are in votes
, the bigger the difference in performance. Test with EXPLAIN ANALYZE
.
count(DISTINCT post_id)
has to read all rows, sort or hash them, and then only consider the first per identical set. EXISTS
will only scan votes
(or, preferably, an index on post_id
) until the first match is found.
If every post_id
in votes
is guaranteed to be present in the table posts
(referential integrity enforced with a foreign key constraint), this short form is equivalent to the longer form:
SELECT count(DISTINCT post_id) AS post_ct
FROM votes;
May actually be faster than the EXISTS
query with no or few entries per post.
The query you had works in simpler form, too:
SELECT count(*) AS post_ct
FROM (
SELECT FROM posts
JOIN votes ON votes.post_id = posts.id
GROUP BY posts.id
) sub;
To verify my claims I ran a benchmark on my test server with limited resources. All in a separate schema:
Fake a typical post / vote situation:
CREATE SCHEMA y;
SET search_path = y;
CREATE TABLE posts (
id int PRIMARY KEY
, post text
);
INSERT INTO posts
SELECT g, repeat(chr(g%100 + 32), (random()* 500)::int) -- random text
FROM generate_series(1,10000) g;
DELETE FROM posts WHERE random() > 0.9; -- create ~ 10 % dead tuples
CREATE TABLE votes (
vote_id serial PRIMARY KEY
, post_id int REFERENCES posts(id)
, up_down bool
);
INSERT INTO votes (post_id, up_down)
SELECT g.*
FROM (
SELECT ((random()* 21)^3)::int + 1111 AS post_id -- uneven distribution
, random()::int::bool AS up_down
FROM generate_series(1,70000)
) g
JOIN posts p ON p.id = g.post_id;
All of the following queries returned the same result (8093 of 9107 posts had votes).
I ran 4 tests with EXPLAIN ANALYZE
ant took the best of five on Postgres 9.1.4 with each of the three queries and appended the resulting total runtimes.
As is.
After ..
ANALYZE posts;
ANALYZE votes;
After ..
CREATE INDEX foo on votes(post_id);
After ..
VACUUM FULL ANALYZE posts;
CLUSTER votes using foo;
count(*) ... WHERE EXISTS
count(DISTINCT x)
- long form with joincount(DISTINCT x)
- short form without joinBest time for original query in question:
For simplified version:
@wildplasser's query with a CTE uses the same plan as the long form (index scan on posts, index scan on votes, merge join) plus a little overhead for the CTE. Best time:
Index-only scans in the upcoming PostgreSQL 9.2 can improve the result for each of these queries, most of all for EXISTS
.
Related, more detailed benchmark for Postgres 9.5 (actually retrieving distinct rows, not just counting):
A static function is one that can be called on the class itself, as opposed to an instance of the class.
For example a non-static would be:
Person* tom = new Person();
tom->setName("Tom");
This method works on an instance of the class, not the class itself. However you can have a static method that can work without having an instance. This is sometimes used in the Factory pattern:
Person* tom = Person::createNewPerson();
I came across this thread when I have the same problem. I only need to get the first element then I re-analyze my code until this came up to my mind.
$firstElement = true;
foreach ($reportData->result() as $row)
{
if($firstElement) { echo "first element"; $firstElement=false; }
// Other lines of codes here
}
The above codes are great and complete but if you only need just the first element then you may try this code.
Or simply:
view.getLayoutParams().width = 400;
view.requestLayout();
The first column of output is the index of each item in enumm
and the second one is its keys. If you want to iterate your dictionary then use .items():
for k, v in enumm.items():
print(k, v)
And the output should look like:
0 1
1 2
2 3
4 4
5 5
6 6
7 7
Here is an easy example on how to deep clone any object: Implement serializable first
public class CSVTable implements Serializable{
Table<Integer, Integer, String> table;
public CSVTable() {
this.table = HashBasedTable.create();
}
public CSVTable deepClone() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (CSVTable) ois.readObject();
} catch (IOException e) {
return null;
} catch (ClassNotFoundException e) {
return null;
}
}
}
And then
CSVTable table = new CSVTable();
CSVTable tempTable = table.deepClone();
is how you get the clone.
There are two problems in your code.
dbConfig.php
<?php
$conn=mysqli_connect("localhost","root","password","testDB");
if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
?>
index.php
include('dbConfig.php');
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>test</title>
</head>
<body>
<?php
if(isset($_POST['save']))
{
$sql = "INSERT INTO users (username, password, email)
VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";
$result = mysqli_query($conn,$sql);
}
?>
<form action="index.php" method="post">
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>
<label id="first">Password</label><br/>
<input type="password" name="password"><br/>
<label id="first">Email</label><br/>
<input type="text" name="email"><br/>
<button type="submit" name="save">save</button>
</form>
</body>
</html>
I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.
The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.
SHORT ANSWER (should be similar for MinGW too but I haven't tried it):
LONG ANSWER:
Below are the detailed steps that solved this issue for me:
Uninstall/delete the previous version of Cygwin (MinGW in your case)
Make sure that CLion is up-to-date
Run Cygwin setup (x64 for my 64-bit OS)
Install at least the following packages for Cygwin:
gcc
g++
make
Cmake
gdb
Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).
Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows
[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']
Add the 'bin' folder to the Path variable. For Cygwin, I added:
D:\cygwin64\bin
Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings
Select 'Build, Execution, Deployment' and then click on 'Toolchains'
Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)
For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)
'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]
Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'
See screenshot: Check all paths to the compiler, make and gdb
See screenshot: Check the configuration to run the project
There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active
Build your project and then run the project. You should see the output in the terminal window
Hope this helps! Good luck and enjoy CLion.
continue
is kind of like goto
. Are you familiar with break
? It's easier to think about them in contrast:
break
terminates the loop (jumps to the code below it).
continue
terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.
They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:
<input type="radio" checked="checked">
...and you got it.
Cheers!
I know this is old question. But maybe this can help you
var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';
JSON.stringify(JSON.parse(jsonStr), null, 2);
JSON.stringify(JSON.parse(jsonStr));
Here is working code for converting an image from a base64 string to an Image
object and storing it in a folder with unique file name:
public void SaveImage()
{
string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
//this is a simple white background image
var myfilename= string.Format(@"{0}", Guid.NewGuid());
//Generate unique filename
string filepath= "~/UserImages/" + myfilename+ ".jpeg";
var bytess = Convert.FromBase64String(strm);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country()
{
Cities = new List<City>();
}
}
public class City
{
public string Name { get; set; }
}
List<Country> Countries = new List<Country>
{
new Country
{
Name = "Germany",
Cities =
{
new City {Name = "Berlin"},
new City {Name = "Hamburg"}
}
},
new Country
{
Name = "England",
Cities =
{
new City {Name = "London"},
new City {Name = "Birmingham"}
}
}
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo
Box.ValueMember = "Name";
This is the code I am using now.
This is quite an old question, but I offer this answer because the previous answers do not cope with items in the list that are not strings (or some kind of iterable object). Such items would cause the entire list comprehension to fail with an exception.
To gracefully deal with such items in the list by skipping the non-iterable items, use the following:
[el for el in lst if isinstance(el, collections.Iterable) and (st in el)]
then, with such a list:
lst = [None, 'abc-123', 'def-456', 'ghi-789', 'abc-456', 123]
st = 'abc'
you will still get the matching items (['abc-123', 'abc-456']
)
The test for iterable may not be the best. Got it from here: In Python, how do I determine if an object is iterable?
It can be done easily & automatically if that textfield
is in a table's cell (even when the table.scrollable = NO
).
NOTE that: the position and size of the table must be reasonable. e.g:
height = 10
, and the textfield
in it must be scrolled up 100 when keyboard appears in order to be visible, then that textfield will be out of the table's bound.You need an appropriate permission in manifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
out.flush()
check the out
is not null..
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PhysicsSketchpad";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "sketchpad" + pad.t_id + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
For the case: "This has not been pushed, only committed." - if you use IntelliJ (or another JetBrains IDE) and you haven't pushed changes yet you can do next.
Done.
This will "uncommit" your changes and return your git status to the point before your last local commit. You will not lose any changes you made.
git reset --hard && git clean -dfx
or, zsh provides a 'gpristine' alias:
alias gpristine='git reset --hard && git clean -dfx'
Which is really handy. (warning: The "-x" will also delete 'git ignored' files, so remove this if it is not what you want)
If working on a forked repo, make sure to fetch and reset from the correct repo/branch, for example:
git fetch upstream && git reset --hard upstream/master && git clean -df
It probably depends on the type of collection you are enumerating and the implementation of its indexer. In general though, using foreach
is likely to be a better approach.
Also, it'll work with any IEnumerable
- not just things with indexers.
Hackbod's is one of the best answers on Stack Overflow. It throws light on a very obscure subject. It helped me a lot.
Another really helpful resource is this must-see video: Google I/O 2011: Memory management for Android Apps
UPDATE:
Process Stats, a service to discover how your app manages memory explained at the blog post Process Stats: Understanding How Your App Uses RAM by Dianne Hackborn:
SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
You just need to set the table cell padding to zero. Here's a jsfiddle (using Bootstrap 2.3.2) with your code slightly modified:
http://jsfiddle.net/marciowerner/fhjgn7b5/4/
The javascript is optional and only needed if you want to use a cell padding other than zero.
$('.collapse').on('show.bs.collapse', function() {_x000D_
$(this).parent().removeClass("zeroPadding");_x000D_
});_x000D_
_x000D_
$('.collapse').on('hide.bs.collapse', function() {_x000D_
$(this).parent().addClass("zeroPadding");_x000D_
});
_x000D_
.zeroPadding {_x000D_
padding: 0 !important;_x000D_
}
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<script type="text/javascript" src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<table class="table table-bordered table-striped">_x000D_
<tr>_x000D_
<td>_x000D_
<button type="button" class="btn" data-toggle="collapse" data-target="#collapseme">Click to expand</button>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="zeroPadding">_x000D_
<div class="collapse out" id="collapseme">Should be collapsed</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>
_x000D_
I know this is old, but came across it looking for a simpler way, and this is how i do it, just create a new list of the same object and add it to the one you want to use e.g.
Subject[] subjectsList = {new Subject1{....}, new Subject2{....}, new Subject3{....}}
univStudent.subjects = subjectsList ;
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
A simple working configuration using
@TestPropertySource and properties
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {"spring.config.location=classpath:another.yml"})
public class TestClass {
@Test
public void someTest() {
}
}
You could also just use the old fashion 'strtok'
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Its a bit wonky but doesn't involve using boost (not that boost is a bad thing).
You basically call strtok with the string you want to split and the delimiter (in this case a space) and it will return you a char*.
From the link:
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.
You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.
Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.
One of the basic and simple thing which leads to this error is: No Internet Connection
Turn on the Internet Connection of your device first.
(May be we'll forget to do so)
open the right navigation pane where your project files exist OR JSUT click on cmd + 1 Then search for "Recovered References" Folder open it all red files (delete them) then everything will work so fine .
In VirtualBox you should add custom resolution via the command:
VBoxManage setextradata "VM name" "CustomVideoMode1" "800x480x16"
instead of editing a .vbox
file.
This solution works fine for me!
I solved this. double click this error leads to behavior.
for my case. a miss match of debug and release mod kills my afternoon.
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">copy %(Filename)%(Extension) ..\..\cvd\
</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
</CustomBuild>
That's not JSON at all, it's just Javascript objects. JSON is a text representation of data, that uses a subset of the Javascript syntax.
The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)
What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items
to access the array.
For example, to add another item to the array using dynamic values:
// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);
I have been using this one....
/^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/
It allows that +
before @
([email protected])