If you want XCode on another OS, I suggest cloud computing. That way your app is being developed on a Mac and can be submitted to the App Store.
you can
float Lasttime;
public float Sec = 3f;
public int Num;
void Start(){
ExampleStart();
}
public void ExampleStart(){
Lasttime = Time.time;
}
void Update{
if(Time.time - Lasttime > sec){
// if(Num == step){
// Yourcode
//You Can Change Sec with => sec = YOURTIME(Float)
// Num++;
// ExampleStart();
}
if(Num == 0){
TextUI.text = "Welcome to Number Wizard!";
Num++;
ExampleStart();
}
if(Num == 1){
TextUI.text = ("The highest number you can pick is " + max);
Num++;
ExampleStart();
}
if(Num == 2){
TextUI.text = ("The lowest number you can pick is " + min);
Num++;
ExampleStart();
}
}
}
Khaled Developer
Easy For Gaming
The URLs are passed in the request: request.getRequestURL()
.
If you mean other sites that are linking to you? You want to capture the HTTP Referrer, which you can do by calling:
request.getHeader("referer");
Unfortunately, re.escape()
is not suited for the replacement string:
>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'
A solution is to put the replacement in a lambda:
>>> re.sub('a', lambda _: '_', 'aa')
'__'
because the return value of the lambda is treated by re.sub()
as a literal string.
Try this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
try
{
cn.Open();
SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
cmd.ExecuteNonQuery();
lblAlert.Text = "SucessFully Connected";
cn.Close();
}
catch (Exception eq)
{
lblAlert.Text = eq.ToString();
}
}
There are two ways to do the redirect. Both apply to either subprocess.Popen
or subprocess.call
.
Set the keyword argument shell = True
or executable = /path/to/the/shell
and specify the command just as you have it there.
Since you're just redirecting the output to a file, set the keyword argument
stdout = an_open_writeable_file_object
where the object points to the output
file.
subprocess.Popen
is more general than subprocess.call
.
Popen
doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen
returns a Popen
object.
call
does block. While it supports all the same arguments as the Popen
constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call
returns a code representing the process' exit status.
returncode = call(*args, **kwargs)
is basically the same as calling
returncode = Popen(*args, **kwargs).wait()
call
is just a convenience function. It's implementation in CPython is in subprocess.py:
def call(*popenargs, timeout=None, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
As you can see, it's a thin wrapper around Popen
.
Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:
param(
[Parameter(Position = 0)]
[string[]]$Hosts,
[string]$VLAN
)
foreach ($i in $Hosts)
{
Do-Stuff $i
}
Then call it like:
.\script.ps1 host1, host2, host3 -VLAN 2
Notice the comma between the values. This collects them in an array
If the data type of the field is date or timestamp, Oracle should always give the correct result if you add the correct number given in number of days (or a the correct fraction of a day in your case). So if you are trying to bump the value in 30 minutes, you should use :
select field + 0.5/24 from table;
Based on the information you provided, I believe this is what you tried to do and I am quite sure it works.
Usually this refers the the ability for an object of type A to behave like an object of type B. In object oriented programming this is usually achieve by inheritance. Some wikipedia links to read more:
EDIT: fixed broken links.
It is only required if you aren't using the default values for version
and encoding
(which you are in that example).
This will find the first parent with class box
then find the first child class with regex matching something
and get the id.
$(".mylink").closest(".box").find('[class*="something"]').first().attr("id")
Summarizing the different ways you can accomplish it:
open /Applications/Sublime\ Text.app/
open -a /Applications/Sublime\ Text.app/ myFileToOpen.txt
Make your command short by introducing a new alias named 'sublime' and use it
a. open bash_profile:
nano ~/.bash_profile
b. copy this line to create the alias and save and restart terminal
alias sublime="open -a /Applications/Sublime\ Text.app"
c. usage: apple.txt will open with sublime text (provide file path if necessary)
sublime apple.txt
SCREEN:
NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo
or printf
I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)
You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:
screen /dev/ttyS0 19200,cs8
(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.
ECHO:
Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0
) while I was sending the echo command.
PRINTF:
I found that one can also use printf's '%x' command:
c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT
Again, for printf, start cat < /dev/ttyS0
before sending the command.
Easy.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
Don't forget to add your new activity in the AndroidManifest.xml:
<activity android:label="@string/app_name" android:name="NextActivity"/>
as text:
=CONCATENATE(TEXT(cell;"d");" days ";TEXT(cell;"t");" hours ";MID(TEXT(cell;"hh:mm:ss");4;2);" minutes ";TEXT(cell;"s");" seconds")
Considering that this is the first stack overflow result when google searching this topic, it bears mentioning that prefixing u
to unicode strings is optional in Python 3. (Python 2 example was copied from the top answer)
Python 3 (both work):
print('\u0420\u043e\u0441\u0441\u0438\u044f')
print(u'\u0420\u043e\u0441\u0441\u0438\u044f')
Python 2:
print u'\u0420\u043e\u0441\u0441\u0438\u044f'
You could create your own Exception class:
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
In your code:
throw new InvalidSpeedException("TOO HIGH");
I tend to version my framework then apply the version number to script and style paths
<cfset fw.version = '001' />
<script src="/scripts/#fw.version#/foo.js"/>
Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME
in your query for only true or false column
Since nobody mentioned it yet, you can compare arrays with the std::equal
algorithm:
int iar1[] = {1,2,3,4,5};
int iar2[] = {1,2,3,4,5};
if (std::equal(std::begin(iar1), std::end(iar1), std::begin(iar2)))
cout << "Arrays are equal.";
else
cout << "Arrays are not equal.";
You need to include <algorithm>
and <iterator>
. If you don't use C++11 yet, you can write:
if (std::equal(iar1, iar1 + sizeof iar1 / sizeof *iar1, iar2))
Whether null char is allowed or not really depends on base64 codec in question. Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/
But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.
One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.
Docker container installation for php:XXX
Debian based images:
RUN apt-get update && apt-get install -y --no-install-recommends libmagickwand-dev
RUN pecl install imagick && docker-php-ext-enable imagick
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* || true
You need to put the JSP file in /index.jsp
instead of in /WEB-INF/jsp/index.jsp
. This way the whole servlet is superflous by the way.
WebContent
|-- META-INF
|-- WEB-INF
| `-- web.xml
`-- index.jsp
If you're absolutely positive that you need to invoke a servlet this strange way, then you should map it on an URL pattern of /index.jsp
instead of /index
. You only need to change it to get the request dispatcher from request
instead of from config
and get rid of the whole init()
method.
In case you actually intend to have a "home page servlet" (and thus not a welcome file — which has an entirely different purpose; namely the default file which sould be served when a folder is being requested, which is thus not specifically the root folder), then you should be mapping the servlet on the empty string URL pattern.
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
See also Difference between / and /* in servlet mapping url pattern.
A typographical error in the string describing the database driver can also produce the error.
A string specified as:
"jdbc:mysql//localhost:3307/dbname,"usrname","password"
can result in a "no suitable driver found" error. The colon following "mysql" is missing in this example.
The correct driver string would be:
jdbc:mysql://localhost:3307/dbname,"usrname","password"
Since you're only converting one character, the function atoi() is overkill. atoi() is useful if you are converting string representations of numbers. The other posts have given examples of this. If I read your post correctly, you are only converting one numeric character. So, you are only going to convert a character that is the range 0 to 9. In the case of only converting one numeric character, your suggestion to subtract '0' will give you the result you want. The reason why this works is because ASCII values are consecutive (like you said). So, subtracting the ASCII value of 0 (ASCII value 48 - see ASCII Table for values) from a numeric character will give the value of the number. So, your example of c = c - '0' where c = '5', what is really happening is 53 (the ASCII value of 5) - 48 (the ASCII value of 0) = 5.
When I first posted this answer, I didn't take into consideration your comment about being 100% portable between different character sets. I did some further looking around around and it seems like your answer is still mostly correct. The problem is that you are using a char which is an 8-bit data type. Which wouldn't work with all character types. Read this article by Joel Spolsky on Unicode for a lot more information on Unicode. In this article, he says that he uses wchar_t for characters. This has worked well for him and he publishes his web site in 29 languages. So, you would need to change your char to a wchar_t. Other than that, he says that the character under value 127 and below are basically the same. This would include characters that represent numbers. This means the basic math you proposed should work for what you were trying to achieve.
I see so many complicated answer.
All this confused me while I was adding my Aquery jar file in the new version of Android Studio.
This is what I did :
Copy pasted the jar file in the libs folder which is visible under Project view.
And in the build.gradle file just added this line : compile files('libs/android-query.jar')
PS : Once downloading the jar file please change its name. I changed the name to android-query.jar
I found a solution that worked in my case:
<input class="form-control" style="min-width: 100%!important;" type="text" />
You only need to override the min-width set 100% and important and the result is this one:
If you don't apply it, you will always get this:
Relying on JQuery Datepicker, but it could be done easily:
var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);
try to use this one on your view it worked for me:
<View
android:id="@+id/fucused"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"/>
I do not like editing the plist directly. You can easily add it to the plist using the GUI:
Now change the data in the main area:
Add Row
Use CSS grid and set all the grid items to be in the same cell.
.layered {
display: grid;
}
.layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
Adding the layered class to an element causes all it's children to be layered on top of each other.
if the layers are not the same size you can set the justify-items
and align-items
properties to set the horizontal and vertical alignment respectively.
.layered {
display: grid;
/* Set horizontal alignment of items in, case they have a different width. */
/* justify-items: start | end | center | stretch (default); */
justify-items: start;
/* Set vertical alignment of items, in case they have a different height. */
/* align-items: start | end | center | stretch (default); */
align-items: start;
}
.layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
/* for demonstration purposes only */
.layered > * {
outline: 1px solid red;
background-color: rgba(255, 255, 255, 0.4)
}
_x000D_
<div class="layered">
<img src="https://via.placeholder.com/250x100?text=first" />
<p>
2
</p>
<div>
<p>
Third layer
</p>
<p>
Third layer continued
</p>
<p>
Third layer continued
</p>
<p>
Third layer continued
</p>
</div>
</div>
_x000D_
Table Name
sp_rename 'db_name.old_table_name', 'new_table_name'
Column
sp_rename 'db_name.old_table_name.name' 'userName', 'COLUMN'
Index
sp_rename 'db_name.old_table_name.id', 'product_ID', 'INDEX'
also available for statics and datatypes
[[ There are some good answers here but I find that they still are lacking a bit of information. ]]
return (new StringBuilder("select id1, " + " id2 " + " from " + " table"))
.toString();
So as you point out, the example you give is a simplistic but let's analyze it anyway. What happens here is the compiler actually does the +
work here because "select id1, " + " id2 " + " from " + " table"
are all constants. So this turns into:
return new StringBuilder("select id1, id2 from table").toString();
In this case, obviously, there is no point in using StringBuilder
. You might as well do:
// the compiler combines these constant strings
return "select id1, " + " id2 " + " from " + " table";
However, even if you were appending any fields or other non-constants then the compiler would use an internal StringBuilder
-- there's no need for you to define one:
// an internal StringBuilder is used here
return "select id1, " + fieldName + " from " + tableName;
Under the covers, this turns into code that is approximately equivalent to:
StringBuilder sb = new StringBuilder("select id1, ");
sb.append(fieldName).append(" from ").append(tableName);
return sb.toString();
Really the only time you need to use StringBuilder
directly is when you have conditional code. For example, code that looks like the following is desperate for a StringBuilder
:
// 1 StringBuilder used in this line
String query = "select id1, " + fieldName + " from " + tableName;
if (where != null) {
// another StringBuilder used here
query += ' ' + where;
}
The +
in the first line uses one StringBuilder
instance. Then the +=
uses another StringBuilder
instance. It is more efficient to do:
// choose a good starting size to lower chances of reallocation
StringBuilder sb = new StringBuilder(64);
sb.append("select id1, ").append(fieldName).append(" from ").append(tableName);
// conditional code
if (where != null) {
sb.append(' ').append(where);
}
return sb.toString();
Another time that I use a StringBuilder
is when I'm building a string from a number of method calls. Then I can create methods that take a StringBuilder
argument:
private void addWhere(StringBuilder sb) {
if (where != null) {
sb.append(' ').append(where);
}
}
When you are using a StringBuilder
, you should watch for any usage of +
at the same time:
sb.append("select " + fieldName);
That +
will cause another internal StringBuilder
to be created. This should of course be:
sb.append("select ").append(fieldName);
Lastly, as @T.J.rowder points out, you should always make a guess at the size of the StringBuilder
. This will save on the number of char[]
objects created when growing the size of the internal buffer.
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
Inspired from @Grumdrig's answer, and because some of the used instructions would not work, I suggest the following script if needed by someone else:
$(document).ready(function () {
function reorient(e) {
var orientation = window.screen.orientation.type;
$("body > div").css("-webkit-transform", (orientation == 'landscape-primary' || orientation == 'landscape-secondary') ? "rotate(-90deg)" : "");
}
$(window).on("orientationchange",function(){
reorient();
});
window.setTimeout(reorient, 0);
});
The proposed solutions are perfect to download the images and if it is enough for you to save all the files in the directory you are using. But if you want to save all the images in a specified directory without reproducing the entire hierarchical tree of the site, try to add "cut-dirs" to the line proposed by Jon.
wget -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.boia.de --cut-dirs=1 --cut-dirs=2 --cut-dirs=3
in this case cut-dirs will prevent wget from creating sub-directories until the 3th level of depth in the website hierarchical tree, saving all the files in the directory you specified.You can add more 'cut-dirs' with higher numbers if you are dealing with sites with a deep structure.
You can use the Pattern
class for this. If you want to match only word characters inside the {}
then you can use the following regex. \w
is a shorthand for [a-zA-Z0-9_]
. If you are ok with _
then use \w
or else use [a-zA-Z0-9]
.
String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
System.out.println(matcher.group(0)); //prints /{item}/
} else {
System.out.println("Match not found");
}
An example for subtraction is given below:
Select value1 - (select value2 from AnyTable1) from AnyTable2
value1 & value2 can be count,sum,average output etc. But the values should be comapatible
Here is a sample I wrote shows how I parse a json and mess every number inside it:
public class JsonParser {
public static Object parseAndMess(Object object) throws IOException {
String json = JsonUtil.toJson(object);
JsonNode jsonNode = parseAndMess(json);
if(null != jsonNode)
return JsonUtil.toObject(jsonNode, object.getClass());
return null;
}
public static JsonNode parseAndMess(String json) throws IOException {
JsonNode rootNode = parse(json);
return mess(rootNode, new Random());
}
private static JsonNode parse(String json) throws IOException {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(json);
return rootNode;
}
private static JsonNode mess(JsonNode rootNode, Random rand) throws IOException {
if (rootNode instanceof ObjectNode) {
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
replaceObjectNode((ObjectNode) rootNode, field, rand);
}
} else if (rootNode instanceof ArrayNode) {
ArrayNode arrayNode = ((ArrayNode) rootNode);
replaceArrayNode(arrayNode, rand);
}
return rootNode;
}
private static void replaceObjectNode(ObjectNode rootNode, Map.Entry<String, JsonNode> field, Random rand)
throws IOException {
JsonNode childNode = field.getValue();
if (childNode instanceof IntNode) {
(rootNode).put(field.getKey(), rand.nextInt(1000));
} else if (childNode instanceof LongNode) {
(rootNode).put(field.getKey(), rand.nextInt(1000000));
} else if (childNode instanceof FloatNode) {
(rootNode).put(field.getKey(), format(rand.nextFloat()));
} else if (childNode instanceof DoubleNode) {
(rootNode).put(field.getKey(), format(rand.nextFloat()));
} else {
mess(childNode, rand);
}
}
private static void replaceArrayNode(ArrayNode arrayNode, Random rand) throws IOException {
int arrayLength = arrayNode.size();
if(arrayLength == 0)
return;
if (arrayNode.get(0) instanceof IntNode) {
for (int i = 0; i < arrayLength; i++) {
arrayNode.set(i, new IntNode(rand.nextInt(10000)));
}
} else if (arrayNode.get(0) instanceof LongNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(rand.nextInt(1000000));
}
} else if (arrayNode.get(0) instanceof FloatNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(format(rand.nextFloat()));
}
} else if (arrayNode.get(0) instanceof DoubleNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(format(rand.nextFloat()));
}
} else {
for (int i = 0; i < arrayLength; i++) {
mess(arrayNode.get(i), rand);
}
}
}
public static void print(JsonNode rootNode) throws IOException {
System.out.println(rootNode.toString());
}
private static double format(float a) {
return Math.round(a * 10000.0) / 100.0;
}
}
For ListBox / DropDown in MVC5 - i've found this to work for me sofar:
in Model:
[Required(ErrorMessage = "- Select item -")]
public List<string> SelectedItem { get; set; }
public List<SelectListItem> AvailableItemsList { get; set; }
in View:
@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })
Here is another way to do it if you want to use ViewData:
@Html.Partial("~/PathToYourView.cshtml", null, new ViewDataDictionary { { "VariableName", "some value" } })
And to retrieve the passed in values:
@{
string valuePassedIn = this.ViewData.ContainsKey("VariableName") ? this.ViewData["VariableName"].ToString() : string.Empty;
}
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id
?
UPDATE
SELECT t.*
FROM
(SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a
INNER JOIN temp_tickets t ON (t.id = a.id)
from collections import Counter
x = array( [1,1,1,2,2,2,5,25,1,1] )
mode = counter.most_common(1)[0][0]
Export like export default HelloWorld;
and import, such as import React from 'react'
are part of the ES6 modules system.
A module is a self contained unit that can expose assets to other modules using export
, and acquire assets from other modules using import
.
In your code:
import React from 'react'; // get the React object from the react module
class HelloWorld extends React.Component {
render() {
return <p>Hello, world!</p>;
}
}
export default HelloWorld; // expose the HelloWorld component to other modules
In ES6 there are two kinds of exports:
Named exports - for example export function func() {}
is a named export with the name of func
. Named modules can be imported using import { exportName } from 'module';.
In this case, the name of the import should be the same as the name of the export. To import the func in the example, you'll have to use import { func } from 'module';
. There can be multiple named exports in one module.
Default export - is the value that will be imported from the module, if you use the simple import statement import X from 'module'
. X is the name that will be given locally to the variable assigned to contain the value, and it doesn't have to be named like the origin export. There can be only one default export.
A module can contain both named exports and a default export, and they can be imported together using import defaultExport, { namedExport1, namedExport3, etc... } from 'module';
.
The best solution is to create singleton controller for your LED which will queue all commands and execute them with specified delay:
function LedController(timeout) {
this.timeout = timeout || 100;
this.queue = [];
this.ready = true;
}
LedController.prototype.send = function(cmd, callback) {
sendCmdToLed(cmd);
if (callback) callback();
// or simply `sendCmdToLed(cmd, callback)` if sendCmdToLed is async
};
LedController.prototype.exec = function() {
this.queue.push(arguments);
this.process();
};
LedController.prototype.process = function() {
if (this.queue.length === 0) return;
if (!this.ready) return;
var self = this;
this.ready = false;
this.send.apply(this, this.queue.shift());
setTimeout(function () {
self.ready = true;
self.process();
}, this.timeout);
};
var Led = new LedController();
Now you can call Led.exec
and it'll handle all delays for you:
Led.exec(cmd, function() {
console.log('Command sent');
});
I have not tried, but if you know Perl you can use the Parse-Stata-DtaReader module to convert the file for you.
The module has a command-line tool dta2csv, which can "convert Stata 8 and Stata 10 .dta files to csv"
I use Toad for Oracle and if the table is owned by another username than the one you logged in as and you have access to read the table, you still may need to add the original table owner to the table name.
For example, lets say the table owner's name is 'OWNER1' and you are logged in as 'USER1'. This query may give you a ORA-00904 error:
select * from table_name where x='test';
Prefixing the table_name with the table owner eliminated the error and gives results:
select * from
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
run this:
php artisan config:clear
php artisan cache:clear
then
php artisan config:cache
You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.
HTML
<li>
<a id="byParameter"
class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
presence of parameter</a>
</li>
Controller
@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
//Perform logic with foo
return "Mapped by path + method + presence of query parameter! (MappingController)";
}
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
I tried this code, to retrieve shared preferences from an activity, and could not get it to work:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getAll();
Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());
Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.
getPreferenceManager().setSharedPreferencesName("defaultPreferences");
After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.
You can use jQuery's $.map
.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
return i;
});
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
If you're using jQuery-UI, you must include the jQuery UI CSS package, otherwise the UI components don't know how to be styled.
If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied.
Here's an example and some possible fixes.
Here's a demo in Stack Snippets without jquery-ui.css (doesn't work)
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
There is a project that created a Bootstrap-esque theme for jQuery-UI components called jquery-ui-bootstrap. Just grab the stylesheet from there and you should be all set.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using.
After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's autocomplete.css and theme.css to figure out what styles you'll need to manually replace.
You can use bootstrap's dropdowns.less for inspiration.
Here's a sample CSS that fits pretty well with Bootstrap's default theme:
.ui-autocomplete {
position: absolute;
z-index: 1000;
cursor: default;
padding: 0;
margin-top: 2px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.ui-autocomplete > li {
padding: 3px 20px;
}
.ui-autocomplete > li.ui-state-focus {
background-color: #DDD;
}
.ui-helper-hidden-accessible {
display: none;
}
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
.ui-autocomplete {_x000D_
position: absolute;_x000D_
z-index: 1000;_x000D_
cursor: default;_x000D_
padding: 0;_x000D_
margin-top: 2px;_x000D_
list-style: none;_x000D_
background-color: #ffffff;_x000D_
border: 1px solid #ccc_x000D_
-webkit-border-radius: 5px;_x000D_
-moz-border-radius: 5px;_x000D_
border-radius: 5px;_x000D_
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
}_x000D_
.ui-autocomplete > li {_x000D_
padding: 3px 20px;_x000D_
}_x000D_
.ui-autocomplete > li.ui-state-focus {_x000D_
background-color: #DDD;_x000D_
}_x000D_
.ui-helper-hidden-accessible {_x000D_
display: none;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group ui-widget">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group ui-widget">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control" />_x000D_
</div>_x000D_
</div>
_x000D_
Tip: Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with
.ui-autocomplete
and removedisplay: none;
.
Wherever you invoke a generator from within a generator you need a "pump" to re-yield
the values: for v in inner_generator: yield v
. As the PEP points out there are subtle complexities to this which most people ignore. Non-local flow-control like throw()
is one example given in the PEP. The new syntax yield from inner_generator
is used wherever you would have written the explicit for
loop before. It's not merely syntactic sugar, though: It handles all of the corner cases that are ignored by the for
loop. Being "sugary" encourages people to use it and thus get the right behaviors.
This message in the discussion thread talks about these complexities:
With the additional generator features introduced by PEP 342, that is no longer the case: as described in Greg's PEP, simple iteration doesn't support send() and throw() correctly. The gymnastics needed to support send() and throw() actually aren't that complex when you break them down, but they aren't trivial either.
I can't speak to a comparison with micro-threads, other than to observe that generators are a type of paralellism. You can consider the suspended generator to be a thread which sends values via yield
to a consumer thread. The actual implementation may be nothing like this (and the actual implementation is obviously of great interest to the Python developers) but this does not concern the users.
The new yield from
syntax does not add any additional capability to the language in terms of threading, it just makes it easier to use existing features correctly. Or more precisely it makes it easier for a novice consumer of a complex inner generator written by an expert to pass through that generator without breaking any of its complex features.
These functions are fairly compact and only use standard Python 2.6 and later.
def ddhhmmss(seconds):
"""Convert seconds to a time string "[[[DD:]HH:]MM:]SS".
"""
dhms = ''
for scale in 86400, 3600, 60:
result, seconds = divmod(seconds, scale)
if dhms != '' or result > 0:
dhms += '{0:02d}:'.format(result)
dhms += '{0:02d}'.format(seconds)
return dhms
def seconds(dhms):
"""Convert a time string "[[[DD:]HH:]MM:]SS" to seconds.
"""
components = [int(i) for i in dhms.split(':')]
pad = 4 - len(components)
if pad < 0:
raise ValueError('Too many components to match [[[DD:]HH:]MM:]SS')
components = [0] * pad + components
return sum(i * j for i, j in zip((86400, 3600, 60, 1), components))
And here are tests to go with them. I'm using the pytest package as a simple way to test exceptions.
import ddhhmmss
import pytest
def test_ddhhmmss():
assert ddhhmmss.ddhhmmss(0) == '00'
assert ddhhmmss.ddhhmmss(2) == '02'
assert ddhhmmss.ddhhmmss(12 * 60) == '12:00'
assert ddhhmmss.ddhhmmss(3600) == '01:00:00'
assert ddhhmmss.ddhhmmss(10 * 86400) == '10:00:00:00'
assert ddhhmmss.ddhhmmss(86400 + 5 * 3600 + 30 * 60 + 1) == '01:05:30:01'
assert ddhhmmss.ddhhmmss(365 * 86400) == '365:00:00:00'
def test_seconds():
assert ddhhmmss.seconds('00') == 0
assert ddhhmmss.seconds('02') == 2
assert ddhhmmss.seconds('12:00') == 12 * 60
assert ddhhmmss.seconds('01:00:00') == 3600
assert ddhhmmss.seconds('1:0:0') == 3600
assert ddhhmmss.seconds('3600') == 3600
assert ddhhmmss.seconds('60:0') == 3600
assert ddhhmmss.seconds('10:00:00:00') == 10 * 86400
assert ddhhmmss.seconds('1:05:30:01') == 86400 + 5 * 3600 + 30 * 60 + 1
assert ddhhmmss.seconds('365:00:00:00') == 365 * 86400
def test_seconds_raises():
with pytest.raises(ValueError):
ddhhmmss.seconds('')
with pytest.raises(ValueError):
ddhhmmss.seconds('foo')
with pytest.raises(ValueError):
ddhhmmss.seconds('1:00:00:00:00')
in javascript , using jquery for canvas id selection :
var Canvas2 = $("#canvas2")[0];
var Context2 = Canvas2.getContext("2d");
var image = new Image();
image.src = "images/eye.jpg";
Context2.drawImage(image, 0, 0);
html5:
<canvas id="canvas2"></canvas>
This is how I implemented it pre-material design and it seems to still work now I've switched to the new Toolbar
. In my case I want to log the user in if they attempt to open the side nav while logged out, (and catch the event so the side nav won't open). In your case you could not return true;
.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!isLoggedIn() && item.getItemId() == android.R.id.home) {
login();
return true;
}
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
Thanks everybody. Lots of good ideas. This is my first application in Spring and Hibernate.. so a little more patience when dealing with "novices" like me..
Please read Tom Anderson and Roman C.'s answers. They explained very well the problem. And all of you helped me.I replaced
SELECT COUNT(*) FROM Books
with
select count(book.id) from Book book
And of course, I have this Spring config:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan" value="extjs.model"/>
Thank you all again!
First, define a new function to read the input (according to the structure of your input) and store the string, which means the memory in stack used. Set the length of string to be enough for your input.
Second, use strlen
to measure the exact used length of string stored before, and malloc
to allocate memory in heap, whose length is defined by strlen
. The code is shown below.
int strLength = strlen(strInStack);
if (strLength == 0) {
printf("\"strInStack\" is empty.\n");
}
else {
char *strInHeap = (char *)malloc((strLength+1) * sizeof(char));
strcpy(strInHeap, strInStack);
}
return strInHeap;
Finally, copy the value of strInStack
to strInHeap
using strcpy
, and return the pointer to strInHeap
. The strInStack
will be freed automatically because it only exits in this sub-function.
It should also be possible to either extend the listener by prototyping it (if we have a reference to it and its not an anonymous function) -or make the onclick
call a call to a function library (a function calling other functions).
Like:
elm.onclick = myFunctionList;
function myFunctionList(){
myFunc1();
myFunc2();
}
This means we never have to change the onclick
call just alter the function myFunctionList()
to do whatever we want, but this leaves us without control of bubbling/catching phases so should be avoided for newer browsers.
This worked for me as well:
Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"
This script will convert, to UTF-8 without BOM, all .txt files in DIRECTORY1 and output them to DIRECTORY2
foreach ($i in ls -name DIRECTORY1\*.txt)
{
$file_content = Get-Content "DIRECTORY1\$i";
[System.IO.File]::WriteAllLines("DIRECTORY2\$i", $file_content);
}
If you know the child element you're interested in is the first:
$('.second').children().first();
Or to find by index:
var index = 0
$('.second').children().eq(index);
Use java.time.Instant
class to parse text in standard ISO 8601 format, representing a moment in UTC.
Instant.parse( "2010-10-02T12:23:23Z" )
That format is defined by the ISO 8601 standard for date-time string formats.
Both:
…use ISO 8601 formats by default for parsing and generating strings.
You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.
Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Instant instant = Instant.parse( "2010-10-02T12:23:23Z" ); // `Instant` is always in UTC.
Convert to the old class.
java.util.Date date = java.util.Date.from( instant ); // Pass an `Instant` to the `from` method.
Time Zone
If needed, you can assign a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ); // Assign a time zone adjustment from UTC.
Convert.
java.util.Date date = java.util.Date.from( zdt.toInstant() ); // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.
UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.
Here is some example code in Joda-Time 2.8.
org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC ); // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.
Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.
java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.
Time Zone
If needed, you can assign a time zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I got the same error. In my case, I tried all of the above, but I couldn't get the result.
I finally realized that in my case, the reason for the error was that the certificate password was not entered or entered incorrectly. The error disappeared when I entered the password dynamically correctly. successful
You can also use the jqlite functionality built into angular.
angular.element('.selector').trigger('focus');
File.exist?("directory")
Dir[]
returns an array, so it will never be nil
. If you want to do it your way, you could do
Dir["directory"].empty?
which will return true
if it wasn't found.
Your code makes no sense, maybe because it's out of context.
If you mean code like this:
$('a').click(function () {
callFunction();
return false;
});
The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.
There are many scenarios where you want to commit a directory to your Git repo but without the files in it, for example the logs
, cache
, uploads
directories etc.
So what I always do is to add a .gitignore
file in those directories with the following content:
*
!.gitignore
With this .gitignore
file, Git will not track any files in those directories yet still allow me to add the .gitignore
file and hence the directory itself to the repo.
There is also a tool that oracle made called mysqlshow
If you run it with the --k keys $table_name
option it will display the keys.
SYNOPSIS
mysqlshow [options] [db_name [tbl_name [col_name]]]
.......
.......
.......
· --keys, -k
Show table indexes.
example:
?-? mysqlshow -h 127.0.0.1 -u root -p --keys database tokens
Database: database Table: tokens
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id | int(10) unsigned | | NO | PRI | | auto_increment | select,insert,update,references | |
| token | text | utf8mb4_unicode_ci | NO | | | | select,insert,update,references | |
| user_id | int(10) unsigned | | NO | MUL | | | select,insert,update,references | |
| expires_in | datetime | | YES | | | | select,insert,update,references | |
| created_at | timestamp | | YES | | | | select,insert,update,references | |
| updated_at | timestamp | | YES | | | | select,insert,update,references | |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tokens | 0 | PRIMARY | 1 | id | A | 2 | | | | BTREE | | |
| tokens | 1 | tokens_user_id_foreign | 1 | user_id | A | 2 | | | | BTREE | | |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
Method 1:\
add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables
Method 2: (if method 1 not work then)
simple open command prompt with "run as administrator"
Put your params in the data
part of the ajax
call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)
To do a cross server query, check out the system stored procedure: sp_addlinkedserver in the help files.
Once the server is linked you can run a query against it.
In the latest R (3.2.3) there is a bug, preventing it some times from finding correct package. The workaround is to set repository manually:
install.packages("lubridate", dependencies=TRUE, repos='http://cran.rstudio.com/')
Found solution in other question
Tchalvak, who commented on the original question, hit the nail on the head for me. I've been editing (I use Debian):
/etc/php5/apache2/php.ini
...which had the correct timezone for me and was the only .ini file being loaded with date.timezone within it, but I was receiving the above error when I ran a script through Bash. I had no idea that I should have been editing:
/etc/php5/cli/php.ini
as well. (Well, for me it was 'as well', for you it might be different of course, but I'm going to keep my Apache and CLI versions of php.ini synchronised now).
try out with this fastest JSON framework JSONKit. it's faster than normal JSON framework.
The global Git configuration file is stored at $HOME/.gitconfig
on all platforms.
However, you can simply open a terminal and execute git config
, which will write the appropriate changes to this file. You shouldn't need to manually tweak .gitconfig
, unless you particularly want to.
One approach that works from pretty much anywhere, including from places where you don't have an Activity
or View
, is to grab a Handler
to the main thread and show the toast:
public void toast(final Context context, final String text) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
});
}
The advantage of this approach is that it works with any Context
, including Service
and Application
.
public static Item getRandomChestItem(List<Item> items) {
return items.get(new Random().nextInt(items.size()));
}
If you are running this in a script, you'll want to add the following line afterwards to make it rerunnable, otherwise you get a procedure already exists error.
drop procedure foo;
FYI, the list of operators (containing like and all others) is in code:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
protected $operators = array(
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
);
disclaimer:
Joel Larson's answer is correct. Got my upvote.
I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.
Facebook's FQL documentation here tells you how to do it. Run the example SELECT name, fan_count FROM page WHERE page_id = 19292868552
and replace the page_id number with your page's id number and it will return the page name and the fan count.
There is also:
try:
del mydict[key]
except KeyError:
pass
This only does 1 lookup instead of 2. However, except
clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.
//get the value of a gridview
public string getUpdatingGridviewValue(GridView gridviewEntry, string fieldEntry)
{//start getGridviewValue
//scan gridview for cell value
string result = Convert.ToString(functionsOther.getCurrentTime());
for(int i = 0; i < gridviewEntry.HeaderRow.Cells.Count; i++)
{//start i for
if(gridviewEntry.HeaderRow.Cells[i].Text == fieldEntry)
{//start check field match
result = gridviewEntry.Rows[rowUpdateIndex].Cells[i].Text;
break;
}//end check field match
}//end i for
//return
return result;
}//end getGridviewValue
Simply, row_num = df.shape[0] # gives number of rows, here's the example:
import pandas as pd
import numpy as np
In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])
In [323]: df
Out[323]:
col_1 col_2
0 -0.894268 1.309041
1 -0.120667 -0.241292
2 0.076168 -1.071099
3 1.387217 0.622877
4 -0.488452 0.317882
In [324]: df.shape
Out[324]: (5, 2)
In [325]: df.shape[0] ## Gives no. of rows/records
Out[325]: 5
In [326]: df.shape[1] ## Gives no. of columns
Out[326]: 2
The output of getent passwd username
can be parsed with a Bash regular expression
OTHER_HOME="$(
[[ "$(
getent \
passwd \
"${OTHER_USER}"
)" =~ ([^:]*:){5}([^:]+) ]] \
&& echo "${BASH_REMATCH[2]}"
)"
If you use Express 4.x, you can use the req.get(headerName)
method as described in Express 4.x API Reference
The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-"
for a red line, or by explicitely stating the color
argument.
import matplotlib.pyplot as plt
plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line
plt.show()
See also the plot command's documentation.
In case you already have a line with a certain color, you can change that with the lines2D.set_color()
method.
line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line
plt.show()
If you want to change this color later on, you can do so by
plt.gca().get_lines()[0].set_color("black")
This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them
for ax in plt.gcf().axes:
ax.get_lines()[0].set_color("black")
and if you have more lines you can loop over them as well.
You can try this
public string ToString(this object value)
{
// this will throw an exception if value is null
string val = Convert.ToString (value);
// it can be a space
If (string.IsNullOrEmpty(val.Trim())
return string.Empty:
}
// to avoid not all code paths return a value
return val;
}
Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...
CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;
CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid),
INDEX(tmpid))
SELECT * FROM tmpLivecheck;
... solved my problem.
Greetings...
hi firstly there seems to be many 'errors' in your html where you are missing closing tags, you could try wrapping the contents of your <body>
in a fixed width <div style="margin: 0 auto; width: 900px>
to achieve what you have done with the body {margin: 0 10% 0 10%}
<div id="video_box">
<div id="video_overlays"></div>
<div>
<video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm" onclick="this.play();">Your browser does not support this streaming content.</video>
</div>
</div>
for this you need to just add css like this:
#video_overlays {
position: absolute;
background-color: rgba(0, 0, 0, 0.46);
z-index: 2;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#video_box{position: relative;}
Did you try assigning it back to the column?
df['column'] = df['column'].astype('str')
Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:
df['column_new'] = df['column'].str.split(',')
I encounter this problem when trying to use matlab eng to call m functions from c code.
which occurs with command mex -f .. ..
My solution:
strings /usr/lib/i386-<tab>/libstdc++.so.6 | grep GLIBC
I found it includes 3.4.15
so my system has the newest libs.
the problem comes from matlab itself, it calls its own libstdc++.so.6 from {MATLAB}/bin
so, just replace it with the updated system lib.
What you may actually want to use is an Iterable
that can return a fresh Iterator
multiple times by calling iterator()
.
//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
Iterator<Type> it = ible.iterator(); //Gets an iterator
while (it.hasNext()) {
it.next();
}
it = ible.iterator(); //Gets a NEW iterator, also from the beginning
while (it.hasNext()) {
it.next();
}
}
You must define what the iterator()
method does just once beforehand:
void main() {
LinkedList<String> list; //This could be any type of object that has an iterator
//Define an Iterable that knows how to retrieve a fresh iterator
Iterable<Type> ible = new Iterable<Type>() {
@Override
public Iterator<Type> iterator() {
return list.listIterator(); //Define how to get a fresh iterator from any object
}
};
//Now with a single instance of an Iterable,
func(ible); //you can iterate through it multiple times.
}
If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.
public class MyClass : BaseClass
{
private MyClass(string someString) : base(someString)
{
//your code goes in here
}
public static MyClass FactoryMethod(string someString)
{
//whatever you want to do with your string before passing it in
return new MyClass(someString);
}
}
The above method works good.
Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.
To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).
To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name])
.
To overwrite one file's content to another file. use cat eg.
echo "this is foo" > foobar.txt
cat foobar.txt
echo "this is bar" > bar.txt
cat bar.txt
Now to overwrite foobar we can use a cat command as below
cat bar.txt >> foobar.txt
cat foobar.txt
Use:
a:visited {
text-decoration: none;
}
But it will only affect links that haven't been clicked on yet.
This will help you
echo '<pre>';
$output = print_r($array,1);
echo '</pre>';
EDIT
using echo '<pre>';
is useless, but var_export($var);
will do the thing which you are expecting.
If you are working with character variables (note that stringsAsFactors
is false here) you can use replace:
junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12], stringsAsFactors = FALSE)
colnames(junk) <- c("nm", "val")
junk$nm <- replace(junk$nm, junk$nm == "B", "b")
junk
# nm val
# 1 A a
# 2 b b
# 3 C c
# 4 D d
# ...
Brief answer to your question: No. You shouldn't call ConfigureAwait(false)
at the application level like that.
TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false)
. Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.
Here is a bit more detailed explanation on the importance of ConfigureAwait
method (a quote from my blog post):
When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the
SynchronizationContext.Current
which gets the synchronization context for the current thread.SynchronizationContext.Current
is populated depending on the environment you are in. TheGetAwaiter
method of Task looks up forSynchronizationContext.Current
. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because
SynchronizationContext.Current
is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!
Also, here are two great articles for you which are exactly for your question:
Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).
Hope this helps.
Here you go:
user@host:~$ sed 's/^[\t ]*//g' < file-in.txt
Or:
user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt
Alternative way to check would be:
if (!$('#myModal').is(':visible')) {
// if modal is not shown/visible then do something
}
Do not forget to access iframe after it is loaded. Old but reliable way without jQuery:
<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>
<script>
function access() {
var iframe = document.getElementById("iframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
console.log(innerDoc.body);
}
</script>
To keep this question current it is worth highlighting that AssemblyInformationalVersion
is used by NuGet and reflects the package version including any pre-release suffix.
For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli
dotnet pack --version-suffix ci-7 src/MyProject
Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using:
CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);
For windows users with Chrome Versions 60.0.3112.78 (the day the solution was tested and worked) and at least until today 19.01.2019 (ver. 71.0.3578.98). You do not need to close any chrome instance.
BEWARE NOT TO USE THIS PARTICULAR BROWSER INSTANCE FOR BROWSING BECAUSE YOU CAN BE HACKED WITH IT!
An example of direct String
usage since 1.7 may be shown as well:
public static void main(String[] args) {
switch (args[0]) {
case "Monday":
case "Tuesday":
case "Wednesday":
System.out.println("boring");
break;
case "Thursday":
System.out.println("getting better");
case "Friday":
case "Saturday":
case "Sunday":
System.out.println("much better");
break;
}
}
Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.
The for loop you specified is absolutely correct.
Although i will do all the loops for you once again.
int sum = 0;
// for loop
for (int i = 1; i<= 100; i++){
sum = sum + i;
}
System.out.println(sum);
// while loop
sum = 0;
int j = 1;
while(j<=100){
sum = sum + j;
j++;
}
System.out.println(sum);
// do while loop
sum = 0;
j = 1;
do{
sum = sum + j;
j++;
}
while(j<=100);
System.out.println(sum);
In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.
For that you need reflection in C/C++ language, that doesn't exists. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers doesn't provide automatically that information in built binaries.
I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :
Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.
For example you can serialize like that :
// Random class initialization
com::class1* aObject = new com::class1();
for (int i=0; i<10; i++){
aObject->setData(i,i);
}
aObject->pdata = new char[7];
for (int i=0; i<7; i++){
aObject->pdata[i] = 7-i;
}
// dictionary initialization
cjson::dictionary aDict("./data/dictionary.xml");
// json transformation
std::string aJson = aDict.toJson<com::class1>(aObject);
// print encoded class
cout << aJson << std::endl ;
To deserialize data it works like that:
// decode the object
com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);
// modify data
aDecodedObject->setData(4,22);
// json transformation
aJson = aDict.toJson<com::class1>(aDecodedObject);
// print encoded class
cout << aJson << std::endl ;
Ouptuts:
>:~/cjson$ ./main
{"_index":54,"_inner": {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$
Usually these implementations are compiler dependent (ABI Specification for example), and requires external description to work (GCCXML output), such are not really easy to integrate to projects.
I think what you are trying to convey can be achieved through multiprocessing. However if you want to do it through threads you can do this. This might help
from threading import Thread
import time
def func1():
print 'Working'
time.sleep(2)
def func2():
print 'Working'
time.sleep(2)
th = Thread(target=func1)
th.start()
th1=Thread(target=func2)
th1.start()
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
I wanted something where I have access to base64 value to store into a list and for me adding event listener worked. You just need the FileReader which will read the image blob and return the base64 in the result.
createImageFromBlob(image: Blob) {
const reader = new FileReader();
const supportedImages = []; // you can also refer to some global variable
reader.addEventListener(
'load',
() => {
// reader.result will have the required base64 image
const base64data = reader.result;
supportedImages.push(base64data); // this can be a reference to global variable and store the value into that global list so as to use it in the other part
},
false
);
// The readAsDataURL method is used to read the contents of the specified Blob or File.
if (image) {
reader.readAsDataURL(image);
}
}
Final part is the readAsDataURL which is very important is being used to read the content of the specified Blob
The method shown below allows to run defined Excel macro from batch file, it uses environment variable to pass macro name from batch to Excel.
Put this code to the batch file (use your paths to EXCEL.EXE
and to the workbook):
Set MacroName=MyMacro
"C:\Program Files\Microsoft Office\Office15\EXCEL.EXE" "C:\MyWorkbook.xlsm"
Put this code to Excel VBA ThisWorkBook Object:
Private Sub Workbook_Open()
Dim strMacroName As String
strMacroName = CreateObject("WScript.Shell").Environment("process").Item("MacroName")
If strMacroName <> "" Then Run strMacroName
End Sub
And put your code to Excel VBA Module, like as follows:
Sub MyMacro()
MsgBox "MyMacro is running..."
End Sub
Launch the batch file and get the result:
For the case when you don't intend to run any macro just put empty value Set MacroName=
to the batch.
To reload a page with jQuery, do:
$.ajax({
url: "",
context: document.body,
success: function(s,x){
$(this).html(s);
}
});
The approach here that I used was Ajax jQuery. I tested it on Chrome 13. Then I put the code in the handler that will trigger the reload. The URL is ""
, which means this page.
I had a similar problem and it was caused by the placement of the Timer initialisation.
It was placed in a method that was invoked oftener.
Try this:
Timer waitTimer;
void exampleMethod() {
if (waitTimer == null ) {
//initialize your Timer here
...
}
The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.
If you execute the following example, you will know the difference between a Throw and a Catch block.
In general terms:
The catch block will handle the Exception
throws will pass the error to his caller.
In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().
public class CatchThrow {
private static void throwsMethod() throws NumberFormatException {
String intNumber = "5A";
Integer.parseInt(intNumber);
}
private static void catchMethod() {
try {
throwsMethod();
} catch (NumberFormatException e) {
System.out.println("Convertion Error");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
catchMethod();
}
}
For the SQL Server 2019 (Express Edition) installation, I did the following:
SQL Server Installation Center
Installation
New SQL Server stand-alone installation or add features to
an existing installation
C:\SQL2019\Express_ENU
and click OK
See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.
They are both used in the request to the server so the server knows what kind of data to receive/send.
since a string as '1234' with typeof will show 'string', and the inverse cannot ever happen (typeof 123 will always be number), the best is to use a simple regex /^\-?\d+$/.test(var)
. Or a more advanced to match floats, integers and negative numbers, /^[\-\+]?[\d]+\.?(\d+)?$/
The important side of .test
is that it WON'T throw an exception if the var isn't an string, the value can be anything.
var val, regex = /^[\-\+]?[\d]+\.?(\d+)?$/;
regex.test(val) // false
val = '1234';
regex.test(val) // true
val = '-213';
regex.test(val) // true
val = '-213.2312';
regex.test(val) // true
val = '+213.2312';
regex.test(val) // true
val = 123;
regex.test(val) // true
val = new Number(123);
regex.test(val) // true
val = new String('123');
regex.test(val) // true
val = '1234e';
regex.test(val) // false
val = {};
regex.test(val) // false
val = false;
regex.test(val) // false
regex.test(undefined) // false
regex.test(null) // false
regex.test(window) // false
regex.test(document) // false
If you are looking for the real type, then typeof alone will do.
I suppose you could want to test the base functionality of an abstract class... But you'd probably be best off by extending the class without overriding any methods, and make minimum-effort mocking for the abstract methods.
$ git commit --allow-empty -m "Trigger Build"
Try .html() instead of .val() :
var text = $('#frame1').contents().find('#area1').html();
Try this ...
Dim r as Range
Dim x as Integer
For x = 5000 to 4 step -1 '---> or change as you want //Thanx 4 KazJaw
set r = range("E" & format(x))
if ucase(r.Value) = "NONE" then
Rows(x).EntireRow.Delete
end if
Next
As per MSDN the default value is 4096 KB (4 MB).
UPDATE
As for the Maximum, since it is an int data type, then theoretically you can go up to 2,147,483,647. Also I wanted to make sure that you are aware that IIS 7 uses maxAllowedContentLength for specifying file upload size. By default it is set to 30000000 around 30MB and being an uint, it should theoretically allow a max of 4,294,967,295
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
Simply restate the target field & condition;
where (field like "*AA*" and field not like "*BB*")
You can do it, but not at the point you've specified. Within the context of B
, you may invoke A.X()
by calling base.X()
.
You define the variable name re16digit
but later refer to it as re10digit
, which will throw an error. To simplify your code, you should use RegExp.prototype.test()
rather than String.prototype.search()
:
function validate_creditcardnumber() {
var re16digit = /^\d{16}$/;
if (!re16digit.test(document.myform.CreditCardNumber.value)) {
alert("Please enter your 16 digit credit card numbers");
return false;
}
}
Working demo: http://jsfiddle.net/Dxjkh/
As others have mentioned, you may be better off using a JavaScript implementation of the Luhn Algorithm. It's also worth mentioning that a check for 16 digits will fail for American Express (15 digits) and Diners (14 digits) cards.
You can also use LocalDate.parse()
or LocalDateTime.parse()
on a String
without providing it with a pattern, if the String
is in ISO-8601 format.
for example,
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);
String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);
Output,
Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30
and use DateTimeFormatter
only if you have to deal with other date patterns.
For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);
Output
04 Aug 2015 parses to 2015-08-04
also remember that the DateTimeFormatter
object is bidirectional; it can both parse input and format output.
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));
Output
2015-08-04 formats as 04 Aug 2015
(see complete list of Patterns for Formatting and Parsing DateFormatter)
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
p pad next pad modifier 1
' escape for text delimiter
'' single quote literal '
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use
Using wrap=virtual
in your HTML form boxes gets rid of the horizontal scrollbar at the bottom of the box:
<textarea name= "enquiry" rows="4" cols="30" wrap="virtual"></textarea>
See example here : http://jsbin.com/opube3/2 (Tested on FF and IE)
Docker really needs to implement this as a new feature, but here's another workaround option for situations in which you have an Entrypoint that terminates after success or failure, which can make it difficult to debug.
If you don't already have an Entrypoint script, create one that runs whatever command(s) you need for your container. Then, at the top of this file, add these lines to entrypoint.sh
:
# Run once, hold otherwise
if [ -f "already_ran" ]; then
echo "Already ran the Entrypoint once. Holding indefinitely for debugging."
cat
fi
touch already_ran
# Do your main things down here
To ensure that cat
holds the connection, you may need to provide a TTY. I'm running the container with my Entrypoint script like so:
docker run -t --entrypoint entrypoint.sh image_name
This will cause the script to run once, creating a file that indicates it has already run (in the container's virtual filesystem). You can then restart the container to perform debugging:
docker start container_name
When you restart the container, the already_ran
file will be found, causing the Entrypoint script to stall with cat
(which just waits forever for input that will never come, but keeps the container alive). You can then execute a debugging bash
session:
docker exec -i container_name bash
While the container is running, you can also remove already_ran
and manually execute the entrypoint.sh
script to rerun it, if you need to debug that way.
This solution appears better to me, regarding maintainability and design for change:
Create the logging property file embedding it in the resource project folder, to be included in the jar file:
# Logging
handlers = java.util.logging.ConsoleHandler
.level = ALL
# Console Logging
java.util.logging.ConsoleHandler.level = ALL
Load the property file from code:
public static java.net.URL retrieveURLOfJarResource(String resourceName) {
return Thread.currentThread().getContextClassLoader().getResource(resourceName);
}
public synchronized void initializeLogger() {
try (InputStream is = retrieveURLOfJarResource("logging.properties").openStream()) {
LogManager.getLogManager().readConfiguration(is);
} catch (IOException e) {
// ...
}
}
now you can use rgba in CSS properties like this:
.class {
background: rgba(0,0,0,0.5);
}
0.5 is the transparency, change the values according to your design.
Live demo http://jsfiddle.net/EeAaB/
I really fail to see the use case... If you will type print_var_name($foobar) what's so hard (and different) about typing print("foobar") instead?
Because even if you were to use this in a function, you'd get the local name of the variable...
In any case, here's the reflection manual in case there's something you need in there.
Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.
window.location.href = window.location.href
I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.
/**
* ResizeHeaderOnScroll
*
* @constructor
*/
var ResizeHeaderOnScroll = function()
{
this.protocol = window.location.protocol;
this.domain = window.location.host;
};
ResizeHeaderOnScroll.prototype.init = function()
{
if($(document).scrollTop() > 0)
{
$('header').data('size','big');
} else {
$('header').data('size','small');
}
ResizeHeaderOnScroll.prototype.checkScrolling();
$(window).scroll(function(){
ResizeHeaderOnScroll.prototype.checkScrolling();
});
};
ResizeHeaderOnScroll.prototype.checkScrolling = function()
{
if($(document).scrollTop() > 0)
{
if($('header').data('size') == 'big')
{
$('header').data('size','small');
$('header').stop().animate({
paddingTop:'1em',
paddingBottom:'1em'
},200);
}
}
else
{
if($('header').data('size') == 'small')
{
$('header').data('size','big');
$('header').stop().animate({
paddingTop:'3em'
},200);
}
}
}
$(document).ready(function(){
var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
resizeHeaderOnScroll.init()
})
A good way is to derive from TcpClient and override the Disposing(bool) method:
class MyClient : TcpClient {
public bool IsDead { get; set; }
protected override void Dispose(bool disposing) {
IsDead = true;
base.Dispose(disposing);
}
}
Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.
Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.
EDIT: A reflection example:
using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
// Retrieve a FieldInfo instance corresponding to the field
PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
// Retrieve the value of the field, and cast as necessary
return (bool)field.GetValue(s, null);
}
Here is the solution which works for me:
I do the relative imports as from ..sub2 import mod2
and then, if I want to run mod1.py
then I go to the parent directory of app
and run the module using the python -m switch as python -m app.sub1.mod1
.
The real reason why this problem occurs with relative imports, is that relative imports works by taking the __name__
property of the module. If the module is being directly run, then __name__
is set to __main__
and it doesn't contain any information about package structure. And, thats why python complains about the relative import in non-package
error.
So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.
I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)
Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.
Short answer: You can't. rm
removes files blindly, with no concept of 'trash'.
Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i
by default, but not all do.
Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete
.
In the future, use rm
with caution. Either create a del
alias that provides interactivity, or use a file manager.
That should work:
>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
A
0 0
1 1
2 2
But the append
doesn't happen in-place, so you'll have to store the output if you want it:
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
A
0 0
1 1
2 2
feel free to use this tool https://github.com/rooty0/ffmpeg_video_cutter I wrote awhile ago Pretty much that's cli front-end for ffmpeg... you just need to create a yaml what you want to cut out... something like this
cut_method: delete # we're going to delete following video fragments from a video
timeframe:
- from: start # waiting for people to join the conference
to: 4m
- from: 10m11s # awkward silence
to: 15m50s
- from: 30m5s # Off-Topic Discussion
to: end
and then just run a tool to get result
With re-encoding:
ffmpeg -y -i seeing_noaudio.mp4 -vf "setpts=1.25*PTS" -r 24 seeing.mp4
Without re-encoding:
First step - extract video to raw bitstream
ffmpeg -y -i seeing_noaudio.mp4 -c copy -f h264 seeing_noaudio.h264
Remux with new framerate
ffmpeg -y -r 24 -i seeing_noaudio.h264 -c copy seeing.mp4
In Select2 4.0.2
$("#yourId").append("<option value='"+item+"' selected>"+item+"</option>");
$('#yourId').trigger('change');
No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng
is producing the same result as Joe's code.
If you need to switch sheets for some reasons, use Application.ScreenUpdating = False
at the beginning of your macro (and Application.ScreenUpdating=True
at the end). This will remove the screenflickering - and speed up the execution.
NSSM is totally free and hyper-easy, running command prompt / terminal as administrator:
nssm install "YourCoolServiceNameLabel"
then a dialog will appear so you can choose where is the file you want to run.
to uninstall
nssm remove "YourCoolServiceNameLabel"
You can accomplish this with a slightly different syntax:
ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}"
This post was the starting point of my solution, lots of good ideas here so I though I would share my results. The main insight is that I've found a way to get around the slowness of keypoint-based image matching by exploiting the speed of phash.
For the general solution, it's best to employ several strategies. Each algorithm is best suited for certain types of image transformations and you can take advantage of that.
At the top, the fastest algorithms; at the bottom the slowest (though more accurate). You might skip the slow ones if a good match is found at the faster level.
I am having very good results with phash. The accuracy is good for rescaled images. It is not good for (perceptually) modified images (cropped, rotated, mirrored, etc). To deal with the hashing speed we must employ a disk cache/database to maintain the hashes for the haystack.
The really nice thing about phash is that once you build your hash database (which for me is about 1000 images/sec), the searches can be very, very fast, in particular when you can hold the entire hash database in memory. This is fairly practical since a hash is only 8 bytes.
For example, if you have 1 million images it would require an array of 1 million 64-bit hash values (8 MB). On some CPUs this fits in the L2/L3 cache! In practical usage I have seen a corei7 compare at over 1 Giga-hamm/sec, it is only a question of memory bandwidth to the CPU. A 1 Billion-image database is practical on a 64-bit CPU (8GB RAM needed) and searches will not exceed 1 second!
For modified/cropped images it would seem a transform-invariant feature/keypoint detector like SIFT is the way to go. SIFT will produce good keypoints that will detect crop/rotate/mirror etc. However the descriptor compare is very slow compared to hamming distance used by phash. This is a major limitation. There are a lot of compares to do, since there are maximum IxJxK descriptor compares to lookup one image (I=num haystack images, J=target keypoints per haystack image, K=target keypoints per needle image).
To get around the speed issue, I tried using phash around each found keypoint, using the feature size/radius to determine the sub-rectangle. The trick to making this work well, is to grow/shrink the radius to generate different sub-rect levels (on the needle image). Typically the first level (unscaled) will match however often it takes a few more. I'm not 100% sure why this works, but I can imagine it enables features that are too small for phash to work (phash scales images down to 32x32).
Another issue is that SIFT will not distribute the keypoints optimally. If there is a section of the image with a lot of edges the keypoints will cluster there and you won't get any in another area. I am using the GridAdaptedFeatureDetector in OpenCV to improve the distribution. Not sure what grid size is best, I am using a small grid (1x3 or 3x1 depending on image orientation).
You probably want to scale all the haystack images (and needle) to a smaller size prior to feature detection (I use 210px along maximum dimension). This will reduce noise in the image (always a problem for computer vision algorithms), also will focus detector on more prominent features.
For images of people, you might try face detection and use it to determine the image size to scale to and the grid size (for example largest face scaled to be 100px). The feature detector accounts for multiple scale levels (using pyramids) but there is a limitation to how many levels it will use (this is tunable of course).
The keypoint detector is probably working best when it returns less than the number of features you wanted. For example, if you ask for 400 and get 300 back, that's good. If you get 400 back every time, probably some good features had to be left out.
The needle image can have less keypoints than the haystack images and still get good results. Adding more doesn't necessarily get you huge gains, for example with J=400 and K=40 my hit rate is about 92%. With J=400 and K=400 the hit rate only goes up to 96%.
We can take advantage of the extreme speed of the hamming function to solve scaling, rotation, mirroring etc. A multiple-pass technique can be used. On each iteration, transform the sub-rectangles, re-hash, and run the search function again.
Quick solution. There are already really great answers above. I am also adding my quick 2 points input, which is presented in the screenshot.
If you are not using Navigation Controller
then from Right Menu Inspector
set the Presentation to Full Screen
If you are using Navigation Controller
then by default it will present full screen, you have to do nothing.
test = data.frame(C=c(0,2,4, 7, 8), A=c(4,2,4, 7, 8), B=c(1, 3, 8,3,2))
Using the simple following function replacement can be performed (but only if data frame does not have many columns):
test <- test[, c("A", "B", "C")]
for others:
test <- test[, c("B", "A", "C")]
For error 7302 in particular, I discovered, in my registry, when looking for OraOLEDB.Oracle that the InprocServer32 location was wrong.
If that's the case, or you can't find that string in the registry, then you'll have to install or re-register the component.
I had to delete the key from the GUID level, and then find the ProgID (OraOLEDB.Oracle) key, and delete that too. (The ProgID links to the CLSID as a pair).
Then I re-registered OraOLEDB.Oracle by calling regsvr32.exe on ORAOLEDB*.dll.
Just re-registering alone didn't solve the problem, I had to delete the registry keys to make it point to the correct location. Alternatively, hack the InprocServer32 location.
Now I have error 7308, about single threaded apartments; rolling on!
you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend
You can also use
SELECT @curRow := ifnull(@curRow,0) + 1 Row, ...
to initialise the counter variable.
There is also another way of getting thread id. While creating threads with
int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);
function call; the first parameter pthread_t * thread
is actually a thread id (that is an unsigned long int defined in bits/pthreadtypes.h). Also, the last argument void *arg
is the argument that is passed to void * (*start_routine)
function to be threaded.
You can create a structure to pass multiple arguments and send a pointer to a structure.
typedef struct thread_info {
pthread_t thread;
//...
} thread_info;
//...
tinfo = malloc(sizeof(thread_info) * NUMBER_OF_THREADS);
//...
pthread_create (&tinfo[i].thread, NULL, handler, (void*)&tinfo[i]);
//...
void *handler(void *targs) {
thread_info *tinfo = targs;
// here you get the thread id with tinfo->thread
}
Was facing similar issue and found below link more helpful then the answers provided here. I guess this is due to the updates to AWS CLI since the answers are provided.
https://serverfault.com/questions/792937/the-config-profile-adminuser-could-not-be-found
Essentially it helps to create two different files (i.e. one for the general config related information and the second for the credentials related information).
This can be done in a much simpler manner now.
$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));
This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.
You can turn an array into a stream by using Arrays.stream()
:
int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);
Once you've got your stream, you can use any of the methods described in the documentation, like sum()
or whatever. You can map
or filter
like in Python by calling the relevant stream methods with a Lambda function:
Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);
Once you're done modifying your stream, you then call toArray()
to convert it back into an array to use elsewhere:
int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();
I solved it with the help of this answer
1.Add the following in Linear Layout of list_items.xml
android:descendantFocusability="blocksDescendants"
2.Child Views of LinearLayout in list_items.xml
android:focusable="false"
I have tried every single solution there was. In the end, this was my problem: when installing the developer certificate I have set it to "Always Trust", when I changed that back to default, it worked. All credit for this goes to: https://blog.supereasyapps.com/how-to-fix-iphone-and-ipad-app-codesign-crashes-using-an-apple-developer-profile/
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
angularjs controller way, just an example to look for one or more email in the body of a message.
sp = $scope.messagebody; // email message body
if (sp != null && sp.match(/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+/)) {
console.log('Error. You are not allowed to have an email in the message body');
}
Use StatefulWidget
and setState
to update dropdown.
String _dropDownValue;
@override
Widget build(BuildContext context) {
return DropdownButton(
hint: _dropDownValue == null
? Text('Dropdown')
: Text(
_dropDownValue,
style: TextStyle(color: Colors.blue),
),
isExpanded: true,
iconSize: 30.0,
style: TextStyle(color: Colors.blue),
items: ['One', 'Two', 'Three'].map(
(val) {
return DropdownMenuItem<String>(
value: val,
child: Text(val),
);
},
).toList(),
onChanged: (val) {
setState(
() {
_dropDownValue = val;
},
);
},
);
}
initial state of dropdown:
Open dropdown and select value:
Reflect selected value to dropdown:
This post helped me A LOT!
I added UIViewAlertForUnsatisfiableConstraints symbolic breakpoint with suggested action:
Obj-C project
po [[UIWindow keyWindow] _autolayoutTrace]
Swift project
expr -l objc++ -O -- [[UIWindow keyWindow] _autolayoutTrace]
With this hint, the log became more detailed, and It was easier for me identify which view had the constraint broken.
UIWindow:0x7f88a8e4a4a0
| UILayoutContainerView:0x7f88a8f23b70
| | UINavigationTransitionView:0x7f88a8ca1970
| | | UIViewControllerWrapperView:0x7f88a8f2aab0
| | | | •UIView:0x7f88a8ca2880
| | | | | *UIView:0x7f88a8ca2a10
| | | | | | *UIButton:0x7f88a8c98820'Archived'
| | | | | | | UIButtonLabel:0x7f88a8cb0e30'Archived'
| | | | | | *UIButton:0x7f88a8ca22d0'Download'
| | | | | | | UIButtonLabel:0x7f88a8cb04e0'Download'
| | | | | | *UIButton:0x7f88a8ca1580'Deleted'
| | | | | | | UIButtonLabel:0x7f88a8caf100'Deleted'
| | | | | *UIView:0x7f88a8ca33e0
| | | | | *_UILayoutGuide:0x7f88a8ca35b0
| | | | | *_UILayoutGuide:0x7f88a8ca4090
| | | | | _UIPageViewControllerContentView:0x7f88a8f1a390
| | | | | | _UIQueuingScrollView:0x7f88aa031c00
| | | | | | | UIView:0x7f88a8f38070
| | | | | | | UIView:0x7f88a8f381e0
| | | | | | | | •UIView:0x7f88a8f39fa0, MISSING HOST CONSTRAINTS
| | | | | | | | | *UIButton:0x7f88a8cb9bf0'Retrieve data'- AMBIGUOUS LAYOUT for UIButton:0x7f88a8cb9bf0'Retrieve data'.minX{id: 170}, UIButton:0x7f88a8cb9bf0'Retrieve data'.minY{id: 171}
| | | | | | | | | *UIImageView:0x7f88a8f3ad80- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8f3ad80.minX{id: 172}, UIImageView:0x7f88a8f3ad80.minY{id: 173}
| | | | | | | | | *App.RecordInfoView:0x7f88a8cbe530- AMBIGUOUS LAYOUT for App.RecordInfoView:0x7f88a8cbe530.minX{id: 174}, App.RecordInfoView:0x7f88a8cbe530.minY{id: 175}, App.RecordInfoView:0x7f88a8cbe530.Width{id: 176}, App.RecordInfoView:0x7f88a8cbe530.Height{id: 177}
| | | | | | | | | | +UIView:0x7f88a8cc1d30- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc1d30.minX{id: 178}, UIView:0x7f88a8cc1d30.minY{id: 179}, UIView:0x7f88a8cc1d30.Width{id: 180}, UIView:0x7f88a8cc1d30.Height{id: 181}
| | | | | | | | | | | *UIView:0x7f88a8cc1ec0- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc1ec0.minX{id: 153}, UIView:0x7f88a8cc1ec0.minY{id: 151}, UIView:0x7f88a8cc1ec0.Width{id: 154}, UIView:0x7f88a8cc1ec0.Height{id: 165}
| | | | | | | | | | | | *UIView:0x7f88a8e68e10- AMBIGUOUS LAYOUT for UIView:0x7f88a8e68e10.minX{id: 155}, UIView:0x7f88a8e68e10.minY{id: 150}, UIView:0x7f88a8e68e10.Width{id: 156}
| | | | | | | | | | | | *UIImageView:0x7f88a8e65de0- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8e65de0.minX{id: 159}, UIImageView:0x7f88a8e65de0.minY{id: 182}
| | | | | | | | | | | | *UILabel:0x7f88a8e69080'8-6-2015'- AMBIGUOUS LAYOUT for UILabel:0x7f88a8e69080'8-6-2015'.minX{id: 183}, UILabel:0x7f88a8e69080'8-6-2015'.minY{id: 184}, UILabel:0x7f88a8e69080'8-6-2015'.Width{id: 185}
| | | | | | | | | | | | *UILabel:0x7f88a8cc0690'16:34'- AMBIGUOUS LAYOUT for UILabel:0x7f88a8cc0690'16:34'.minX{id: 186}, UILabel:0x7f88a8cc0690'16:34'.minY{id: 187}, UILabel:0x7f88a8cc0690'16:34'.Width{id: 188}, UILabel:0x7f88a8cc0690'16:34'.Height{id: 189}
| | | | | | | | | | | | *UIView:0x7f88a8cc2050- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc2050.minX{id: 161}, UIView:0x7f88a8cc2050.minY{id: 166}, UIView:0x7f88a8cc2050.Width{id: 163}
| | | | | | | | | | | | *UIImageView:0x7f88a8e69d90- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8e69d90.minX{id: 190}, UIImageView:0x7f88a8e69d90.minY{id: 191}, UIImageView:0x7f88a8e69d90.Width{id: 192}, UIImageView:0x7f88a8e69d90.Height{id: 193}
| | | | | | | | | | | *UIView:0x7f88a8f3cc00
| | | | | | | | | | | | *UIView:0x7f88a8e618d0
| | | | | | | | | | | | *UIImageView:0x7f88a8e5ba10
| | | | | | | | | | | | *UIView:0x7f88a8f3cd70
| | | | | | | | | | | | *UIImageView:0x7f88a8e58e10
| | | | | | | | | | | | *UIImageView:0x7f88a8e5e7a0
| | | | | | | | | | | | *UIView:0x7f88a8f3cee0
| | | | | | | | | | | *UIView:0x7f88a8f3dc70
| | | | | | | | | | | | *UIView:0x7f88a8e64dd0
| | | | | | | | | | | | *UILabel:0x7f88a8e65290'Average flow rate'
| | | | | | | | | | | | *UILabel:0x7f88a8e712d0'177.0 ml/s'
| | | | | | | | | | | | *UILabel:0x7f88a8c97150'1299.4'
| | | | | | | | | | | | *UIView:0x7f88a8f3dde0
| | | | | | | | | | | | *UILabel:0x7f88a8f3df50'Maximum flow rate'
| | | | | | | | | | | | *UILabel:0x7f88a8cbfdb0'371.6 ml/s'
| | | | | | | | | | | | *UILabel:0x7f88a8cc0230'873.5'
| | | | | | | | | | | | *UIView:0x7f88a8f3e2a0
| | | | | | | | | | | | *UILabel:0x7f88a8f3e410'Total volume'
| | | | | | | | | | | | *UILabel:0x7f88a8cc0f20'371.6 ml'
| | | | | | | | | | | | *UIView:0x7f88a8f3e870
| | | | | | | | | | | | *UILabel:0x7f88a8f3ea00'Time do max. flow'
| | | | | | | | | | | | *UILabel:0x7f88a8cc0ac0'3.6 s'
| | | | | | | | | | | | *UIView:0x7f88a8f3ee10
| | | | | | | | | | | | *UILabel:0x7f88a8f3efa0'Flow time'
| | | | | | | | | | | | *UILabel:0x7f88a8cbf980'2.1 s'
| | | | | | | | | | | | *UIView:0x7f88a8f3f3e0
| | | | | | | | | | | | *UILabel:0x7f88a8f3f570'Voiding time'
| | | | | | | | | | | | *UILabel:0x7f88a8cc17e0'3.5 s'
| | | | | | | | | | | | *UIView:0x7f88a8f3f9a0
| | | | | | | | | | | | *UILabel:0x7f88a8f3fb30'Voiding delay'
| | | | | | | | | | | | *UILabel:0x7f88a8cc1380'1.0 s'
| | | | | | | | | | | | *UIView:0x7f88a8e65000
| | | | | | | | | | | | *UIButton:0x7f88a8e52f20'Show'
| | | | | | | | | | | | *UIImageView:0x7f88a8e6e1d0
| | | | | | | | | | | | *UIButton:0x7f88a8e52c90'Send'
| | | | | | | | | | | | *UIImageView:0x7f88a8e61bb0
| | | | | | | | | | | | *UIButton:0x7f88a8e528e0'Delete'
| | | | | | | | | | | | *UIImageView:0x7f88a8e6b3f0
| | | | | | | | | | | | *UIView:0x7f88a8f3ff60
| | | | | | | | | *UIActivityIndicatorView:0x7f88a8cba080
| | | | | | | | | | UIImageView:0x7f88a8cba700
| | | | | | | | | *_UILayoutGuide:0x7f88a8cc3150
| | | | | | | | | *_UILayoutGuide:0x7f88a8cc3b10
| | | | | | | UIView:0x7f88a8f339c0
| | UINavigationBar:0x7f88a8c96810
| | | _UINavigationBarBackground:0x7f88a8e45c00
| | | | UIImageView:0x7f88a8e46410
| | | UINavigationItemView:0x7f88a8c97520'App'
| | | | UILabel:0x7f88a8c97cc0'App'
| | | UINavigationButton:0x7f88a8e3e850
| | | | UIImageView:0x7f88a8e445b0
| | | _UINavigationBarBackIndicatorView:0x7f88a8f2b530
Legend:
* - is laid out with auto layout
+ - is laid out manually, but is represented in the layout engine because translatesAutoresizingMaskIntoConstraints = YES
• - layout engine host
Then I paused execution and I changed problematic view's background color with the command (replacing 0x7f88a8cc2050
with the memory address of your object of course)...
Obj-C
expr ((UIView *)0x7f88a8cc2050).backgroundColor = [UIColor redColor]
Swift 3.0
expr -l Swift -- import UIKit
expr -l Swift -- unsafeBitCast(0x7f88a8cc2050, to: UIView.self).backgroundColor = UIColor.red
... and the result It was awesome!
Simply amazing! Hope It helps.
To use a promise, you have to either call a function that creates a promise or you have to create one yourself. You don't really describe what problem you're really trying to solve, but here's how you would create a promise yourself:
function justTesting(input) {_x000D_
return new Promise(function(resolve, reject) {_x000D_
// some async operation here_x000D_
setTimeout(function() {_x000D_
// resolve the promise with some value_x000D_
resolve(input + 10);_x000D_
}, 500);_x000D_
});_x000D_
}_x000D_
_x000D_
justTesting(29).then(function(val) {_x000D_
// you access the value from the promise here_x000D_
log(val);_x000D_
});_x000D_
_x000D_
// display output in snippet_x000D_
function log(x) {_x000D_
document.write(x);_x000D_
}
_x000D_
Or, if you already have a function that returns a promise, you can use that function and return its promise:
// function that returns a promise_x000D_
function delay(t) {_x000D_
return new Promise(function(resolve) {_x000D_
setTimeout(function() {_x000D_
resolve();_x000D_
}, t);_x000D_
});_x000D_
}_x000D_
_x000D_
function justTesting(input) {_x000D_
return delay(100).then(function() {_x000D_
return input + 10;_x000D_
});_x000D_
}_x000D_
_x000D_
justTesting(29).then(function(val) {_x000D_
// you access the value from the promise here_x000D_
log(val);_x000D_
});_x000D_
_x000D_
// display output in snippet_x000D_
function log(x) {_x000D_
document.write(x);_x000D_
}
_x000D_
you need to simply add /Y
xcopy /s c:\mmyinbox\test.doc C:\myoutbox /Y
and if you're using path with spaces, try this
xcopy /s "c:\mmyinbox\test.doc" "C:\myoutbox" /Y
You can use
android:ellipsize="marquee"
with your textview.
But remember to put focus on the desired textview.
I got the error failed to initialize NVML: Driver/Library version mismatch
from my nvidia-gpu-temperature-indicator. And nvidia-smi failed to print any info. I tried to find if there were other versions of nvidia driver installed in my ubuntu. But I just found nvidia-driver-390. In the end, reboot
helped me solve the problem.
For anyone that is looking for an easy solution in Visual Studio Community 2019, Fine Code Coverage is simple but it works well.
It cannot give accurate numbers on the precise coverage, but it will tell which lines are being covered with green/red gutters.
Another example is, you have class like :
@obc class Album: NSObject {
let name:String
let singer:Singer
let artwork:URL
let playingSong:Song
// ...
class func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
// ...
return playingSong.lyric
}
}
you will also get the same type of error like :
instance member x cannot be used on type x.
It's because you assign your method with "class" keyword (which makes your method a type method) and using like :
Album.getCurrentlyPlayingSongLyric(duration: 5)
but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :
// ...
func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
// ...
return playingSong.lyric
}
// ...
Now you're free to go.
Django has support for this, check get_or_create
person, created = Person.objects.get_or_create(name='abc')
if created:
# A new person object created
else:
# person object already exists
The efficient way to do that is just to cast to a generic Map as follows:
Properties props = new Properties();
Map<String, String> map = (Map)props;
This will convert a Map<Object, Object>
to a raw Map, which is "ok" for the compiler (only warning). Once we have a raw Map
it will cast to Map<String, String>
which it also will be "ok" (another warning). You can ignore them with annotation @SuppressWarnings({ "unchecked", "rawtypes" })
This will work because in the JVM the object doesn't really have a generic type. Generic types are just a trick that verifies things at compile time.
If some key or value is not a String it will produce a ClassCastException
error. With current Properties
implementation this is very unlikely to happen, as long as you don't use the mutable call methods from the super Hashtable<Object,Object>
of Properties
.
So, if don't do nasty things with your Properties instance this is the way to go.
You can put up all your JS like this, so it doesn't execute before your HTML is ready
$(document).ready(function() {
// some code here
});
Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload
My Java is a little rusty, but let me see if I can point you in the right direction:
public class Converter {
public static Integer parseInt(String str) {
Integer n = null;
try {
n = new Integer(Integer.tryParse(str));
} catch (NumberFormatException ex) {
// leave n null, the string is invalid
}
return n;
}
}
If your return value is null
, you have a bad value. Otherwise, you have a valid Integer
.
You can even try below option:
<a href="javascript:show_more_menu();">More >>></a>
Using the spread operator like obj2 = { ...obj1 }
Will have same values but different references
IETF Open Standards RFC 5321 2.4. General Syntax Principles and Transaction Model
SMTP implementations MUST take care to preserve the case of mailbox local-parts. In particular, for some hosts, the user "smith" is different from the user "Smith".
Mailbox domains follow normal DNS rules and are hence not case sensitive
I feel I need to clarify one very important thing, for others (like my co-worker) who came across this thread and got the wrong information.
The answer given ("Try decimal(9,2) or decimal(10,2) or whatever.") is correct, but the reason ("increase the number of digits before the decimal") is wrong.
decimal(p,s) and numeric(p,s) both specify a Precision and a Scale. The "precision" is not the number of digits to the left of the decimal, but instead is the total precision of the number.
For example: decimal(2,1) covers 0.0 to 9.9, because the precision is 2 digits (00 to 99) and the scale is 1. decimal(4,1) covers 000.0 to 999.9 decimal(4,2) covers 00.00 to 99.99 decimal(4,3) covers 0.000 to 9.999
Not sure as cant see it in steps you mentioned.
Please try FLUSH PRIVILEGES [Reloads the privileges from the grant tables in the mysql database]:
flush privileges;
You need to execute it after GRANT
Hope this help!
The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:
Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
String apply(Object from){
return from.toString();
}
});
This take you away from using arrays,but I think this would be my prefered way.
Modify your estimated population function to take a growth argument of type float. Then you can call the growthRate function with your birthRate and deathRate and use the return value as the input for grown into estimatedPopulation.
float growthRate (float birthRate, float deathRate)
{
return ((birthRate) - (deathRate));
}
int estimatedPopulation (int currentPopulation, float growth)
{
return ((currentPopulation) + (currentPopulation) * (growth / 100);
}
// main.cpp
int currentPopulation = 100;
int births = 50;
int deaths = 25;
int population = estimatedPopulation(currentPopulation, growthRate(births, deaths));
I pulled most of this code from another post found here. I have modified it for my purposes. This works well for what I need. It may help with your situation.
$(window).load(function() {
function checkDate() {
var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var valDate = $(this).val();
if ( valDate.match( dateFormat )) {
$(this).css("border","1px solid #cccccc","color", "#555555", "font-weight", "normal");
var seperator1 = valDate.split('/');
var seperator2 = valDate.split('-');
if ( seperator1.length > 1 ) {
var splitdate = valDate.split('/');
} else if ( seperator2.length > 1 ) {
var splitdate = valDate.split('-');
}
var dd = parseInt(splitdate[0]);
var mm = parseInt(splitdate[1]);
var yy = parseInt(splitdate[2]);
var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];
if ( mm == 1 || mm > 2 ) {
if ( dd > ListofDays[mm - 1] ) {
$(this).val("");
$(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
alert('Invalid Date! You used a date which does not exist in the known calender.');
return false;
}
}
if ( mm == 2 ) {
var lyear = false;
if ( (!(yy % 4) && yy % 100) || !(yy % 400) ){
lyear = true;
}
if ( (lyear==false) && (dd>=29) ) {
$(this).val("");
$(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
alert('Invalid Date! You used Feb 29th for an invalid leap year');
return false;
}
if ( (lyear==true) && (dd>29) ) {
$(this).val("");
$(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
alert('Invalid Date! You used a date greater than Feb 29th in a valid leap year');
return false;
}
}
} else {
$(this).val("");
$(this).css("border","solid red 1px","color", "red", "font-weight", "bold");
alert('Date format was invalid! Please use format mm/dd/yyyy');
return false;
}
};
$('#from_date').change( checkDate );
$('#to_date').change( checkDate );
});
With postgres 9.3 use -> for object access. 4 example
seed.rb
se = SmartElement.new
se.data =
{
params:
[
{
type: 1,
code: 1,
value: 2012,
description: 'year of producction'
},
{
type: 1,
code: 2,
value: 30,
description: 'length'
}
]
}
se.save
rails c
SELECT data->'params'->0 as data FROM smart_elements;
returns
data
----------------------------------------------------------------------
{"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)
You can continue nesting
SELECT data->'params'->0->'type' as data FROM smart_elements;
return
data
------
1
(1 row)
Visual Studio Code, menu File → Preference → Settings → search for "trim":
@Component
and @Bean
do two quite different things, and shouldn't be confused.
@Component
(and @Service
and @Repository
) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.
@Bean
is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.
To answer your question...
would it have been possible to re-use the
@Component
annotation instead of introducing@Bean
annotation?
Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.
I'll make this pretty simple for you. When a transaction is initiated, it goes under processing stage until it reaches the terminal stage. Once it reaches the terminal stage, the transaction status is posted by the payment gateway to the callback url which generally the merchants use as a reference to show the success/failure page to the user. Hope this helps?
Very useful I had a slightly different scenario where I the request xml was itself the body of the POST and not a param. For that the following code can be used - Posting as an answer just in case anyone else having similar issue will benefit.
final HttpHeaders headers = new HttpHeaders();
headers.add("header1", "9998");
headers.add("username", "xxxxx");
headers.add("password", "xxxxx");
headers.add("header2", "yyyyyy");
headers.add("header3", "zzzzz");
headers.setContentType(MediaType.APPLICATION_XML);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
final HttpEntity<MyXmlbeansRequestDocument> httpEntity = new HttpEntity<MyXmlbeansRequestDocument>(
MyXmlbeansRequestDocument.Factory.parse(request), headers);
final ResponseEntity<MyXmlbeansResponseDocument> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity,MyXmlbeansResponseDocument.class);
log.info(responseEntity.getBody());
Check out my answer here: Git submodules: Specify a branch/tag
If you want, you can add the "branch = master" line into your .gitmodules file manually. Read the link to see what I mean.
EDIT: To track an existing submodule project at a branch, follow VonC's instructions here instead:
I know this has been answered already and it's an old question, but here's an extension method to do the same:
public static class DataExtensions
{
public static bool AreAllCellsEmpty(this DataRow row)
{
var itemArray = row.ItemArray;
if(itemArray==null)
return true;
return itemArray.All(x => string.IsNullOrWhiteSpace(x.ToString()));
}
}
And you use it like so:
if (dr.AreAllCellsEmpty())
// etc
Now you can use the Shared Project
Shared Project is a great way of sharing common code across multiple application We already have experienced with the Shared Project type in Visual Studio 2013 as part of Windows 8.1 Universal App Development, But with Visual Studio 2015, it is a Standalone New Project Template; and we can use it with other types of app like Console, Desktop, Phone, Store App etc.. This types of project is extremely helpful when we want to share a common code, logic as well as components across multiple applications with in single platform. This also allows accessing the platform-specific API ’s, assets etc.
for more info check this
Foreach before foreach: :)
reset($array);
while(list($key,$value) = each($array))
{
// we used this back in php3 :)
}