I do realize that my answer is way late for this question but I think the community would like a newer approach to this issue.
from sh import gunzip
gunzip('/tmp/file1.gz')
There are $watchGroup
and $watchCollection
as well. Specifically, $watchGroup
is really helpful if you want to call a function to update an object which has multiple properties in a view that is not dom object, for e.g. another view in canvas, WebGL or server request.
Here, the documentation link.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
The problem is that for json.load
you should pass a file like object with a read
function defined. So either you use json.load(response)
or json.loads(response.read())
.
I had the same problem, even after following Sinhue's setup, but I solved it.
The problem was that that something (Tomcat?) was forwarding from "/" to "/index.jsp" when I had the file index.jsp in my WebContent directory. When I removed that, the request did not get forwarded anymore.
What I did to diagnose the problem was to make a catch-all request handler and printed the servlet path to the console. This showed me that even though the request I was making was for http://localhost/myapp/, the servlet path was being changed to "/index.html". I was expecting it to be "/".
@RequestMapping("*")
public String hello(HttpServletRequest request) {
System.out.println(request.getServletPath());
return "hello";
}
So in summary, the steps you need to follow are:
<url-pattern>/</url-pattern>
RequestMapping("/")
Hope this helps.
The best way for centering your element it is using .center-block
helper class. But must your bootstrap version not less than 3.1.1
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet" />_x000D_
<div class="row">_x000D_
<div class="col-lg-3 center-block">_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control">_x000D_
<span class="input-group-btn">_x000D_
<button class="btn btn-default" type="button">Go!</button>_x000D_
</span>_x000D_
</div>_x000D_
<!-- /input-group -->_x000D_
</div>_x000D_
<!-- /.col-lg-6 -->_x000D_
</div>_x000D_
<!-- /.row -->
_x000D_
java.lang.String
class has method substring
not substr
, thats the error in your program.
Moreover you can do this in one single line if you are ok in using regular expression.
a.replaceAll("\\s+","");
Solution with utl_encode.base64_encode
and utl_encode.base64_decode
have one limitation, they work only with strings up to 32,767 characters/bytes.
In case you have to convert bigger strings you will face several obstacles.
BASE64_ENCODE
the function has to read 3 Bytes and transform them. In case of Multi-Byte characters (e.g. öäüè€
stored at UTF-8, aka AL32UTF8
) 3 Character are not necessarily also 3 Bytes. In order to read always 3 Bytes you have to convert your CLOB
into BLOB
first.BASE64_DECODE
. The function has to read 4 Bytes and transform them into 3 Bytes. Those 3 Bytes are not necessarily also 3 CharactersCR
and/or LF
) character each 64 characters. Such new-line characters have to be ignored while decoding.Taking all this into consideration the full featured solution could be this one:
CREATE OR REPLACE FUNCTION DecodeBASE64(InBase64Char IN OUT NOCOPY CLOB) RETURN CLOB IS
blob_loc BLOB;
clob_trim CLOB;
res CLOB;
lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
warning INTEGER;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InBase64Char);
amount INTEGER := 1440; -- must be a whole multiple of 4
buffer RAW(1440);
stringBuffer VARCHAR2(1440);
-- BASE64 characters are always simple ASCII. Thus you get never any Mulit-Byte character and having the same size as 'amount' is sufficient
BEGIN
IF InBase64Char IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen<= 32000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(InBase64Char)));
END IF;
-- UTL_ENCODE.BASE64_DECODE is limited to 32k, process in chunks if bigger
-- Remove all NEW_LINE from base64 string
ClobLen := DBMS_LOB.GETLENGTH(InBase64Char);
DBMS_LOB.CREATETEMPORARY(clob_trim, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
stringBuffer := REPLACE(REPLACE(DBMS_LOB.SUBSTR(InBase64Char, amount, read_offset), CHR(13), NULL), CHR(10), NULL);
DBMS_LOB.WRITEAPPEND(clob_trim, LENGTH(stringBuffer), stringBuffer);
read_offset := read_offset + amount;
END LOOP;
read_offset := 1;
ClobLen := DBMS_LOB.GETLENGTH(clob_trim);
DBMS_LOB.CREATETEMPORARY(blob_loc, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
buffer := UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR(clob_trim, amount, read_offset)));
DBMS_LOB.WRITEAPPEND(blob_loc, DBMS_LOB.GETLENGTH(buffer), buffer);
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.CREATETEMPORARY(res, TRUE);
DBMS_LOB.CONVERTTOCLOB(res, blob_loc, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
DBMS_LOB.FREETEMPORARY(blob_loc);
DBMS_LOB.FREETEMPORARY(clob_trim);
RETURN res;
END DecodeBASE64;
CREATE OR REPLACE FUNCTION EncodeBASE64(InClearChar IN OUT NOCOPY CLOB) RETURN CLOB IS
dest_lob BLOB;
lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
warning INTEGER;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InClearChar);
amount INTEGER := 1440; -- must be a whole multiple of 3
-- size of a whole multiple of 48 is beneficial to get NEW_LINE after each 64 characters
buffer RAW(1440);
res CLOB := EMPTY_CLOB();
BEGIN
IF InClearChar IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen <= 24000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW(InClearChar)));
END IF;
-- UTL_ENCODE.BASE64_ENCODE is limited to 32k/(3/4), process in chunks if bigger
DBMS_LOB.CREATETEMPORARY(dest_lob, TRUE);
DBMS_LOB.CONVERTTOBLOB(dest_lob, InClearChar, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
LOOP
EXIT WHEN read_offset >= dest_offset;
DBMS_LOB.READ(dest_lob, amount, read_offset, buffer);
res := res || UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(buffer));
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.FREETEMPORARY(dest_lob);
RETURN res;
END EncodeBASE64;
Go to Start
Type regsvr32 hhctrl.ocx
You should get a success message like:
" DllRegisterServer in hhctrl.ocx succeeded "
Now try to open your CHM file again.
Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").
$.ajax( {
url: "http://yourlocationtopost/",
type: 'POST',
data: new FormData(document.getElementById("yourFormElementID")),
processData: false,
contentType: false
} ).done(function(d) {
console.log('done');
});
try
public void PrintGeneric<T>(T test) where T: ITest
{
Console.WriteLine("Generic : " + test.@var);
}
as @Ash Burlaczenko has said you cant name a variable after a keyword, if you reallllly want this prefix with @ symbol to escape the keyword
If any doubt in this code, please ask your questions(Here for gmail Port number is 587)
// code to Send Mail
// Add following Lines in your web.config file
// <system.net>
// <mailSettings>
// <smtp>
// <network host="smtp.gmail.com" port="587" userName="[email protected]" password="yyy" defaultCredentials="false"/>
// </smtp>
// </mailSettings>
// </system.net>
// Add below lines in your config file inside appsetting tag <appsetting></appsetting>
// <add key="emailFromAddress" value="[email protected]"/>
// <add key="emailToAddress" value="[email protected]"/>
// <add key="EmailSsl" value="true"/>
// Namespace Used
using System.Net.Mail;
public static bool SendingMail(string subject, string content)
{
// getting the values from config file through c#
string fromEmail = ConfigurationSettings.AppSettings["emailFromAddress"];
string mailid = ConfigurationSettings.AppSettings["emailToAddress"];
bool useSSL;
if (ConfigurationSettings.AppSettings["EmailSsl"] == "true")
{
useSSL = true;
}
else
{
useSSL = false;
}
SmtpClient emailClient;
MailMessage message;
message = new MailMessage();
message.From = new MailAddress(fromEmail);
message.ReplyTo = new MailAddress(fromEmail);
if (SetMailAddressCollection(message.To, mailid))
{
message.Subject = subject;
message.Body = content;
message.IsBodyHtml = true;
emailClient = new SmtpClient();
emailClient.EnableSsl = useSSL;
emailClient.Send(message);
}
return true;
}
// if you are sending mail in group
private static bool SetMailAddressCollection(MailAddressCollection toAddresses, string mailId)
{
bool successfulAddressCreation = true;
toAddresses.Add(new MailAddress(mailId));
return successfulAddressCreation;
}
Here is a slightly simpler version that I found. It reads the entire file in one go and only requires a single using
directive.
byte[] ComputeHash(string filePath)
{
using (var md5 = MD5.Create())
{
return md5.ComputeHash(File.ReadAllBytes(filePath));
}
}
A sha256 is 256 bits long -- as its name indicates.
Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64)
, or even a char(64)
, as the length is always the same, not varying at all.
And the demo :
$hash = hash('sha256', 'hello, world!');
var_dump($hash);
Will give you :
$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"
i.e. a string with 64 characters.
You can build your HttpContent
using the combination of JObject
to avoid and JProperty
and then call ToString()
on it when building the StringContent
:
/*{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}*/
JObject payLoad = new JObject(
new JProperty("agent",
new JObject(
new JProperty("name", "Agent Name"),
new JProperty("version", 1)
),
new JProperty("username", "Username"),
new JProperty("password", "User Password"),
new JProperty("token", "xxxxxx")
)
);
using (HttpClient client = new HttpClient())
{
var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return JObject.Parse(responseBody);
}
}
It depends on the database you are using. MySQL for example supports the (non-standard) group_concat function. So you could write:
SELECT GROUP_CONCAT(ModuleValue) FROM Table_X WHERE ModuleID=@ModuleID
Group-concat is not available at all database servers though.
something like:
$("ul#wizard li").click(function () {
var index = $("ul#wizard li").index(this);
alert("index is: " + index)
});
You can run the DOS ping.exe command from javaScript using the folowing:
function ping(ip)
{
var input = "";
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);
while (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.ReadLine() + "<br />";
}
return input;
}
Is this what was asked for, or am i missing something?
Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code
class Program
{
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";
//duplicate file path
string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
//provide source and destination file paths
File.Copy(pathToOriginalFile, PathForDuplicateFile);
Console.ReadKey();
}
}
Source: File I/O in C# (Read, Write, Delete, Copy file using C#)
If you need multiple branches on the same condition, use an if:
if (A == 6)
f(1, 2, 3);
else
f(4, 5, 6);
If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:
f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );
Also, you can use the ternary operator in initialization.
const int i = (A == 6)? 1 : 4;
Doing that with if is very messy:
int i_temp;
if (A == 6)
i_temp = 1;
else
i_temp = 4;
const int i = i_temp;
You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.
State machines can be very complex for a complex problem. They are also subject to unexpected bugs. They can turn into a nightmare if someone runs into a bug or needs to change the logic in the future. They are also difficult to follow and debug without the state diagram. Structured programming is much better (for example you would probably not use a state machine at mainline level). You can use structured programming even in interrupt context (which is where state machines are usually used). See this article "Macros to simulate multi-tasking/blocking code at interrupt level" found at codeproject.com.
With Spring Security in Spring Boot 2 to configure CORS globally (e.g. enabled all request for development) you can do:
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and().authorizeRequests()
.anyRequest().permitAll()
.and().csrf().disable();
}
The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector<const int>
is not allowed.
I solved this issue by going into Properties -> Java Build Path and reordering my source folder so it was above the JRE System Library.
Soft Link:
soft or symbolic is more of a short cut to the original file....if you delete the original the shortcut fails and if you only delete the short cut nothing happens to the original.
Soft link Syntax: ln -s Pathof_Target_file link
Output : link -> ./Target_file
Proof: readlink link
Also in ls -l link
output you will see the first letter in lrwxrwxrwx
as l which is indication that the file is a soft link.
Deleting the link: unlink link
Note: If you wish, your softlink can work even after moving it somewhere else from the current dir. Make sure you give absolute path and not relative path while creating a soft link. i.e.(starting from /root/user/Target_file and not ./Target_file)
Hard Link:
Hard link is more of a mirror copy or multiple paths to the same file. Do something to file1 and it appears in file 2. Deleting one still keeps the other ok.
The inode(or file) is only deleted when all the (hard)links or all the paths to the (same file)inode has been deleted.
Once a hard link has been made the link has the inode of the original file. Deleting renaming or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.
Hard Link syntax: ln Target_file link
Output: A file with name link will be created with the same inode number as of Targetfile.
Proof: ls -i link Target_file
(check their inodes)
Deleting the link: rm -f link
(Delete the link just like a normal file)
Note: Symbolic links can span file systems as they are simply the name of another file. Whereas hard links are only valid within the same File System.
Symbolic links have some features hard links are missing:
you know immediately where a symbolic link points to while with hard links, you need to explore the whole file system to find files sharing the same inode.
# find / -inum 517333
/home/bobbin/sync.sh /root/synchro
hard-links cannot point to directories.
The hard links have two limitations:
In short set cascade type to all , will do a job; For an example in your model. Add Code like this . @OneToMany(mappedBy = "receipt", cascade=CascadeType.ALL) private List saleSet;
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href
.
There's a nice bookmarklet called Visual Event that can show you all the events attached to an element. It has color-coded highlights for different types of events (mouse, keyboard, etc.). When you hover over them, it shows the body of the event handler, how it was attached, and the file/line number (on WebKit and Opera). You can also trigger the event manually.
It can't find every event because there's no standard way to look up what event handlers are attached to an element, but it works with popular libraries like jQuery, Prototype, MooTools, YUI, etc.
Importing .cer
certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security
worked for me, as opposed to attemps to generate and use my own keystore.
java_home\jre\lib\security
cmd
and CTRL+SHIFT+ENTERyourAliasName
and path\to\certificate.cer
respectively) ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer
This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.
you have problems with " :
<a href=<?php echo "'www.someotherwebsite.com'><img src='". url::file_loc('img'). "media/img/twitter.png' style='vertical-align: middle' border='0'></a>"; ?>
As this is one of the first hits in the search engines, and none of the above seems to work for MongoDB 3.x, here is one regex search that does work:
db.users.find( { 'name' : { '$regex' : yourvalue, '$options' : 'i' } } )
No need to create and extra index or alike.
When you have related tables you often have one-to-many or many-to-many relationships. So when you join to TableB each record in TableA many have multiple records in TableB. This is normal and expected.
Now at times you only need certain columns and those are all the same for all the records, then you would need to do some sort of group by or distinct to remove the duplicates. Let's look at an example:
TableA
Id Field1
1 test
2 another test
TableB
ID Field2 field3
1 Test1 something
1 test1 More something
2 Test2 Anything
So when you join them and select all the files you get:
select *
from tableA a
join tableb b on a.id = b.id
a.Id a.Field1 b.id b.field2 b.field3
1 test 1 Test1 something
1 test 1 Test1 More something
2 another test 2 2 Test2 Anything
These are not duplicates because the values of Field3 are different even though there are repeated values in the earlier fields. Now when you only select certain columns the same number of records are being joined together but since the columns with the different information is not being displayed they look like duplicates.
select a.Id, a.Field1, b.field2
from tableA a
join tableb b on a.id = b.id
a.Id a.Field1 b.field2
1 test Test1
1 test Test1
2 another test Test2
This appears to be duplicates but it is not because of the multiple records in TableB.
You normally fix this by using aggregates and group by, by using distinct or by filtering in the where clause to remove duplicates. How you solve this depends on exactly what your business rule is and how your database is designed and what kind of data is in there.
My promisify version of a callback
function is the P
function:
var P = function() {_x000D_
var self = this;_x000D_
var method = arguments[0];_x000D_
var params = Array.prototype.slice.call(arguments, 1);_x000D_
return new Promise((resolve, reject) => {_x000D_
if (method && typeof(method) == 'function') {_x000D_
params.push(function(err, state) {_x000D_
if (!err) return resolve(state)_x000D_
else return reject(err);_x000D_
});_x000D_
method.apply(self, params);_x000D_
} else return reject(new Error('not a function'));_x000D_
});_x000D_
}_x000D_
var callback = function(par, callback) {_x000D_
var rnd = Math.floor(Math.random() * 2) + 1;_x000D_
return rnd > 1 ? callback(null, par) : callback(new Error("trap"));_x000D_
}_x000D_
_x000D_
callback("callback", (err, state) => err ? console.error(err) : console.log(state))_x000D_
callback("callback", (err, state) => err ? console.error(err) : console.log(state))_x000D_
callback("callback", (err, state) => err ? console.error(err) : console.log(state))_x000D_
callback("callback", (err, state) => err ? console.error(err) : console.log(state))_x000D_
_x000D_
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))_x000D_
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))_x000D_
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))_x000D_
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))
_x000D_
The P
function requires that the callback signature must be callback(error,result)
.
Could be SELinux. Check the appropriate log file (/var/log/messages? - been a while since I've used a RedHat derivative) to see if that's blocking the access.
h1{
background:url("../images/logo.png") no-repeat;
height:180px;
width:200px;
display:inline-block;
font-size:0px !important;
text-intent:-9999999px !important;
color:transparent !important;
}
I think you can use layout:weight = 5
instead android:lines = 5
because when you port your app to smaller device - it does it nicely.. well, both attributes will accomplish your job..
In my case, I backed up and then deleted the file that Git was complaining about, committed, then I was able to finally check out another branch.
I then replaced the file, copied back in the contents and continued as though nothing happened.
You must of already called the session start maybe being called again through an include?
if( ! $_SESSION)
{
session_start();
}
Ok, I realize that this is a bit late... maybe this alternative wasn't available at the moment of writing the post?
Anyway, I've found installing the pos package via Fink (a prerequisite in this case, maybe there is something similar for those who uses MacPorts?) to be the easiest solution. You get two commands:
Yes, you have to switch to the Terminal window before writing cdf, but I suppose that's quite cheap comparing to clicking a button in the Finder toolbar. And it works with iTerm as well, you don't have to download a separate Finder toolbar button that opens an iTerm window. This is the same approach as proposed by PCheese, but you don't have to clutter your .bash_profile.
this is an out of topic answer, but, for those who are interested, it maybe valuable.
As in @John Kugelman's answer, % is related to job specification. how to efficiently find that? use less's &pattern command, seems man use less pager (not that sure), in man bash type &% then type Enter will only show lines that containing '%', to reshow all, type &. then Enter.
Add /usr/local/bin
to your PATH
environment variable, earlier in the list than /usr/bin
.
Generally this is done in your shell's rc file, e.g. for bash, you'd put this in .bashrc
:
export PATH="/usr/local/bin:$PATH"
This will cause your shell to look first for a python
in /usr/local/bin
, before it goes with the one in /usr/bin
.
(Of course, this means you also need to have /usr/local/bin/python
point to python2.7
- if it doesn't already, you'll need to symlink it.)
For everyone having the same issue, make sure you actually wrote "120px" instead of only "120". This was my mistake and it drove me crazy.
I am getting this issue when using owl carousal and scrolling the images.
So get solved just adding below CSS in your page.
.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}
or
.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}
JavaScript is not required, and no outrageously huge max-height is needed. Instead, set your max-height
on your text elements, and use a font relative unit such as rem
or em
. This way, you can set a maximum height larger than your container, while avoiding a delay or "popping" when the menu closes:
HTML
<nav>
<input type="checkbox" />
<ul>
<li>Link 1</li>
<li>Link 1</li>
<li>Link 1</li>
<li>Link 1</li>
</ul>
</nav>
CSS
nav input + ul li { // Notice I set max-height on li, not ul
max-height: 0;
}
nav input:checked + ul li {
max-height: 3rem; // A little bigger to allow for text-wrapping - but not outrageous
}
See an example here: http://codepen.io/mindfullsilence/pen/DtzjE
You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.
Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.
Here is a working code I have written for you:
https://www.funfun.io/1/#/edit/5a58c6368dfd67466879ed27
In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.
I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file):
Percentage (%) = 100 x partial value / total value
It automatically calculates the total and pourcentage even if you add more categories.
I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:
var trace1 = {
x: xValue,
y: data,
type: 'bar',
text: yValue,
textposition: 'auto',
hoverinfo: 'none',
marker: {
color: 'yellow',
opacity: 0.6,
line: {
color: 'yellow',
width: 1.5
}
}
};
It is rather self explanatory, the text
is where you put the percentage.
Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:
I know it is an old post but I hope it helps people with the same problem !
Disclosure : I’m a developer of funfun
For Mapping Composite primary key using Entity framework we can use two approaches.
1) By Overriding the OnModelCreating() Method
For ex: I have the model class named VehicleFeature as shown below.
public class VehicleFeature
{
public int VehicleId { get; set; }
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
The Code in my DBContext would be like ,
public class VegaDbContext : DbContext
{
public DbSet<Make> Makes{get;set;}
public DbSet<Feature> Features{get;set;}
public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)
{
}
// we override the OnModelCreating method here.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
}
}
2) By Data Annotations.
public class VehicleFeature
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int VehicleId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
Please refer the below links for the more information.
1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
Open angular.json file and find budgets
keyword.
It should look like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
As you’ve probably guessed you can increase the maximumWarning
value to prevent this warning, i.e.:
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
}
]
A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.
In our case budget is the limit for bundle sizes.
See also:
If you don't want Jquery (and can use ES6)
for (const option of document.getElementById('mySelect')) {
console.log(option);
}
Try this
SELECT
DateAppr,
TimeAppr,
TAT,
LaserLTR,
Permit,
LtrPrinter,
JobName,
JobNumber,
JobDesc,
ActQty,
(ActQty-LtrPrinted) AS L,
(ActQty-QtyInserted) AS M,
((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N
FROM
[test].[dbo].[MM]
WHERE
DateDropped = 0
AND (
(ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0)
OR
(ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
)
when you login, or start a bash shell, environment variables are loaded/configured according to .bashrc, or .bash_profile. Whatever export you are doing, it's valid only for current session. so export PATH=/Applications/SenchaSDKTools-2.0.0-beta3:$PATH
this command is getting executed each time you are opening a shell, you can override it, but again that's for the current session only. edit the .bashrc file to suite your need. If it's saying permission denied, perhaps the file is write-protected, a link to some other file (many organisations keep a master .bashrc file and gives each user a link of it to their home dir, you can copy the file instead of link and the start adding content to it)
.NET definitely has some of the same issues that Java has when it comes to intense 3D performance. Microsoft has also invested a lot more time and money in the development of the libraries when it comes to working with 3D heavy operations.
(...personally, I also think they had a leg up when it comes to the magic between DirectX and .NET)
I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.
Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.
Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.
Use log4j in your java program instead. Then you can output to multiple media, create rolling logs, etc. and include timestamps, class names and line numbers.
As theczechsensation comment above I try to search about Gradle Build Varians and I found this link: http://code.tutsplus.com/tutorials/using-gradle-build-variants--cms-25005 This is a very simple solution. This is what I did: - In build.gradle:
flavorDimensions "version"
productFlavors {
trial{
applicationId "org.de_studio.recentappswitcher.trial"
flavorDimension "version"
}
pro{
applicationId "org.de_studio.recentappswitcher.pro"
flavorDimension "version"
}
}
Then I have 2 more version of my app: pro and trial with 2 diffrent packageName which is 2 applicationId in above code so I can upload both to Google Play. I still just code in the "main" section and use the getpackageName to switch between to version. Just go to the link I gave for detail.
I'd like to provide an alternate, easier solution that is specific to FontAwesome. If you're using a different iconic font, JOPLOmacedo's answer is still perfectly fine for use.
FontAwesome now handles list styles internally with CSS classes.
Here's the official example:
<ul class="fa-ul">
<li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
<li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
<li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
<li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>
</ul>
You can use angular.bootstrap()
directly... the problem is you lose the benefits of directives.
First you need to get a reference to the HTML element in order to bootstrap it, which means your code is now coupled to your HTML.
Secondly the association between the two is not as apparent. With ngApp
you can clearly see what HTML is associated with what module and you know where to look for that information. But angular.bootstrap()
could be invoked from anywhere in your code.
If you are going to do it at all the best way would be by using a directive. Which is what I did. It's called ngModule
. Here is what your code would look like using it:
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script src="angular.ng-modules.js"></script>
<script>
var moduleA = angular.module("MyModuleA", []);
moduleA.controller("MyControllerA", function($scope) {
$scope.name = "Bob A";
});
var moduleB = angular.module("MyModuleB", []);
moduleB.controller("MyControllerB", function($scope) {
$scope.name = "Steve B";
});
</script>
</head>
<body>
<div ng-modules="MyModuleA, MyModuleB">
<h1>Module A, B</h1>
<div ng-controller="MyControllerA">
{{name}}
</div>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
<div ng-module="MyModuleB">
<h1>Just Module B</h1>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
</body>
</html>
You can get the source code for it at:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/
It's implemented in the same way as ngApp
. It simply calls angular.bootstrap()
behind the scenes.
For a list of files to be pushed, run:
git diff --stat --cached [remote/branch]
example:
git diff --stat --cached origin/master
For the code diff of the files to be pushed, run:
git diff [remote repo/branch]
To see full file paths of the files that will change, run:
git diff --numstat [remote repo/branch]
If you want to see these diffs in a GUI, you will need to configure git for that. See How do I view 'git diff' output with a visual diff program?.
You could use the basic HTML player or you can make your own custom one. Just saying. If you want you can refer to ...
https://codepen.io/search/pens?q=video+player and have a scroll through or not. It is to to you.
For iOS 8, try this:
<a href="sms:/* phone number here */&body=/* body text here */">Link</a>
Switching the ";" with a "&" worked for me.
SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).
The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).
int a = 1;
char b = (char) a;
System.out.println(b);
hola, well i went through the same problem but what i did was the following code.
int a = 1
char b = Integer.toString(a).charAt(0);
System.out.println(b);
With this you get the decimal value as a char type. I used charAt() with index 0 because the only value into that String is 'a' and as you know, the position of 'a' into that String start at 0.
Sorry if my english isn't well explained, hope it helps you.
The above answer is already satisfying the topic. Anyway, if you need all the data in memory - have a look at bcolz. Its compressing the data in memory. I have had really good experience with it. But its missing a lot of pandas features
Edit: I got compression rates at around 1/10 or orig size i think, of course depending of the kind of data. Important features missing were aggregates.
I did it like this in my Jtable its autorefreshing after 300 ms;
DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
JTable table = new JTable();
Timer t = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addColumns();
remakeData(set);
table.setModel(model);
}
});
t.start();
private void addColumns() {
model.setColumnCount(0);
model.addColumn("NAME");
model.addColumn("EMAIL");}
private void remakeData(CollectionType< Objects > name) {
model.setRowCount(0);
for (CollectionType Objects : name){
String n = Object.getName();
String e = Object.getEmail();
model.insertRow(model.getRowCount(),new Object[] { n,e });
}}
I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange
If modal are 100% height/width "mouseenter/leave" will work to easily enable/disable scrolling. This really worked out for me:
var currentScroll=0;
function lockscroll(){
$(window).scrollTop(currentScroll);
}
$("#myModal").mouseenter(function(){
currentScroll=$(window).scrollTop();
$(window).bind('scroll',lockscroll);
}).mouseleave(function(){
currentScroll=$(window).scrollTop();
$(window).unbind('scroll',lockscroll);
});
git reflog
-- this will list all last commit
e.g Head@{0} -- wrong push
Head@{1} -- correct push
git checkout Head@{1} .
-- this will reset your last modified files
git status
git commit -m "reverted to last best"
git push origin/master
No need to worry if other has pulled or not.
Done!
ArrayList
is randomly accessible, while LinkedList
is really cheap to expand and remove elements from. For most cases, ArrayList
is fine.
Unless you've created large lists and measured a bottleneck, you'll probably never need to worry about the difference.
Of course the .gitignore file is showing up on the status, because it's untracked, and git sees it as a tasty new file to eat!
Since .gitignore is an untracked file however, it is a candidate to be ignored by git when you put it in .gitignore!
So, the answer is simple: just add the line:
.gitignore # Ignore the hand that feeds!
to your .gitignore file!
And, contrary to August's response, I should say that it's not that the .gitignore file should be in your repository. It just happens that it can be, which is often convenient. And it's probably true that this is the reason .gitignore was created as an alternative to .git/info/exclude, which doesn't have the option to be tracked by the repository. At any rate, how you use your .gitignore file is totally up to you.
For reference, check out the gitignore(5) manpage on kernel.org.
The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.
select * from ttt.table_name;
or if table name in all attached databases is unique
select * from my_unique_table_name;
But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential
normally you would use sqlite-command-line in a script
The below examples might help understand:
def add_nums1(x,y):
print(x+y)
def add_nums2(x,y):
return x+y
#----Function output is usable for further processing
add_nums2(10,20)/2
15.0
#----Function output can't be used further (gives TypeError)
add_nums1(10,20)/2
30
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-124-e11302d7195e> in <module>
----> 1 add_nums1(10,20)/2
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'
If you're not in an activity you can use the static from()
method from the LayoutInflater
class to get a LayoutInflater
, or request the service from the context method getSystemService()
too :
LayoutInflater i;
Context x; //Assuming here that x is a valid context, not null
i = (LayoutInflater) x.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//OR
i = LayoutInflater.from(x);
(I know it's almost 4 years ago but still worth mentioning)
This should work if you need to check keyboard status:
fun Activity.isKeyboardOpened(): Boolean {
val r = Rect()
val activityRoot = getActivityRoot()
val visibleThreshold = dip(UiUtils.KEYBOARD_VISIBLE_THRESHOLD_DP)
activityRoot.getWindowVisibleDisplayFrame(r)
val heightDiff = activityRoot.rootView.height - r.height()
return heightDiff > visibleThreshold;
}
fun Activity.getActivityRoot(): View {
return (findViewById<ViewGroup>(android.R.id.content)).getChildAt(0);
}
Where UiUtils.KEYBOARD_VISIBLE_THRESHOLD_DP
= 100 and dip() is an anko func that convert dpToPx:
fun dip(value: Int): Int {
return (value * Resources.getSystem().displayMetrics.density).toInt()
}
Some additional things that I can think of.
As @allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.
Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html
Best Solution
The only difference is
1.Mutex -> lock and unlock are under the ownership of a thread that locks the mutex.
2.Semaphore -> No ownership i.e; if one thread calls semwait(s) any other thread can call sempost(s) to remove the lock.
The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.
What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!
I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.
So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;
// create and initialize an object
public static JSONObject buildObject( final SimpleEntry... entries ) {
JSONObject object = new JSONObject();
for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
return object;
}
// nest a list of objects inside another
public static void putObjects( final JSONObject parentObject, final String key,
final JSONObject... objects ) {
List objectList = new ArrayList<JSONObject>();
for( JSONObject o : objects ) objectList.add( o );
parentObject.put( key, objectList );
}
Implementation example:
JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
buildObject(
new SimpleEntry( "child1Key1", "someValue" )
, new SimpleEntry( "child1Key2", "someValue" )
)
, buildObject(
new SimpleEntry( "child2Key1", "someValue" )
, new SimpleEntry( "child2Key2", "someValue" )
)
);
void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
{
TextBox txt = (TextBox)sender;
var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
string str = txt.Text + e.Text.ToString();
int cntPrc = 0;
if (str.Contains('.'))
{
string[] tokens = str.Split('.');
if (tokens.Count() > 0)
{
string result = tokens[1];
char[] prc = result.ToCharArray();
cntPrc = prc.Count();
}
}
if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
This is almost certainly going to be true given that SSL requires an extra step of encryption that simply isn't required by non-SLL HTTP.
If you want a hashCode() function like Java's in JavaScript, that is yours:
String.prototype.hashCode = function(){
var hash = 0;
for (var i = 0; i < this.length; i++) {
var character = this.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
That is the way of implementation in Java (bitwise operator).
Please note that hashCode could be positive and negative, and that's normal, see HashCode giving negative values. So, you could consider to use Math.abs()
along with this function.
Try this: parent.$.fancybox.close();
A quick, non-elegant but working standalone solution with inline CSS and no jQuery requirements. AFAIK it works from IE9 too.
<body style="overflow:hidden; margin:0">
<form id="form1" runat="server">
<div id="main" style="background-color:red">
<div id="content">
</div>
<div id="footer">
</div>
</div>
</form>
<script language="javascript">
function autoResizeDiv()
{
document.getElementById('main').style.height = window.innerHeight +'px';
}
window.onresize = autoResizeDiv;
autoResizeDiv();
</script>
</body>
Dupx
Dupx is a simple *nix utility to redirect standard output/input/error of an already running process.
Motivation
I've often found myself in a situation where a process I started on a remote system via SSH takes much longer than I had anticipated. I need to break the SSH connection, but if I do so, the process will die if it tries to write something on stdout/error of a broken pipe. I wish I could suspend the process with ^Z and then do a
bg %1 >/tmp/stdout 2>/tmp/stderr
Unfortunately this will not work (in shells I know).
With Django Class-based views you can write:
from django.views import View
from django.http import JsonResponse
class JsonView(View):
def get(self, request):
return JsonResponse({'some': 'data'})
and with Django-Rest-Framework you can write:
from rest_framework.views import APIView
from rest_framework.response import Response
class JsonView(APIView):
def get(self, request):
return Response({'some': 'data'})
"dynamic" can also be used for this purpose.
var anonymousType = new { Id = 1, Name = "A" };
var anonymousTypes = new[] { new { Id = 1, Name = "A" }, new { Id = 2, Name = "B" };
private void DisplayAnonymousType(dynamic anonymousType)
{
}
private void DisplayAnonymousTypes(IEnumerable<dynamic> anonymousTypes)
{
foreach (var info in anonymousTypes)
{
}
}
You have to add the size of the legend box to the ylim range
#Plot an empty graph and legend to get the size of the legend
x <-1:10
y <-11:20
plot(x,y,type="n", xaxt="n", yaxt="n")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"),plot = FALSE)
#custom ylim. Add the height of legend to upper bound of the range
my.range <- range(y)
my.range[2] <- 1.04*(my.range[2]+my.legend.size$rect$h)
#draw the plot with custom ylim
plot(x,y,ylim=my.range, type="l")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"))
Use discard
from purrr (works with lists and vectors).
discard(v, is.na)
The benefit is that it is easy to use pipes; alternatively use the built-in subsetting function [
:
v %>% discard(is.na)
v %>% `[`(!is.na(.))
Note that na.omit
does not work on lists:
> x <- list(a=1, b=2, c=NA)
> na.omit(x)
$a
[1] 1
$b
[1] 2
$c
[1] NA
You can write directly to an event log. Check the following links:
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx
And here's the sample from MSDN:
using System;
using System.Diagnostics;
using System.Threading;
class MySample{
public static void Main(){
// Create the source, if it does not already exist.
if(!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created. Exit the application to allow it to be registered.
return;
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";
// Write an informational entry to the event log.
myLog.WriteEntry("Writing to event log.");
}
}
You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.
According to the page:
This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.
Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
DateTime.strptime allows you to specify the format and convert a String to a DateTime.
Cross browser testing java scripts
public class MultipleBrowser {
public WebDriver driver= null;
String browser="mozilla";
String url="https://www.omnicard.com";
@BeforeMethod
public void LaunchBrowser() {
if(browser.equalsIgnoreCase("mozilla"))
driver= new FirefoxDriver();
else if(browser.equalsIgnoreCase("safari"))
driver= new SafariDriver();
else if(browser.equalsIgnoreCase("chrome"))
//System.setProperty("webdriver.chrome.driver","/Users/mhossain/Desktop/chromedriver");
driver= new ChromeDriver();
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.navigate().to(url);
}
}
but when you want to run firefox you need to chrome path disable, otherwise browser will launch but application may not.(try both way) .
Hope this is your structure:
<ul>
<li>
<div ><img.. /><p>text</p></div>
</li>
<li>
<div ><img.. /><p>text</p></div>
</li>
<li>
<div ><img.. /><p>text</p></div>
</li>
</ul>
By default, it will be add one after another row:
-----
-----
-----
if you want to make it vertical, just add float left to li, give width and height, make sure that content will not break the width:
| | |
| | |
li
{
display:block;
float:left;
width:300px; /* adjust */
height:150px; /* adjust */
padding: 5px; /*adjust*/
}
This is a limit of the C++ compiler. If you put the function in the header, all the cpp files where it can be inlined can see the "source" of your function and the inlining can be done by the compiler. Otherwhise the inlining would have to be done by the linker (each cpp file is compiled in an obj file separately). The problem is that it would be much more difficult to do it in the linker. A similar problem exists with "template" classes/functions. They need to be instantiated by the compiler, because the linker would have problem instantiating (creating a specialized version of) them. Some newer compiler/linker can do a "two pass" compilation/linking where the compiler does a first pass, then the linker does its work and call the compiler to resolve unresolved things (inline/templates...)
If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:
df3 = df3.query('~index.duplicated()')
This enables chaining statements like this:
df3.assign(C=2).query('~index.duplicated()').mean()
Create an element which shows the left part of the bar (the round part), also create an element for the right part. For the actual progress bar, create a third element with a repeating background and a width which depends on the actual progress. Put it all on top of the background image (containing the empty progress bar).
But I suppose you already knew that...
Edit: When creating a progress bar which do not use textual backgrounds. You can use the border-radius
to get the round effect, as shown by Rikudo Sennin and RoToRa!
Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:
Make sure you study this thread, as overriding a signed tag is not as easy:
git tag
man page seriously advised against a simple git tag -f B
to replace a tag name "A
"don't try to recreate a signed tag with git tag -f
(see the thread extract below)
(it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):
Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:
- in the tag object itself as a contents of 'tag' header (you can see it in output of "
git show <tag>
" and also in output of "git cat-file -p <tag>
", where<tag>
is heavyweight tag, e.g.v1.6.3
ingit.git
repository),- and also is default name of tag reference (reference in "
refs/tags/*
" namespace) pointing to a tag object.
Note that the tag reference (appropriate reference in the "refs/tags/*
" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3
', other can have in 'refs/tags/sub/v0.1.3
' for example.So when you create signed tag '
A
', you have the following situation (assuming that it points at some commit)
35805ce <--- 5b7b4ead <=== refs/tags/A
(commit) tag A
(tag)
Please also note that "
git tag -f A A
" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.If you do "
git tag -f -s A A
": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of-s
/-a
/-m
options is used to force annotated tag (creation of tag object), you will get the following situation
35805ce <--- 5b7b4ea <--- ada8ddc <=== refs/tags/A
(commit) tag A tag A
(tag) (tag)
Note also that "
git show A
" would show the whole chain down to the non-tag object...
Trying using :
imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_CENTER);
This will fit your imageview to the screen with the correct ratio.
I know this question has been answered. But my requirement was slightly different. Instead of value I wanted to filter by text. So i modified the answer by @William Herry like this.
var array = ['Administration', 'Finance', 'HR', 'IT', 'Marketing', 'Materials', 'Reception', 'Support'];
if (somecondition) {
$(array).each(function () {
$("div#deprtmnts option:contains(" + this + ")").unwrap();
});
}
else{
$(array).each(function () {
$("div#deprtmnts option:contains(" + this + ")").wrap('<span/>');
});
}
This way you can use value also by replacing contains like this
$("div#ovrcateg option[value=" + this + "]").wrap('<span/>');
You can find the last column of table and then fill the cell by looping throught it.
Sub test()
Dim lastCol As Long, i As Integer
lastCol = Range("AZ1").End(xlToLeft).Column
For i = 1 To lastCol
Cells(1, i).Value = "PHEV"
Next
End Sub
Thank you to all the commenters on this page. When I first installed the latest TortoiseSVN I got this error.
I was using the latest version, so decided to downgrade to 1.5.9 (as the rest of my colleagues were using) and this got it to work. Then, once built, my machine was moved onto another subnet and the problem started again.
I went to TortoiseSVN->Settings->Saved Data and cleared the Authentication data. After this it worked fine.
Firstly, I would try a non-secure websocket connection. So remove one of the s
's from the connection address:
conn = new WebSocket('ws://localhost:8080');
If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080
both in TCP_IN
and TCP_OUT
.
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block. A very basic Example:
try {
// some instructions
} catch(ATypeException e) {
} catch(BTypeException e) {
} catch(CTypeException e) {
}
But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.
try {
// some instructions
} catch(ATypeException|BTypeException|CTypeException ex) {
throw e;
}
So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code. I found this article which explains this feature very well along with its implementation. Improved and Better Exception Handling from Java 7 This may help you too.
You could target all text boxes with input[type=text]
and then explicitly define the class for the textboxes who need it.
You can code like below :
input[type=text] {_x000D_
padding: 0;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
left: 0;_x000D_
outline: none;_x000D_
border: 1px solid #cdcdcd;_x000D_
border-color: rgba(0, 0, 0, .15);_x000D_
background-color: white;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
width: 526px;_x000D_
margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
Spinner returns you the integer value for the array. You have to retrieve the string value based of the index.
Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
Implementation Patterns by Kent Beck.
alt text http://ecx.images-amazon.com/images/I/51JHn-6oNwL._SL500_AA240_.jpg
You can learn how to communicate people with programming.
\df <schema>.*
in psql
gives the necessary information.
To see the query that's used internally connect to a database with psql
and supply an extra "-E
" (or "--echo-hidden
") option and then execute the above command.
You would usually do something like this:
while ( resultSet.next() ) {
// Read the next item
resultSet.getString("columnName");
}
If you want to report an empty set, add a variable counting the items read. If you only need to read a single item, then your code is adequate.
Consider just downloading the file with permanent link and gdown
preinstalled like here
Use the built-in time
keyword:
$ help time time: time [-p] PIPELINE Execute PIPELINE and print a summary of the real time, user CPU time, and system CPU time spent executing PIPELINE when it terminates. The return status is the return status of PIPELINE. The `-p' option prints the timing summary in a slightly different format. This uses the value of the TIMEFORMAT variable as the output format.
Example:
$ time sleep 2
real 0m2.009s user 0m0.000s sys 0m0.004s
I don't know what you mean by "data dont get lost". Here's how you pass a normal 2D array to a function:
void myfunc(int arr[M][N]) { // M is optional, but N is required
..
}
int main() {
int somearr[M][N];
...
myfunc(somearr);
...
}
I found the docs for the get api
to be helpful - especially the two sections, Source filtering and Fields: https://www.elastic.co/guide/en/elasticsearch/reference/7.3/docs-get.html#get-source-filtering
They state about source filtering:
If you only need one or two fields from the complete _source, you can use the _source_include & _source_exclude parameters to include or filter out that parts you need. This can be especially helpful with large documents where partial retrieval can save on network overhead
Which fitted my use case perfectly. I ended up simply filtering the source like so (using the shorthand):
{
"_source": ["field_x", ..., "field_y"],
"query": {
...
}
}
FYI, they state in the docs about the fields parameter:
The get operation allows specifying a set of stored fields that will be returned by passing the fields parameter.
It seems to cater for fields that have been specifically stored, where it places each field in an array. If the specified fields haven't been stored it will fetch each one from the _source, which could result in 'slower' retrievals. I also had trouble trying to get it to return fields of type object.
So in summary, you have two options, either though source filtering or [stored] fields.
A Third Answer
Sorry, maybe I have it correct this time...
var savedBox1, savedBox2, state1=0, state2=0;
jQuery(document).ready(function() {
jQuery(".rec1").click(function() {
if (state1==0){
savedBox1 = jQuery('#rec-box').html();
jQuery('#rec-box').html(jQuery(this).next().html());
state1 = 1;
}else{
jQuery('#rec-box').html(savedBox1);
state1 = 0;
}
});
jQuery(".rec2").click(function() {
if (state1==0){
savedBox2 = jQuery('#rec-box2').html();
jQuery('#rec-box2').html(jQuery(this).next().html());
state2 = 1;
}else{
jQuery('#rec-box2').html(savedBox2);
state2 = 0;
}
});
});
This is a very generic question and there is a lot of ways it can be answered.
If you want to use JUnit to create the tests, you need to create your testcase class, then create individual test methods that test specific functionality of your class/module under tests (single testcase classes are usually associated with a single "production" class that is being tested) and inside these methods execute various operations and compare the results with what would be correct. It is especially important to try and cover as many corner cases as possible.
In your specific example, you could for example test the following:
To verify the results, you can use various assertXXX methods from the org.junit.Assert class (for convenience, you can do 'import static org.junit.Assert.*'). These methods test a particular condition and fail the test if it does not validate (with a specific message, optionally).
Example testcase class in your case (without the methods contents defined):
import static org.junit.Assert.*;
public class AdditionTests {
@Test
public void testSimpleAddition() { ... }
@Test
public void testPositiveNegativeAddition() { ... }
@Test
public void testNegativePositiveAddition() { ... }
@Test
public void testNegativeAddition() { ... }
@Test
public void testOverflow() { ... }
}
If you are not used to writing unit tests but instead test your code by writing ad-hoc tests that you then validate "visually" (for example, you write a simple main method that accepts arguments entered using the keyboard and then prints out the results - and then you keep entering values and validating yourself if the results are correct), then you can start by writing such tests in the format above and validating the results with the correct assertXXX method instead of doing it manually. This way, you can re-run the test much easier then if you had to do manual tests.
For retrieving the screen resolution, you're going to want to use the System.Windows.Forms.Screen
class. The Screen.AllScreens
property can be used to access a collection of all of the displays on the system, or you can use the Screen.PrimaryScreen
property to access the primary display.
The Screen
class has a property called Bounds
, which you can use to determine the resolution of the current instance of the class. For example, to determine the resolution of the current screen:
Rectangle resolution = Screen.PrimaryScreen.Bounds;
For changing the resolution, things get a little more complicated. This article (or this one) provides a detailed implementation and explanation. Hope this helps.
After discussion posting updated answer:
Option Explicit
Sub test()
Dim wk As String, yr As String
Dim fname As String, fpath As String
Dim owb As Workbook
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
End With
wk = ComboBox1.Value
yr = ComboBox2.Value
fname = yr & "W" & wk
fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"
On Error GoTo ErrorHandler
Set owb = Application.Workbooks.Open(fpath & "\" & fname)
'Do Some Stuff
With owb
.SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
.Close
End With
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
End With
Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
Else: Call Clear
End Sub
Error Handling:
You could try something like this to catch a specific error:
On Error Resume Next
Set owb = Application.Workbooks.Open(fpath & "\" & fname)
If Err.Number = 1004 Then
GoTo FileNotFound
Else
End If
...
Exit Sub
FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
Else: Call Clear
Using the regex provided by @JustinLevene did not have the proper escape sequences on the back-slashes. Updated to now be correct, and added in condition to match the FTP protocol as well: Will match to all urls with or without protocols, and with out without "www."
Code: ^((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?
Example: https://regex101.com/r/uQ9aL4/65
Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.
#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__
#include <sys/socket.h> /* socket, connect */
#include <netdb.h> /* struct hostent, gethostbyname */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#else
#endif
void error(const char *msg) { perror(msg); exit(0); }
int main(int argc,char *argv[])
{
int i;
struct hostent *server;
struct sockaddr_in serv_addr;
int bytes, sent, received, total, message_size;
char *message, response[4096];
int portno = atoi(argv[2])>0?atoi(argv[2]):80;
char *host = strlen(argv[1])>0?argv[1]:"localhost";
char *path = strlen(argv[4])>0?argv[4]:"/";
if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
/* How big is the message? */
message_size=0;
if(!strcmp(argv[3],"GET"))
{
printf("Process 1\n");
message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n"); /* method */
message_size+=strlen(argv[3]); /* path */
message_size+=strlen(path); /* headers */
if(argc>5)
message_size+=strlen(argv[5]); /* query string */
for(i=6;i<argc;i++) /* headers */
message_size+=strlen(argv[i])+strlen("\r\n");
message_size+=strlen("\r\n"); /* blank line */
}
else
{
printf("Process 2\n");
message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
message_size+=strlen(argv[3]); /* method */
message_size+=strlen(path); /* path */
for(i=6;i<argc;i++) /* headers */
message_size+=strlen(argv[i])+strlen("\r\n");
if(argc>5)
message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
message_size+=strlen("\r\n"); /* blank line */
if(argc>5)
message_size+=strlen(argv[5]); /* body */
}
printf("Allocating...\n");
/* allocate space for the message */
message=malloc(message_size);
/* fill in the parameters */
if(!strcmp(argv[3],"GET"))
{
if(argc>5)
sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
strlen(argv[3])>0?argv[3]:"GET", /* method */
path, /* path */
strlen(argv[5])>0?"?":"", /* ? */
strlen(argv[5])>0?argv[5]:"",host); /* query string */
else
sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
strlen(argv[3])>0?argv[3]:"GET", /* method */
path,host); /* path */
for(i=6;i<argc;i++) /* headers */
{strcat(message,argv[i]);strcat(message,"\r\n");}
strcat(message,"\r\n"); /* blank line */
}
else
{
sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
strlen(argv[3])>0?argv[3]:"POST", /* method */
path,host); /* path */
for(i=6;i<argc;i++) /* headers */
{strcat(message,argv[i]);strcat(message,"\r\n");}
if(argc>5)
sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
strcat(message,"\r\n"); /* blank line */
if(argc>5)
strcat(message,argv[5]); /* body */
}
printf("Processed\n");
/* What are we going to send? */
printf("Request:\n%s\n",message);
/* lookup the ip address */
total = strlen(message);
/* create the socket */
#ifdef _WIN32
WSADATA wsa;
SOCKET s;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
printf("connect failed with error code : %d" , WSAGetLastError());
return 1;
}
puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
printf("Send failed with error code : %d" , WSAGetLastError());
return 1;
}
puts("Data Send\n");
//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
printf("recv failed with error code : %d" , WSAGetLastError());
}
puts("Reply received\n");
//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);
closesocket(s);
WSACleanup();
#endif
#ifdef __linux__
int sockfd;
server = gethostbyname(host);
if (server == NULL) error("ERROR, no such host");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
/* fill in the structure */
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
/* connect the socket */
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
/* send the request */
sent = 0;
do {
bytes = write(sockfd,message+sent,total-sent);
if (bytes < 0)
error("ERROR writing message to socket");
if (bytes == 0)
break;
sent+=bytes;
} while (sent < total);
/* receive the response */
memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
printf("Response: \n");
do {
printf("%s", response);
memset(response, 0, sizeof(response));
bytes = recv(sockfd, response, 1024, 0);
if (bytes < 0)
printf("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (1);
if (received == total)
error("ERROR storing complete response from socket");
/* close the socket */
close(sockfd);
#endif
free(message);
return 0;
}
Playing with the code, you can put an HorizontalScrollView into an ScrollView. Thereby, you can have the two scroll method in the same view.
Source : http://androiddevblog.blogspot.com/2009/12/creating-two-dimensions-scroll-view.html
I hope this could help you.
The accepted answer seems acceptable, except that CodeAnalysis/FxCop will complain about the fact that it's catching a general exception type.
Also, it seems the "is" operator might degrade performance slightly.
CA1800: Do not cast unnecessarily says to "consider testing the result of the 'as' operator instead", but if you do that, you'll be writing more code than if you catch each exception separately.
Anyhow, here's what I would do:
bool exThrown = false;
try
{
// Something
}
catch (FormatException) {
exThrown = true;
}
catch (OverflowException) {
exThrown = true;
}
if (exThrown)
{
// Something else
}
UserController.php
use View;
public function create()
{
return View::make('user.manage', compact('user'));
}
public function edit($id)
{
$user = User::find($id);
return View::make('user.manage', compact('user'));
}
user.blade.php
@if(isset($user))
{{ Form::model($user, ['route' => ['user.update', $user->id], 'method' => 'PUT']) }}
@else
{{ Form::open(['route' => 'user.store', 'method' => 'POST']) }}
@endif
// fields
{{ Form::close() }}
A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.
Here's some code to illustrate. A point is time is captured in three different ways.
var moment = require( 'moment' );
var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );
//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );
//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate = ' + utcDate );
//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );
Which outputs this:
localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570
In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).
As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!
Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.
Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate )
, and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log
calls in the example.
As explained above, using new Array(size)
is somewhat dangerous. Instead of using it directly, place it inside an "array creator function". You can easily make sure that this function is bug-free and you avoid the danger of calling new Array(size)
directly. Also, you can give it an optional default initial value. This createArray
function does exactly that:
function createArray(size, defaultVal) {
const arr = new Array(size);
if (defaultVal !== undefined) {
// optional default value
for (let i = 0; i < size; ++i) {
arr[i] = defaultVal;
}
}
return arr;
}
Static member variables must be declared in the class and then defined outside of it!
There's no workaround, just put their actual definition in a source file.
From your description it smells like you're not using static variables the right way. If they never change you should use constant variable instead, but your description is too generic to say something more.
Static member variables always hold the same value for any instance of your class: if you change a static variable of one object, it will change also for all the other objects (and in fact you can also access them without an instance of the class - ie: an object).
The best approach to use yum and update your devtoolset is to utilize the CentOS SCLo RH Testing repository.
yum install centos-release-scl-rh
yum --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc devtoolset-7-gcc-c++
Many additional packages are also available, to see them all
yum --enablerepo=centos-sclo-rh-testing list devtoolset-7*
You can use this method to install any dev tool version, just swap the 7 for your desired version. devtoolset-6-gcc, devtoolset-5-gcc etc.
Take the pyc file to a windows machine. Use any Hex editor to open this pyc file. I used freeware 'HexEdit'. Now read hex value of first two bytes. In my case, these were 03 f3.
Open calc and convert its display mode to Programmer (Scientific in XP) to see Hex and Decimal conversion. Select "Hex" from Radio button. Enter values as second byte first and then the first byte i.e f303 Now click on "Dec" (Decimal) radio button. The value displayed is one which is correspond to the magic number aka version of python.
So, considering the table provided in earlier reply
This was asked some time ago now, but based on the answer that @nacho_zona3 provided, and previous experience with fragments, the issue is that the views have not been created by the time you are trying to find them with the findViewById()
method in onCreate()
to fix this, move the following code:
// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// this is data fro recycler view
ItemData itemsData[] = { new ItemData("Indigo",R.drawable.circle),
new ItemData("Red",R.drawable.color_ic_launcher),
new ItemData("Blue",R.drawable.indigo),
new ItemData("Green",R.drawable.circle),
new ItemData("Amber",R.drawable.color_ic_launcher),
new ItemData("Deep Orange",R.drawable.indigo)};
// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator());
to your fragment's onCreateView()
call. A small amount of refactoring is required because all variables and methods called from this method have to be static. The final code should look like:
public class ColorsFragment extends Fragment {
public ColorsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.list);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// this is data fro recycler view
ItemData itemsData[] = {
new ItemData("Indigo", R.drawable.circle),
new ItemData("Red", R.drawable.color_ic_launcher),
new ItemData("Blue", R.drawable.indigo),
new ItemData("Green", R.drawable.circle),
new ItemData("Amber", R.drawable.color_ic_launcher),
new ItemData("Deep Orange", R.drawable.indigo)
};
// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
}
So the main thing here is that anywhere you call findViewById()
you will need to use rootView.findViewById()
Corrupt Permissions: Regaining access to a folder and its sub-objects
Although most of the answers posted in reply to the question have some merit, IMHO none of them give a complete solution. The following (might be) a perfect solution for Windows 7 if you are locked-out of a folder by corrupted permission settings:
icacls "c:\folder" /remove:d /grant:r Everyone:(OI)(CI)F /T
For Windows 10 the user/SID must be specified after the /remove:d
option:
icacls "c:\folder" /remove:d Everyone /grant:r Everyone:(OI)(CI)F /T
.
Notes:
The command is applied to the specified directory.
Specifying the user "Everyone" sets the widest possible permission, as it includes every possible user.
The option "/remove:d" deletes any explicit DENY settings that may exist, as those override explicit ALLOW settings: a necessary preliminary to creating a new ALLOW setting. This is only a precaution, as there is often no DENY setting present, but better safe than sorry.
The option "/grant" creates a new ALLOW setting, an explicit permission that replaces (":r") any and all explicit ALLOW settings that may exist.
The "F" parameter (i.e. the permission created) makes this a grant of FULL control.
The "/T" parameter adds recursion, applying these changes to all current sub-objects in the specified directory (i.e. files and subfolders), as well as the folder itself.
The "(OI)" and "(CI)" parameters also add recursion, applying these changes to sub-objects created subsequently.
.
ADDENDUM (2019/02/10) -
The Windows 10 command line above was kindly suggested to me today, so here it is. I haven't got Windows 10 to test it, but please try it out if you have (and then will you please post a comment below).
The change only concerns removing the DENY setting as a first step. There might well not be any DENY setting present, so that option might make no difference. My understanding is, on Windows 7, that you don't need to specify a user after /remove:d but I might be wrong about that!
.
ADDENDUM (2019/11/21) -
User astark recommends replacing Everyone with the term *S-1-1-0 in order for the command to be language independent. I only have an English install of Windows, so I can't test this proposal, but it seems reasonable.
I think you need something a bit more generic. Try this:
public static System.Boolean IsNumeric (System.Object Expression)
{
if(Expression == null || Expression is DateTime)
return false;
if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
Hope it helps!
Here is simple CSS rules that put any div in the center
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/
It's like you said; dependencyManagement
is used to pull all the dependency information into a common POM file, simplifying the references in the child POM file.
It becomes useful when you have multiple attributes that you don't want to retype in under multiple children projects.
Finally, dependencyManagement
can be used to define a standard version of an artifact to use across multiple projects.
The density plot can also be created by using matplotlib: The function plt.hist(data) returns the y and x values necessary for the density plot (see the documentation https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html). Resultingly, the following code creates a density plot by using the matplotlib library:
import matplotlib.pyplot as plt
dat=[-1,2,1,4,-5,3,6,1,2,1,2,5,6,5,6,2,2,2]
a=plt.hist(dat,density=True)
plt.close()
plt.figure()
plt.plot(a[1][1:],a[0])
This code returns the following density plot
Thanks for commenting, I understand what you mean but I didn't want to check old values. I just wanted to get a pointer to that view.
Looking at someone else's code I have just found a workaround, you can access the root of a layout using LayoutInflater
.
The code is the following, where this
is an Activity:
final LayoutInflater factory = getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.landmark_new_dialog, null);
landmarkEditNameView = (EditText) textEntryView.findViewById(R.id.landmark_name_dialog_edit);
You need to get the inflater for this
context, access the root view through the inflate method and finally call findViewById
on the root view of the layout.
Hope this is useful for someone! Bye
Remove the spaces before the autoplay=1:
src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&;enablejsapi=1"
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
Document has already explain the usage. So I am using SQL to explain these methods
Assuming there is an Order (orders)
has many OrderItem (order_items)
.
And you have already build the relationship between them.
// App\Models\Order:
public function orderItems() {
return $this->hasMany('App\Models\OrderItem', 'order_id', 'id');
}
These three methods are all based on a relationship.
Result: with()
return the model object and its related results.
Advantage: It is eager-loading which can prevent the N+1 problem.
When you are using the following Eloquent Builder:
Order::with('orderItems')->get();
Laravel change this code to only two SQL:
// get all orders:
SELECT * FROM orders;
// get the order_items based on the orders' id above
SELECT * FROM order_items WHERE order_items.order_id IN (1,2,3,4...);
And then laravel merge the results of the second SQL as different from the results of the first SQL by foreign key. At last return the collection results.
So if you selected columns without the foreign_key in closure, the relationship result will be empty:
Order::with(['orderItems' => function($query) {
// $query->sum('quantity');
$query->select('quantity'); // without `order_id`
}
])->get();
#=> result:
[{ id: 1,
code: '00001',
orderItems: [], // <== is empty
},{
id: 2,
code: '00002',
orderItems: [], // <== is empty
}...
}]
Has
will return the model's object that its relationship is not empty.
Order::has('orderItems')->get();
Laravel change this code to one SQL:
select * from `orders` where exists (
select * from `order_items` where `order`.`id` = `order_item`.`order_id`
)
whereHas
and orWhereHas
methods to put where
conditions on your has
queries. These methods allow you to add customized constraints to a relationship constraint.
Order::whereHas('orderItems', function($query) {
$query->where('status', 1);
})->get();
Laravel change this code to one SQL:
select * from `orders` where exists (
select *
from `order_items`
where `orders`.`id` = `order_items`.`order_id` and `status` = 1
)
Try this:
You can create a custom class for your panel heading. Using this css class you can style the panel heading. I have a simple Fiddle for this.
HTML:
<div class="panel panel-default">
<div class="panel-heading panel-heading-custom">
<h3 class="panel-title">Panel title</h3>
</div>
<div class="panel-body">
Panel content
</div>
</div>
CSS:
.panel-default > .panel-heading-custom {
background: #ff0000; color: #fff; }
Demo Link:
I believe that as of PHP 5.3, you can use const
outside of classes, as shown here in the second example:
http://www.php.net/manual/en/language.constants.syntax.php
<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';
echo CONSTANT;
?>
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
If you have copied the seeders files from any other project then you need to run the artisan command php artisan db:seed
otherwise it is fine.
A good way to do it in Node is to use the ajv
package (https://github.com/epoberezkin/ajv).
const Ajv = require('ajv');
const ajv = new Ajv({ allErrors: true, useDefaults: true, verbose: true });
const uuidSchema = { type: 'string', format: 'uuid' };
ajv.validate(uuidSchema, 'bogus'); // returns false
ajv.validate(uuidSchema, 'd42a8273-a4fe-4eb2-b4ee-c1fc57eb9865'); // returns true with v4 GUID
ajv.validate(uuidSchema, '892717ce-3bd8-11ea-b77f-2e728ce88125'); // returns true with a v1 GUID
You could try updating the table to get rid of these characters:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
EDIT
Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Please confirm that this code on its own (well, the first SELECT
, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
So take a random row, and then paste the output into a query like this:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0)
- since you can't really filter out the rows that contain CHAR(0)
because they could contain CHAR(0)
and CHAR(something else)
. For all we know you have values in the table like:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
...which also can't be converted to an integer, whether you've replaced CHAR(0)
or not.
I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.
How about this?
WAITFOR DELAY '00:00:02';
If you have "00:02" it's interpreting that as Hours:Minutes.
git push
or
git push server_name master
should do the trick, after you have made a commit to your local repository.
Thread.sleep() could work in most cases, but usually if you're waiting, you are actually waiting for a particular condition or state to occur. Thread.sleep() does not guarantee that whatever you're waiting for has actually happened.
If you are waiting on a rest request for example maybe it usually return in 5 seconds, but if you set your sleep for 5 seconds the day your request comes back in 10 seconds your test is going to fail.
To remedy this JayWay has a great utility called Awatility which is perfect for ensuring that a specific condition occurs before you move on.
It has a nice fluent api as well
await().until(() ->
{
return yourConditionIsMet();
});
Setup twig
$twig = new Twig_Environment(...);
$twig->addGlobal('session', $_SESSION);
Then within your template access session values for example
$_SESSION['username'] in php file Will be equivalent to {{ session.username }} in your twig template
Here's an example (source):
SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);
I want to do a for loop, yet with askewchan's method it does not work well, so I have modified it.
x = np.empty((0,3))
y = np.array([1,2,3])
for i in ...
x = np.vstack((x,y))
For normal users. Open the inspect window of current page. And type in:
l = document.getElementsByTagName("a");
for (var i =0; i<l.length; i++) {
l[i].href = "";
}
Then you shall not see the url links in print preview.
For static text:
For long text that needs to be updated once in a while:
For a number (formatted 00.0):
In your onDraw event only update the value variable sent to the shader.
precision highp float;
precision highp sampler2D;
uniform float uTime;
uniform float uValue;
uniform vec3 iResolution;
varying vec4 v_Color;
varying vec2 vTextureCoord;
uniform sampler2D s_texture;
void main() {
vec4 fragColor = vec4(1.0, 0.5, 0.2, 0.5);
vec2 uv = vTextureCoord;
float devisor = 10.75;
float digit;
float i;
float uCol;
float uRow;
if (uv.y < 0.45) {
if (uv.x > 0.75) {
digit = floor(uValue*10.0);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.5) / devisor, uRow / devisor) );
} else if (uv.x > 0.5) {
uCol = 4.0;
uRow = 1.0;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.0) / devisor, uRow / devisor) );
} else if (uv.x > 0.25) {
digit = floor(uValue);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.5) / devisor, uRow / devisor) );
} else if (uValue >= 10.0) {
digit = floor(uValue/10.0);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.0) / devisor, uRow / devisor) );
} else {
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
}
} else {
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
}
gl_FragColor = fragColor;
}
Above code works for a texture atlas where numbers start from 0 at the 7th column of the 2nd row of the font atlas (texture).
Refer to https://www.shadertoy.com/view/Xl23Dw for demonstration (with wrong texture though)
My solution accept Copy&Paste and save the position of the caret. It's used for cost of products so allows positive decimal values only. Can be refactor very easy to allow negative or just integer digits.
angular
.module("client")
.directive("onlyNumber", function () {
return {
restrict: "A",
link: function (scope, element, attr) {
element.bind('input', function () {
var position = this.selectionStart - 1;
//remove all but number and .
var fixed = this.value.replace(/[^0-9\.]/g, '');
if (fixed.charAt(0) === '.') //can't start with .
fixed = fixed.slice(1);
var pos = fixed.indexOf(".") + 1;
if (pos >= 0) //avoid more than one .
fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');
if (this.value !== fixed) {
this.value = fixed;
this.selectionStart = position;
this.selectionEnd = position;
}
});
}
};
});
Put on the html page:
<input type="text" class="form-control" only-number ng-model="vm.cost" />
$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter
If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
<?php
if ($_GET) {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
} else {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
?>
To call from command line chmod 755 /var/www/webroot/index.php
and use
/usr/bin/php /var/www/webroot/index.php arg1 arg2
To call from the browser, use
http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2
Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.
You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.
Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.
It's the directory where java
was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.
So if you cd
into /somedir
, then run your program, user.dir
will be /somedir
.
A different property, user.home
, refers to the user directory. As in /Users/myuser
or /home/myuser
or C:\Users\myuser
.
See here for a list of system properties and their descriptions.
Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line
error_log /var/log/nginx/error.log debug;
And then restart nginx:
sudo service nginx restart
That way you can detail what nginx is doing and why it is returning the status code 400.
As mentioned in the React documentation, there is no guarantee of setState
being fired synchronously, so your console.log
may return the state prior to it updating.
Michael Parker mentions passing a callback within the setState
. Another way to handle the logic after state change is via the componentDidUpdate
lifecycle method, which is the method recommended in React docs.
Generally we recommend using componentDidUpdate() for such logic instead.
This is particularly useful when there may be successive setState
s fired, and you would like to fire the same function after every state change. Rather than adding a callback to each setState
, you could place the function inside of the componentDidUpdate
, with specific logic inside if necessary.
// example
componentDidUpdate(prevProps, prevState) {
if (this.state.value > prevState.value) {
this.foo();
}
}
Keep in mind that search spiders don't index JS code. So, if you put your URL
inside JS code and make sure to also include it inside a traditional HTML link elsewhere on the page.
That is, if you want the linked pages to be indexed by Google, etc.
I would say change var sv = sel.options[sel.selectedIndex].value; to var sv = sel.options[sel.selectedIndex].text;
It worked for me. Directing you to where I found my solution Getting the selected value dropdown jstl
Objective-C
Create:
NSDictionary *dictionary = @{@"myKey1": @7, @"myKey2": @5};
Change:
NSMutableDictionary *mutableDictionary = [dictionary mutableCopy]; //Make the dictionary mutable to change/add
mutableDictionary[@"myKey3"] = @3;
The short-hand syntax is called Objective-C Literals
.
Swift
Create:
var dictionary = ["myKey1": 7, "myKey2": 5]
Change:
dictionary["myKey3"] = 3
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "
Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
I created a subroutine one using a double float, it returns 2 integer values.
void double2Ints(double f, int p, int *i, int *d)
{
// f = float, p=decimal precision, i=integer, d=decimal
int li;
int prec=1;
for(int x=p;x>0;x--)
{
prec*=10;
}; // same as power(10,p)
li = (int) f; // get integer part
*d = (int) ((f-li)*prec); // get decimal part
*i = li;
}
void test()
{
double df = 3.14159265;
int i,d;
for(int p=2;p<9;p++)
{
double2Ints(df, p, &i,&d); printf("d2i (%d) %f = %d.%d\r\n",p, df,i,d);
}
}
The problem is that they're all the same exact list in memory. When you use the [x]*n
syntax, what you get is a list of n
many x
objects, but they're all references to the same object. They're not distinct instances, rather, just n
references to the same instance.
To make a list of 3 different lists, do this:
x = [[] for i in range(3)]
This gives you 3 separate instances of []
, which is what you want
[[]]*n
is similar to
l = []
x = []
for i in range(n):
x.append(l)
While [[] for i in range(3)]
is similar to:
x = []
for i in range(n):
x.append([]) # appending a new list!
In [20]: x = [[]] * 4
In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object
In [22]: x=[[] for i in range(4)]
In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time
Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.
You can avoid this problem by
Hibernate.initialize(obj);
Fetch profiles
to select lazy/non-lazy fetching runtimeFurther I would recommend looking at the related
links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.
Great answers!
One thing that I would like to clarify deeper is nonatomic
/atomic
.
The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents.
I.e. atomic
will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute.
For example:
@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...
In this case it is guaranteed that the pointer to the dict
will be read/set in the atomic manner by different threads.
BUT the dict
itself (the dictionary dict
pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.
If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".
When you update the configuration in the php.ini file, you might have to restart apache. Try running apachectl restart
or apache2ctl restart
, or something like that.
Also, in you ini file, make sure you have display_errors = on
, but only in a development environment, never in a production machine.
Also, the strictest error reporting is exactly what you have cited, E_ALL | E_STRICT
. You can find more information on error levels at the php docs.
May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?
In order to clear all selection, I am using like this and its working fine for me. here is the script:
$("#ddlMultiselect").multiselect("clearSelection");
$("#ddlMultiselect").multiselect( 'refresh' );
Go to tools
>> nuget
>> console
and type:
Install-Package System.Configuration.ConfigurationManager
If you want a specific version:
Install-Package System.Configuration.ConfigurationManager -Version 4.5.0
Your ConfigurationManager
dll will now be imported and the code will begin to work.
Today I found, that the old ways are not working very well.
So I used: "Customize YouTube Start and End Time - Acetrot.com" from http://www.youtubestartend.com/
They provide a link into https://xxxx.app.goo.gl/yyyyyyyyyy e.g. https://v637g.app.goo.gl/Cs2SV9NEeoweNGGy9 Link contain forward to format like this https://www.youtube.com/embed/xyzabc123?start=17&end=21&version=3&autoplay=1
You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:
listy = [[] for i in range(3)]
Running your example code now gives the result you probably expected:
>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]
The way I got around this issue is by not calling intent within a dialog. **** use syntax applicable to activity or fragment accordingly
@Override
public void onClick(DialogInterface dialog, int which) {
checkvariable= true;
getActivity().finish();
}
@Override
public void onStop() {
super.onStop();
if (checkvariable) {
startActivity(intent);
}
}
More concise than others:
def parseString(string):
try:
return int(string)
except ValueError:
return string
b = [[parseString(s) for s in clause.split(', ')] for clause in a]
Alternatively if your format is fixed as <string>, <int>, <int>
, you can be even more concise:
def parseClause(a,b,c):
return [a, int(b), int(c)]
b = [parseClause(*clause) for clause in a]
I'm not entirely sure about speed, but if you are looking for simplicity I would suggest using the lodash/underscore escape function.
In 2017 you can do this (saying this because this thread is almost 9 years old!)
function copyStringToClipboard (string) {
function handler (event){
event.clipboardData.setData('text/plain', string);
event.preventDefault();
document.removeEventListener('copy', handler, true);
}
document.addEventListener('copy', handler, true);
document.execCommand('copy');
}
And now to copy copyStringToClipboard('Hello World')
If you noticed the setData
line, and wondered if you can set different data types the answer is yes.
The simplest way is:
if n==int(n):
--do something--
Where n is the variable
git clone -o <sha1-of-the-commit> <repository-url> <local-dir-name>
git
uses the word origin
in stead of popularly known revision
Following is a snippet from the manual $ git help clone
--origin <name>, -o <name>
Instead of using the remote name origin to keep track of the upstream repository, use <name>.
If Multiset
extends from the Array
class
x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]
x.union(y) # => [1, 2, 4, 7] (ONLY IN RUBY 2.6)
x.union(y, z) # => [1, 2, 4, 7, 3] (ONLY IN RUBY 2.6)
x | y # => [1, 2, 4, 7]
x.difference(y) # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z) # => [4] (ONLY IN RUBY 2.6)
x - y # => [4, 7]
x & y # => [1, 2]
For more info about the new methods in Ruby 2.6, you can check this blog post about its new features
(Should be a comment, but too long, so new reply). As others have mentioned, the Arrays.asList
method is fixed size, but that's not the only issue with it. It also doesn't handle inheritance very well. For instance, suppose you have the following:
class A{}
class B extends A{}
public List<A> getAList(){
return Arrays.asList(new B());
}
The above results in a compiler error, because List<B>
(which is what is returned by Arrays.asList) is not a subclass of List<A>
, even though you can add Objects of type B to a List<A>
object. To get around this, you need to do something like:
new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))
This is probably the best way to go about doing this, esp. if you need an unbounded list or need to use inheritance.
If you are using gradle build system, follow these steps:
put jar
files inside respective libs
folder of your android app. You will generally find it at Project
> app
> libs
. If libs
folder is missing, create one.
add this to your build.gradle
file your app
. (Not to your Project
's build.gradle
)
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
// other dependencies
}
This will include all your jar
files available in libs
folder.
If don't want to include all jar
files, then you can add it individually.
compile fileTree(dir: 'libs', include: 'file.jar')
If the assembly is part of the build of an ASP.NET application, you can use the BuildManager class:
using System.Web.Compilation
...
BuildManager.GetType(typeName, false);
Do you have to use DataTable.Select()
? I prefer to write a linq query for this kind of thing.
var dValue= from row in myDataTable.AsEnumerable()
where row.Field<int>("A") == 1
&& row.Field<int>("B") == 2
&& row.Field<int>("C") == 3
select row.Field<string>("D");
dialog-component.css
This code works perfectly for me, other solutions don't work. Use the ::ng-deep shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The ::ng-deep combinator works to any depth of nested components, and it applies to both the view children and content children of the component.
::ng-deep .mat-dialog-container {
height: 400px !important;
width: 400px !important;
}
I would recommend you google 'Read objects in folder'. You might need to create a reader and a list and let the reader read all the object names in the folder and add them to the list in n loops.
I ran into this on Python 3 and found this question (and solution). When opening a file, Python 3 supports the encoding keyword to automatically handle the encoding.
Without it, the BOM is included in the read result:
>>> f = open('file', mode='r')
>>> f.read()
'\ufefftest'
Giving the correct encoding, the BOM is omitted in the result:
>>> f = open('file', mode='r', encoding='utf-8-sig')
>>> f.read()
'test'
Just my 2 cents.
Shallow copy will not create new reference but deep copy will create the new reference.
Here is the program to explain the deep and shallow copy.
public class DeepAndShollowCopy {
int id;
String name;
List<String> testlist = new ArrayList<>();
/*
// To performing Shallow Copy
// Note: Here we are not creating any references.
public DeepAndShollowCopy(int id, String name, List<String>testlist)
{
System.out.println("Shallow Copy for Object initialization");
this.id = id;
this.name = name;
this.testlist = testlist;
}
*/
// To performing Deep Copy
// Note: Here we are creating one references( Al arraylist object ).
public DeepAndShollowCopy(int id, String name, List<String> testlist) {
System.out.println("Deep Copy for Object initialization");
this.id = id;
this.name = name;
String item;
List<String> Al = new ArrayList<>();
Iterator<String> itr = testlist.iterator();
while (itr.hasNext()) {
item = itr.next();
Al.add(item);
}
this.testlist = Al;
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Oracle");
list.add("C++");
DeepAndShollowCopy copy=new DeepAndShollowCopy(10,"Testing", list);
System.out.println(copy.toString());
}
@Override
public String toString() {
return "DeepAndShollowCopy [id=" + id + ", name=" + name + ", testlist=" + testlist + "]";
}
}
int intVar = (int)ds.Tables[0].Rows[0][n]; // n = column index
You can read files in raw/res using getResources().openRawResource(R.raw.myfilename)
.
BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt
or my_data.bin
will not be listed in R.
in your tsconfig you have to add: "esModuleInterop": true - it should help.
If we need to share multiple variables use the below format
//module.js
let name='foobar';
let city='xyz';
let company='companyName';
module.exports={
name,
city,
company
}
Usage
// main.js
require('./modules');
console.log(name); // print 'foobar'
I suspect the problem is that you've put the "-D" after the -jar
. Try this:
java -Dtest="true" -jar myApplication.jar
From the command line help:
java [-options] -jar jarfile [args...]
In other words, the way you've got it at the moment will treat -Dtest="true"
as one of the arguments to pass to main
instead of as a JVM argument.
(You should probably also drop the quotes, but it may well work anyway - it probably depends on your shell.)
First uninstall all java software like JRE 7 or JRE 6 or JDK ,then open the following path :
START > CONTROL PANEL > ADVANCED SETTING > ENVIRONMENT VARIABLE > SYSTEM VARIABLE > PATH
Then click on Edit button and paste the following text to Variable_Value and click OK.
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\
Now go to this url http://java.com/en/download/manual.jsp and click on Windows Offline and click on run and start again eclipse.
Enjoy it!
Add /Q
for quiet mode and it should remove the prompt.
You may find out you want to use the same config for more domains.
Following snippet removes www before any domain:
if ($host ~* ^www\.(.*)$) {
rewrite / $scheme://$1 permanent;
}
(out of date) Spreadsheet of device metrics.
SEE ALSO:
Device Metrics - Material Design.
Screen Sizes.
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Galaxy Y 320 x 240 ldpi 0.75 120 427 x 320 4:3 1.3333 427 x 320
? 400 x 240 ldpi 0.75 120 533 x 320 5:3 1.6667 533 x 320
? 432 x 240 ldpi 0.75 120 576 x 320 9:5 1.8000 576 x 320
Galaxy Ace 480 x 320 mdpi 1 160 480 x 320 3:2 1.5000 480 x 320
Nexus S 800 x 480 hdpi 1.5 240 533 x 320 5:3 1.6667 533 x 320
"Galaxy SIII Mini" 800 x 480 hdpi 1.5 240 533 x 320 5:3 1.6667 533 x 320
? 854 x 480 hdpi 1.5 240 569 x 320 427:240 1.7792 569 x 320
Galaxy SIII 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Galaxy Nexus 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
HTC One X 4.7" 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Nexus 5 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 YES 592 x 360
Galaxy S4 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
HTC One 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
Galaxy Note III 5.7" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
HTC One Max 5.9" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
Galaxy Note II 5.6" 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Nexus 4 4.4" 1200 x 768 xhdpi 2 320 600 x 384 25:16 1.5625 YES 552 x 384
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
? 800 x 480 mdpi 1 160 800 x 480 5:3 1.6667 800 x 480
? 854 x 480 mdpi 1 160 854 x 480 427:240 1.7792 854 x 480
Galaxy Mega 6.3" 1280 x 720 hdpi 1.5 240 853 x 480 16:9 1.7778 853 x 480
Kindle Fire HD 7" 1280 x 800 hdpi 1.5 240 853 x 533 8:5 1.6000 853 x 533
Galaxy Mega 5.8" 960 x 540 tvdpi 1.33333 213.333 720 x 405 16:9 1.7778 720 x 405
Sony Xperia Z Ultra 6.4" 1920 x 1080 xhdpi 2 320 960 x 540 16:9 1.7778 960 x 540
Blackberry Priv 5.43" 2560 x 1440 ? 540 ? 16:9 1.7778
Blackberry Passport 4.5" 1440 x 1440 ? 453 ? 1:1 1.0
Kindle Fire (1st & 2nd gen) 7" 1024 x 600 mdpi 1 160 1024 x 600 128:75 1.7067 1024 x 600
Tesco Hudl 7" 1400 x 900 hdpi 1.5 240 933 x 600 14:9 1.5556 933 x 600
Nexus 7 (1st gen/2012) 7" 1280 x 800 tvdpi 1.33333 213.333 960 x 600 8:5 1.6000 YES 912 x 600
Nexus 7 (2nd gen/2013) 7" 1824 x 1200 xhdpi 2 320 912 x 600 38:25 1.5200 YES 864 x 600
Kindle Fire HDX 7" 1920 x 1200 xhdpi 2 320 960 x 600 8:5 1.6000 960 x 600
? 800 x 480 ldpi 0.75 120 1067 x 640 5:3 1.6667 1067 x 640
? 854 x 480 ldpi 0.75 120 1139 x 640 427:240 1.7792 1139 x 640
Kindle Fire HD 8.9" 1920 x 1200 hdpi 1.5 240 1280 x 800 8:5 1.6000 1280 x 800
Kindle Fire HDX 8.9" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Tab 2 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Tab 3 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
ASUS Transformer 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
ASUS Transformer 2 10" 1920 x 1200 hdpi 1.5 240 1280 x 800 8:5 1.6000 1280 x 800
Nexus 10 10" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Note 10.1 10" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Coping with different aspect ratios
The different aspect ratios seen above are (from most square; h/w):
1:1 1.0 <- rare for phone; common for watch
4:3 1.3333 <- matches iPad (when portrait)
3:2 1.5000
38:25 1.5200
14:9 1.5556 <- rare
25:16 1.5625
8:5 1.6000 <- aka 16:10
5:3 1.6667
128:75 1.7067
16:9 1.7778 <- matches iPhone 5-7
427:240 1.7792 <- rare
37:18 2.0555 <- Galaxy S8
If you skip the extreme aspect ratios, that are rarely seen at phone size or larger, all the other devices fit a range from 1.3333 to 1.7778, which conveniently matches the current iPhone/iPad ratios (considering all devices in portrait mode). Note that there are quite a few variations within that range, so if you are creating a small number of fixed aspect-ratio layouts, you will need to decide how to handle the odd "in-between" screens.
Minimum "portrait mode" solution is to support 1.3333, which results in unused space at top and bottom, on all the resolutions with larger aspect ratio.
Most likely, you would instead design it to stretch over the 1.333 to 1.778 range. But sometimes part of your design looks too distorted then.
Advanced layout ideas:
For text, you can design for 1.3333, then increase line spacing for 1.666 - though that will look quite sparse. For graphics, design for an intermediate ratio, so that on some screens it is slightly squashed, on others it is slightly stretched. geometric mean of Sqrt(1333 x 1667) ~= 1491. So you design for 1491 x 1000, which will be stretched/squashed by +-12% when assigned to the extreme cases.
Next refinement is to design layout as a stack of different-height "bands" that each fill the width of the screen. Then determine where you can most pleasingly "stretch-or-squash" a band's height, to adjust for different ratios.
For example, consider imaginary phones with 1333 x 1000 pixels and 1666 x 1000 pixels. Suppose you have two "bands", and your main "band" is square, so it is 1000 x 1000. Second band is 333 x 1000 on one screen, 666 x 1000 on the other - quite a range to design for.
You might decide your main band looks okay altered 10% up-or-down, and squash it 900 x 1000 on the 1333 x 1000 screen, leaving 433 x 1000. Then stretch it to 1100 x 1000 on 1666 x 1000 screen, leaving 566 x 1000. So your second band now needs to adjust over only 433 to 566, which has geometric mean of Sqrt(433 x 566) ~= 495. So you design for 495 x 1000, which will be stretched/squashed by +-14% when assigned to the extreme cases.
git log -1 --format="%an %ae%n%cn %ce" a2c25061
The Pretty Formats section of the git show
documentation contains
format:<string>
The
format:<string>
format allows you to specify which information you want to show. It works a little bit like printf format, with the notable exception that you get a newline with%n
instead of\n
…The placeholders are:
%an
: author name%ae
: author email%cn
: committer name%ce
: committer email
To make auto-install (but mannually confirm), You can make gist (gist.github.com) with <filename>.user.js
filename to get on-click installation when you click on Raw and get this page:
My problem was that I called https
endpoint with http
.