Go to your project folder\app\src\main\res\mipmap-mdpi\ic_launcher.png
You will see 5 mipmap folders. Replace the icon inside of the each mipmap folder, with the icon you want.
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
To run Minecraft with Forge (change C:\Users\nov11\AppData\Roaming/.minecraft/
to your MineCraft path :) [Just for people who are a bit too lazy to search on Google...]
Special thanks to ammarx for his TagAPI_3 (Github) which was used to create this command.
Arguments are separated line by line to make it easier to find useful ones.
java
-Xms1024M
-Xmx1024M
-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump
-Djava.library.path=C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/natives
-cp
C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraftforge/forge/1.12.2-14.23.5.2775/forge-1.12.2-14.23.5.2775.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/ow2/asm/asm-all/5.2/asm-all-5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/jline/jline/3.5.1/jline-3.5.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/config/1.2.1/config-1.2.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-actors-migration_2.11/1.1.0/scala-actors-migration_2.11-1.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-library_2.11/1.0.2/scala-continuations-library_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-plugin_2.11.1/1.0.2/scala-continuations-plugin_2.11.1-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-parser-combinators_2.11/1.0.1/scala-parser-combinators_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/java3d/vecmath/1.5.2/vecmath-1.5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/trove4j/trove4j/3.0.3/trove4j-3.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/maven/maven-artifact/3.5.3/maven-artifact-3.5.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/patchy/1.1/patchy-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/oshi-project/oshi-core/1.1/oshi-core-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/platform/3.4.0/platform-3.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/ibm/icu/icu4j-core-mojang/51.2/icu4j-core-mojang-51.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecjorbis/20101023/codecjorbis-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecwav/20101023/codecwav-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/libraryjavasound/20101123/libraryjavasound-20101123.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/librarylwjglopenal/20100824/librarylwjglopenal-20100824.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/soundsystem/20120107/soundsystem-20120107.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/io/netty/netty-all/4.1.9.Final/netty-all-4.1.9.Final.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/guava/guava/21.0/guava-21.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-lang3/3.5/commons-lang3-3.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-io/commons-io/2.5/commons-io-2.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-codec/commons-codec/1.10/commons-codec-1.10.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jinput/jinput/2.0.5/jinput-2.0.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jutils/jutils/1.0.0/jutils-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/authlib/1.5.25/authlib-1.5.25.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/realms/1.10.22/realms-1.10.22.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-compress/1.8.1/commons-compress-1.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpclient/4.3.3/httpclient-4.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpcore/4.3.2/httpcore-4.3.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/it/unimi/dsi/fastutil/7.1.0/fastutil-7.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-api/2.8.1/log4j-api-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-core/2.8.1/log4j-core-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.4-nightly-20150209/lwjgl_util-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.2-nightly-20140822/lwjgl-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.2-nightly-20140822/lwjgl_util-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/1.12.2.jar
net.minecraft.launchwrapper.Launch
--width
854
--height
480
--username
Ishikawa
--version
1.12.2-forge1.12.2-14.23.5.2775
--gameDir
C:\Users\nov11\AppData\Roaming/.minecraft
--assetsDir
C:\Users\nov11\AppData\Roaming/.minecraft/assets
--assetIndex
1.12
--uuid
N/A
--accessToken
aeef7bc935f9420eb6314dea7ad7e1e5
--userType
mojang
--tweakClass
net.minecraftforge.fml.common.launcher.FMLTweaker
--versionType
Forge
Just when other solutions don't work. accessToken and uuid can be acquired from Mojang Servers, check other anwsers for details.
Edit (26.11.2018): I've also created Launcher Framework in C# (.NET Framework 3.5), which you can also check to see how launcher should work Available Here
A cleaner way is to set connectionString in xml file, for example Web.Confing(WepApplication)
or App.Config(StandAloneApplication)
.
<connectionStrings>
<remove name="myConn"/>
<add name="myConn" connectionString="User ID=sa;Password=XXXXX;Initial Catalog=qualitaBorri;Data Source=PC_NAME\SQLEXPRESS;Connection Timeout=60"/>
</connectionStrings>
By code you can get connection in this way:
public static SqlConnection getConnection()
{
string conn = string.Empty;
conn = System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
SqlConnection aConnection = new SqlConnection(conn);
return aConnection;
}
You can set ConnectionTimeout
only you create a instance.
When instance is create you don't change this value.
As stated by the other answers, you are adding the same array of rows to each column. To create a multidimensional array you must use a loop
var NumColumns = 27
var NumRows = 52
var array = Array<Array<Double>>()
for column in 0..NumColumns {
array.append(Array(count:NumRows, repeatedValue:Double()))
}
Also you can do like this:
<select class="form-control postType" ng-model="selectedProd">
<option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>
where "selectedProd" will be selected product.
First you can get the rowid
of the selected row with respect of getGridParam
method and 'selrow' as the parameter and then you can use getCell to get the cell value from the corresponding column:
var myGrid = $('#list'),
selRowId = myGrid.jqGrid ('getGridParam', 'selrow'),
celValue = myGrid.jqGrid ('getCell', selRowId, 'columnName');
The 'columnName'
should be the same name which you use in the 'name'
property of the colModel
. If you need values from many column of the selected row you can use getRowData instead of getCell.
Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s
and a RESET
color to end the coloration.
#include <stdio.h>
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
int main() {
printf(RED "red\n" RESET);
printf(GRN "green\n" RESET);
printf(YEL "yellow\n" RESET);
printf(BLU "blue\n" RESET);
printf(MAG "magenta\n" RESET);
printf(CYN "cyan\n" RESET);
printf(WHT "white\n" RESET);
return 0;
}
This program gives the following output:
This way, it's easy to do something like:
printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");
This line produces the following output:
ianhanniballake is right. You can get all the functionality of Activity
from FragmentActivity
. In fact, FragmentActivity
has more functionality.
Using FragmentActivity
you can easily build tab and swap
format. For each tab you can use different Fragment
(Fragments
are reusable). So for any FragmentActivity
you can reuse the same Fragment
.
Still you can use Activity
for single pages like list down something and edit element of the list in next page.
Also remember to use Activity
if you are using android.app.Fragment
; use FragmentActivity
if you are using android.support.v4.app.Fragment
. Never attach a android.support.v4.app.Fragment
to an android.app.Activity
, as this will cause an exception to be thrown.
Hear it from the Horse's Mouth : APUE (Richard Stevens).
To the kernel, all open files are referred to by File Descriptors. A file descriptor is a non-negative number.
When we open an existing file or create a new file, the kernel returns a file descriptor to the process. The kernel maintains a table of all open file descriptors, which are in use. The allotment of file descriptors is generally sequential and they are allotted to the file as the next free file descriptor from the pool of free file descriptors. When we closes the file, the file descriptor gets freed and is available for further allotment.
See this image for more details :
When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write().
It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.
File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n
. For more information, go through 3rd chapter of APUE Book.
public static <T> List<T> toList(String json, Class<T> clazz) {
if (null == json) {
return null;
}
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<T>(){}.getType());
}
sample call:
List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
I know this is an old ticket but I just thought I'd share this:
I found this code which provides a solution. Not sure if it works on all versions of MSSQL; I have MSSQL 2016.
declare @value as nvarchar(50) = 23
select REPLACE(STR(CAST(@value AS INT) + 1,4), SPACE(1), '0') as Leadingzero
This returns "0023".
The 4 in the STR function is the total length, including the value. For example, 4, 23 and 123 will all have 4 in STR and the correct amount of zeros will be added. You can increase or decrease it. No need to get the length on the 23.
Edit: I see it's the same as the post by @Anon.
In bash, contrary to [
, [[
prevents word splitting of variable values.
It doesn't. It makes 0 <= r < 1
, but your original is 0 <= r <= 1
.
Note that this can lead to undefined behavior if RAND_MAX + 1
overflows.
Take a look in error file for your mysql database. According to Bug #26305 my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)
"pull-left" is what you need, it looks like you are using Bootstrap 2, I am not sure if that is available, consider bootstrap 3, unless ofcourse it is a huge rework! ... for Bootstrap 3 but you need to make sure you have 12 columns in each row as well, otherwise you will have issues.
I know this question is for Java 8, but with Java 9 you could use:
public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate)
.collect(Collectors.toList());
}
With twitter bootstrap :
<p class="pull-left">Left aligned text.</p>
<p class="pull-right">Right aligned text.</p>
<p class="text-center">Center aligned text.</p>
First you use startActivityForResult()
with parameters in first Activity
and if you want to send data from second Activity
to first Activity
then pass value using Intent
with setResult()
method and get that data inside onActivityResult()
method in first Activity
.
To make sed
catch from stdin , instead of from a file, you should use -e
.
Like this:
curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk 'BEGIN{FS=":"} {print $4}'
It might be better to use communicate
:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]
"Better", because of this warning:
Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
dynamic_cast should be what you are looking for.
EDIT:
DerivedType m_derivedType = m_baseType; // gives same error
The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.
DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error
You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.
Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):
DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);
If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.
Hope this helps!
For Visual Studio 2017
Find "References" in Solution explorer
Right click "References"
Choose "Add Reference..."
Find "Presentation.Core" list and check checkbox
Click OK
I know it's an old thread, but I landed here several times via Google and think no given answer is really satisfying yet. Try using one of the following functions:
EDIT: As I'm getting some likes on this old thread, I wanna share an updated solution as well (basically putting my two previous functions together and automatically deciding whether it's a bar or hbar plot):
def label_bars(ax, bars, text_format, **kwargs):
"""
Attaches a label on every bar of a regular or horizontal bar chart
"""
ys = [bar.get_y() for bar in bars]
y_is_constant = all(y == ys[0] for y in ys) # -> regular bar chart, since all all bars start on the same y level (0)
if y_is_constant:
_label_bar(ax, bars, text_format, **kwargs)
else:
_label_barh(ax, bars, text_format, **kwargs)
def _label_bar(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
"""
max_y_value = ax.get_ylim()[1]
inside_distance = max_y_value * 0.05
outside_distance = max_y_value * 0.01
for bar in bars:
text = text_format.format(bar.get_height())
text_x = bar.get_x() + bar.get_width() / 2
is_inside = bar.get_height() >= max_y_value * 0.15
if is_inside:
color = "white"
text_y = bar.get_height() - inside_distance
else:
color = "black"
text_y = bar.get_height() + outside_distance
ax.text(text_x, text_y, text, ha='center', va='bottom', color=color, **kwargs)
def _label_barh(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
Note: label always outside. otherwise it's too hard to control as numbers can be very long
"""
max_x_value = ax.get_xlim()[1]
distance = max_x_value * 0.0025
for bar in bars:
text = text_format.format(bar.get_width())
text_x = bar.get_width() + distance
text_y = bar.get_y() + bar.get_height() / 2
ax.text(text_x, text_y, text, va='center', **kwargs)
Now you can use them for regular bar plots:
fig, ax = plt.subplots((5, 5))
bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, bars, value_format)
or for horizontal bar plots:
fig, ax = plt.subplots((5, 5))
horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, horizontal_bars, value_format)
Path.GetFullPath(fileUpload.PostedFile.FileName);
Sorry this 'll get your program file directory + your file name.
We can also use host machine environment variable using -e flag and $ :
docker run -it -e MG_HOST=$MG_HOST -e MG_USER=$MG_USER -e MG_PASS=$MG_PASS -e MG_AUTH=$MG_AUTH -e MG_DB=$MG_DB -t image_tag_name_and_version
By using this method, you can set the environment variable automatically with your given name. In my case(MG_HOST ,MG_USER)
If you are using python you can access these environment variable inside docker by
import os
host,username,password,auth,database=os.environ.get('MG_HOST'),os.environ.get('MG_USER'),os.environ.get('MG_PASS'),os.environ.get('MG_AUTH'),os.environ.get('MG_DB')
I had almost precisely the same error, and was able to completely fix it simply by running:
gem install bundler
It's possible your bundler installation is corrupt or missing - that's what happened in my case. Note that if the above fails you can try:
sudo gem install bundler
...but generally you can do it without sudo.
The ultimate question... Is WebKit supported by IE?
Kind of. Check out Chrome Frame, it's a plugin for Internet Explorer that makes it use the Webkit engine. The only quirk is that you have to persuade your visitors to install the plugin.
Chrome Frame is no longer maintained or supported…
Instead of replacing everything with innerHTML try:
document.body.appendChild(myExtraNode);
import traceback
traceback.print_exc()
When doing this inside an except ...:
block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.
Instead of using width
(which is a suggestion when using flexbox), you could use flex: 0 0 230px;
which means:
0
= don't grow (shorthand for flex-grow
)0
= don't shrink (shorthand for flex-shrink
)230px
= start at 230px
(shorthand for flex-basis
)which means: always be 230px
.
See fiddle, thanks @TylerH
Oh, and you don't need the justify-content
and align-items
here.
img {
max-width: 100%;
}
#container {
display: flex;
x-justify-content: space-around;
x-align-items: stretch;
max-width: 1200px;
}
.column.left {
width: 230px;
flex: 0 0 230px;
}
.column.right {
width: 230px;
flex: 0 0 230px;
border-left: 1px solid #eee;
}
.column.center {
border-left: 1px solid #eee;
}
Use LINQ and add the condition on the "selected" as a question mark condition.
var listSiteId = (from site in db.GetSiteId().ToList()
select new SelectListItem
{
Value = site.SITEID,
Text = site.NAME,
Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
}).ToList();
ViewBag.SiteId = listSiteId;
Request and response.
To understand the req
, try out console.log(req);
.
I faced the same problem and search everywhere for a solution, at last, I fount something which works for me for every browsers.
html {
height: 0;
}
use this css or Instead of css you can have this javascript
$("html").height(0);
Hope this will work for you as well.
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
@AbhinavGupta and @Steef suggested using update()
, which I found very helpful for processing large argument lists:
args.update(kwargs)
What if we want to check that the user hasn't passed any spurious/unsupported arguments? @VinaySajip pointed out that pop()
can be used to iteratively process the list of arguments. Then, any leftover arguments are spurious. Nice.
Here's another possible way to do this, which keeps the simple syntax of using update()
:
# kwargs = dictionary of user-supplied arguments
# args = dictionary containing default arguments
# Check that user hasn't given spurious arguments
unknown_args = user_args.keys() - default_args.keys()
if unknown_args:
raise TypeError('Unknown arguments: {}'.format(unknown_args))
# Update args to contain user-supplied arguments
args.update(kwargs)
unknown_args
is a set
containing the names of arguments that don't occur in the defaults.
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
def bubbleSort(a):
def swap(x, y):
temp = a[x]
a[x] = a[y]
a[y] = temp
#outer loop
for j in range(len(a)):
#slicing to the center, inner loop, python style
for i in range(j, len(a) - j):
#find the min index and swap
if a[i] < a[j]:
swap(j, i)
#find the max index and swap
if a[i] > a[len(a) - j - 1]:
swap(len(a) - j - 1, i)
return a
SELECT * FROM
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser
Instead of remotely putting popper js from CDN you can directly install it in your angular project.
Try this.
npm install popper.js --save
This query installs an updated version of popper.js Don't mention any version there, it will work for you.
I personally use the humanize
library for this:
>>> import datetime
>>> humanize.naturalday(datetime.datetime.now())
'today'
>>> humanize.naturalday(datetime.datetime.now() - datetime.timedelta(days=1))
'yesterday'
>>> humanize.naturalday(datetime.date(2007, 6, 5))
'Jun 05'
>>> humanize.naturaldate(datetime.date(2007, 6, 5))
'Jun 05 2007'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1))
'a second ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600))
'an hour ago'
Of course, it doesn't give you exactly the answer you were looking for (which is, indeed, str(timeA - timeB)
, but I have found that once you go beyond a few hours, the display becomes quickly unreadable. humanize
has support for much larger values that are human-readable, and is also well localized.
It's inspired by Django's contrib.humanize
module, apparently, so since you are using Django, you should probably use that.
Keep it simple!
var classes = $(this).parent('div').attr('class');
Create a constant with absolute path to the root by using define
in ShowInfo.php
:
define('ROOTPATH', __DIR__);
Or PHP <= 5.3
define('ROOTPATH', dirname(__FILE__));
Now use it:
if (file_exists(ROOTPATH.'/Texts/MyInfo.txt')) {
// ...
}
Or use the DOCUMENT_ROOT
defined in $_SERVER
:
if (file_exists($_SERVER['DOCUMENT_ROOT'].'/Texts/MyInfo.txt')) {
// ...
}
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
FileOutputStream f = new FileOutputStream(file);
...
I came with a pretty simple solution. I'm not sure whether it is the correct way to do it but it works in a practical sense. Let's directly watch what we want to be rendered. For example in a directive that includes some ng-repeat
s, I would watch out for the length of text (you may have other things!) of paragraphs or the whole html. The directive will be like this:
.directive('myDirective', [function () {
'use strict';
return {
link: function (scope, element, attrs) {
scope.$watch(function(){
var whole_p_length = 0;
var ps = element.find('p');
for (var i=0;i<ps.length;i++){
if (ps[i].innerHTML == undefined){
continue
}
whole_p_length+= ps[i].innerHTML.length;
}
//it could be this too: whole_p_length = element[0].innerHTML.length; but my test showed that the above method is a bit faster
console.log(whole_p_length);
return whole_p_length;
}, function (value) {
//Code you want to be run after rendering changes
});
}
}]);
NOTE that the code actually runs after rendering changes rather complete rendering. But I guess in most cases you can handle the situations whenever rendering changes happen. Also you could think of comparing this p
s length (or any other measure) with your model if you want to run your code only once after rendering completed. I appreciate any thoughts/comments on this.
My issue was not sending the response back, so it was hanging. If you are using express make sure that res.send(data), res.json(data) or whatever the api method you wanna use is executed for the route you are testing.
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.
To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I
Here is an example with Immediate Window:
int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}
add breakpoint
call commands
Xcode Workspace vs Project
- What is the difference between the two of them?
Workspace
is a set of projects
- What are they responsible for?
Workspace
is responsible for dependencies between projects.
Project
is responsible for the source code.
- Which one of them should I work with when I'm developing my Apps in team/alone?
You choice should depends on a type of your project. For example if your project relies on CocoaPods dependency manager it creates a workspace.
- Is there anything else I should be aware of in matter of these two files?
A competitor of workspace is cross-project references
[About]
You can get the name of the user in ASP.NET MVC4 like this:
System.Web.HttpContext.Current.User.Identity.Name
I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.
Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.
I found this related question on the topic, but if you want direct links, here they are:
I'm surprised node.js doesn't come with a shell, but I guess it's really more like an epoll/selector-based callback/event-oriented webserver, so perhaps it doesn't need the full JS feature set, but I'm not too familiar with its inner workings.
Since you seem interested in node.js and since it's based on V8, it might be best to follow those instructions on getting a V8 environment set up so you can have a consistent basis for your JavaScript programming (I should hope JSC and V8 are mostly the same, but I'm not sure).
I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
transform(array: Array<Object>, filter: Object): any {
let notAllKeysUndefined = false;
let newArray = [];
if(array.length > 0) {
for (let k in filter){
if (filter.hasOwnProperty(k)) {
if(filter[k] != undefined && filter[k] != '') {
for (let i = 0; i < array.length; i++) {
let filterRule = filter[k];
if(typeof filterRule === 'object') {
for(let fkey in filterRule) {
if (filter[k].hasOwnProperty(fkey)) {
if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
newArray.push(array[i]);
}
notAllKeysUndefined = true;
}
}
}
} else {
if(this.shouldPushInArray(array[i][k], filter[k])) {
newArray.push(array[i]);
}
notAllKeysUndefined = true;
}
}
}
}
}
if(notAllKeysUndefined) {
return newArray;
}
}
return array;
}
private shouldPushInArray(item, filter) {
if(typeof filter !== 'string') {
item = item.toString();
filter = filter.toString();
}
// Filter main logic
item = item.toLowerCase();
filter = filter.toLowerCase();
if(item.indexOf(filter) !== -1) {
return true;
}
return false;
}
}
Five years later, when I Google "how to create a kernel density plot using python", this thread still shows up at the top!
Today, a much easier way to do this is to use seaborn, a package that provides many convenient plotting functions and good style management.
import numpy as np
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.set_style('whitegrid')
sns.kdeplot(np.array(data), bw=0.5)
There is extensive paramiko API documentation you can find at: http://docs.paramiko.org/en/stable/index.html
I use the following method to execute commands on a password protected client:
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
if session.recv_ready():
stdout_data.append(session.recv(nbytes))
if session.recv_stderr_ready():
stderr_data.append(session.recv_stderr(nbytes))
if session.exit_status_ready():
break
print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)
session.close()
client.close()
call concat
and pass param axis=1
to concatenate column-wise:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
There is a useful guide to the various methods of merging, joining and concatenating online.
For example, as you have no clashing columns you can merge
and use the indices as they have the same number of rows:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
And for the same reasons as above a simple join
works too:
In [7]:
df_a.join(df_b)
Out[7]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
You can create a directory with PHP using the mkdir() function.
mkdir("/path/to/my/dir", 0700);
You can use fopen() to create a file inside that directory with the use of the mode w
.
fopen('myfile.txt', 'w');
w : Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
[k for (k, v) in i.iteritems() if v == 0]
Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0}
is perfectly legal.
If you want ordering you either need to use a list or a OrderedDict instance instead:
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
easy if its pdf or img use
return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));
public static string NumberToWords(int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + NumberToWords(Math.Abs(number));
string words = "";
if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " hundred ";
number %= 100;
}
if (number > 0)
{
if (words != "")
words += "and ";
var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}
return words;
}
I'll explain the main use cases of implicits below, but for more detail see the relevant chapter of Programming in Scala.
Implicit parameters
The final parameter list on a method can be marked implicit
, which means the values will be taken from the context in which they are called. If there is no implicit value of the right type in scope, it will not compile. Since the implicit value must resolve to a single value and to avoid clashes, it's a good idea to make the type specific to its purpose, e.g. don't require your methods to find an implicit Int
!
example:
// probably in a library
class Prefixer(val prefix: String)
def addPrefix(s: String)(implicit p: Prefixer) = p.prefix + s
// then probably in your application
implicit val myImplicitPrefixer = new Prefixer("***")
addPrefix("abc") // returns "***abc"
Implicit conversions
When the compiler finds an expression of the wrong type for the context, it will look for an implicit Function
value of a type that will allow it to typecheck. So if an A
is required and it finds a B
, it will look for an implicit value of type B => A
in scope (it also checks some other places like in the B
and A
companion objects, if they exist). Since def
s can be "eta-expanded" into Function
objects, an implicit def xyz(arg: B): A
will do as well.
So the difference between your methods is that the one marked implicit
will be inserted for you by the compiler when a Double
is found but an Int
is required.
implicit def doubleToInt(d: Double) = d.toInt
val x: Int = 42.0
will work the same as
def doubleToInt(d: Double) = d.toInt
val x: Int = doubleToInt(42.0)
In the second we've inserted the conversion manually; in the first the compiler did the same automatically. The conversion is required because of the type annotation on the left hand side.
Regarding your first snippet from Play:
Actions are explained on this page from the Play documentation (see also API docs). You are using
apply(block: (Request[AnyContent]) ? Result): Action[AnyContent]
on the Action
object (which is the companion to the trait of the same name).
So we need to supply a Function as the argument, which can be written as a literal in the form
request => ...
In a function literal, the part before the =>
is a value declaration, and can be marked implicit
if you want, just like in any other val
declaration. Here, request
doesn't have to be marked implicit
for this to type check, but by doing so it will be available as an implicit value for any methods that might need it within the function (and of course, it can be used explicitly as well). In this particular case, this has been done because the bindFromRequest
method on the Form class requires an implicit Request
argument.
Simple 1 liner Vanilla Javascript code :
const priorByDays = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
For example:
days = 7
Assume current date = Fri Sep 18 2020 01:33:26 GMT+0530
The result would be : Fri Sep 11 2020 01:34:03 GMT+0530
The beauty of this is you can manipulate it to get result in desired type
timestamp : Date.now() - days * 24 * 60 * 60 * 1000
ISOString: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
McGarnagle has a great answer, and you'll want to be accepting his, but I thought I'd mention (since you asked) how databinding works.
It's generally implemented by firing events whenever a change is made to the data, which then causes listeners (e.g. the UI) to be updated.
Two-way binding works by doing this twice, with a bit of care taken to ensure that you don't wind up stuck in an event loop (where the update from the event causes another event to be fired).
I was gonna put this in a comment, but it was getting pretty long...
This change worked for me:
// The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
// CGImageRef imgRef = [image CGImage];
// CGFloat width = CGImageGetWidth(imgRef);
// CGFloat height = CGImageGetHeight(imgRef);
//
// This returns the actual width and height of the photo (and hence solves the problem
CGFloat width = image.size.width;
CGFloat height = image.size.height;
CGRect bounds = CGRectMake(0, 0, width, height);
You should see the error log. By default, its location is in /var/log/nginx/error.log
In my case, 502 get way because of:
GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:28 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
When we know exactly what is wrong, then fix it. For these error, just modify the buffer:
fastcgi_buffers 16 512k;
fastcgi_buffer_size 512k;
You can quickly serve static content in JAVA Spring-boot App via thymeleaf
(ref: source)
I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot'
and the necessary buildscript
Then go ahead and ADD thymeleaf to your build.gradle
==>
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Lets assume you have added home.html at src/main/resources
To serve this file, you will need to create a controller.
package com.ajinkya.th.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomePageController {
@RequestMapping("/")
public String homePage() {
return "home";
}
}
Thats it ! Now restart your gradle server. ./gradlew bootRun
This might help
import binascii
x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')
print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374
x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'
x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test
This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii')
.
Simply Use Jquery/Javascript trick to add an empty div:
if($('.exposegrid').length%3==2){
$(".exposegrid").append('<div class="exposetab"></div>');
}
One alternative would be to use a getter/setter methods.
For instance, if you only care about reading the calculated value:
var book = {}
Object.defineProperties(book,{
key1: { value: "it", enumerable: true },
key2: {
enumerable: true,
get: function(){
return this.key1 + " works!";
}
}
});
console.log(book.key2); //prints "it works!"
The above code, though, won't let you define another value for key2.
So, the things become a bit more complicated if you would like to also redefine the value of key2. It will always be a calculated value. Most likely that's what you want.
However, if you would like to be able to redefine the value of key2, then you will need a place to cache its value independently of the calculation.
Somewhat like this:
var book = { _key2: " works!" }
Object.defineProperties(book,{
key1: { value: "it", enumerable: true},
_key2: { enumerable: false},
key2: {
enumerable: true,
get: function(){
return this.key1 + this._key2;
},
set: function(newValue){
this._key2 = newValue;
}
}
});
console.log(book.key2); //it works!
book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!
for(var key in book){
//prints both key1 and key2, but not _key2
console.log(key + ":" + book[key]);
}
Another interesting alternative is to use a self-initializing object:
var obj = ({
x: "it",
init: function(){
this.y = this.x + " works!";
return this;
}
}).init();
console.log(obj.y); //it works!
You can override the mro of a class with a metaclass
>>> class A(object):
... def a_method(self):
... print("A")
...
>>> class B(object):
... def b_method(self):
... print("B")
...
>>> class MROMagicMeta(type):
... def mro(cls):
... return (cls, B, object)
...
>>> class C(A, metaclass=MROMagicMeta):
... def c_method(self):
... print("C")
...
>>> cls = C()
>>> cls.c_method()
C
>>> cls.a_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'a_method'
>>> cls.b_method()
B
>>> type(cls).__bases__
(<class '__main__.A'>,)
>>> type(cls).__mro__
(<class '__main__.C'>, <class '__main__.B'>, <class 'object'>)
It's probably hidden for a good reason. :)
I will include one important use case of pointer. When you are storing some object in the base class, but it could be polymorphic.
Class Base1 {
};
Class Derived1 : public Base1 {
};
Class Base2 {
Base *bObj;
virtual void createMemerObects() = 0;
};
Class Derived2 {
virtual void createMemerObects() {
bObj = new Derived1();
}
};
So in this case you can't declare bObj as an direct object, you have to have pointer.
you can use the like query for comparing the respective string with table vales.
select column name from table_name where column name like 'respective comparing value';
Using a text editor, check for ^M
(control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.
sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt
You need a little statistical knowledge to see this. R squared between two vectors is just the square of their correlation. So you can define you function as:
rsq <- function (x, y) cor(x, y) ^ 2
Sandipan's answer will return you exactly the same result (see the following proof), but as it stands it appears more readable (due to the evident $r.squared
).
Basically we fit a linear regression of y
over x
, and compute the ratio of regression sum of squares to total sum of squares.
lemma 1: a regression y ~ x
is equivalent to y - mean(y) ~ x - mean(x)
lemma 2: beta = cov(x, y) / var(x)
lemma 3: R.square = cor(x, y) ^ 2
R squared between two arbitrary vectors x
and y
(of the same length) is just a goodness measure of their linear relationship. Think twice!! R squared between x + a
and y + b
are identical for any constant shift a
and b
. So it is a weak or even useless measure on "goodness of prediction". Use MSE or RMSE instead:
I agree with 42-'s comment:
The R squared is reported by summary functions associated with regression functions. But only when such an estimate is statistically justified.
R squared can be a (but not the best) measure of "goodness of fit". But there is no justification that it can measure the goodness of out-of-sample prediction. If you split your data into training and testing parts and fit a regression model on the training one, you can get a valid R squared value on training part, but you can't legitimately compute an R squared on the test part. Some people did this, but I don't agree with it.
Here is very extreme example:
preds <- 1:4/4
actual <- 1:4
The R squared between those two vectors is 1. Yes of course, one is just a linear rescaling of the other so they have a perfect linear relationship. But, do you really think that the preds
is a good prediction on actual
??
Thanks for your comments 1, 2 and your answer of details.
You probably misunderstood the procedure. Given two vectors x
and y
, we first fit a regression line y ~ x
then compute regression sum of squares and total sum of squares. It looks like you skip this regression step and go straight to the sum of square computation. That is false, since the partition of sum of squares does not hold and you can't compute R squared in a consistent way.
As you demonstrated, this is just one way for computing R squared:
preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2) ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2) ## total sum of squares
rsq <- 1 - rss/tss
#[1] 0.25
But there is another:
regss <- sum((preds - mean(preds)) ^ 2) ## regression sum of squares
regss / tss
#[1] 0.75
Also, your formula can give a negative value (the proper value should be 1 as mentioned above in the Warning section).
preds <- 1:4 / 4
actual <- 1:4
rss <- sum((preds - actual) ^ 2) ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2) ## total sum of squares
rsq <- 1 - rss/tss
#[1] -2.375
I had never expected that this answer could eventually be so long when I posted my initial answer 2 years ago. However, given the high views of this thread, I feel obliged to add more statistical details and discussions. I don't want to mislead people that just because they can compute an R squared so easily, they can use R squared everywhere.
Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> **$dte = Get-Date**
PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
PS C:\Windows\system32> **$PastDueDate**
Sunday, March 1, 2020 12:00:00 AM
PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
PS C:\Windows\system32> **$NewDateFormat 03012020**
There're few additional methods available as well e.g.: $dte.AddDays(-45).Day
See my comment on the chosen answer. Other solutions that limit to the ASCII table or use the actual character literals completely ignore Unicode and the several hundred other characters there that have case.
This code will set the caseGroup variable to:
0 for Without Case
var caseGroup = (character.toLowerCase() == character.toUpperCase() ? 0 : (character == character.toUpperCase() ? 1 : -1));
You could bake that into something like this...
function determineCase(character) {
return (character.toLowerCase() == character.toUpperCase() ? 0 : (character == character.toUpperCase() ? 1 : -1));
}
function isUpper(character) {
return determineCase(character) == 1;
}
function isLower(character) {
return determineCase(character) == -1;
}
function hasCase(character) {
return determineCase(character) != 0;
}
My Xcode Version 6.1.1 (6A2008a)
In playground, test like this:
// I'm in East Timezone 8
let x = NSDate() //Output:"Dec 29, 2014, 11:37 AM"
let y = NSDate.init() //Output:"Dec 29, 2014, 11:37 AM"
println(x) //Output:"2014-12-29 03:37:24 +0000"
// seconds since 2001
x.hash //Output:441,517,044
x.hashValue //Output:441,517,044
x.timeIntervalSinceReferenceDate //Output:441,517,044.875367
// seconds since 1970
x.timeIntervalSince1970 //Output:1,419,824,244.87537
Best event for change title onCreateOptionsMenu
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.general, container,
setHasOptionsMenu(true); // <-Add this line
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If use specific menu
menu.clear();
inflater.inflate(R.menu.path_list_menu, menu);
// If use specific menu
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Fragment");
super.onCreateOptionsMenu(menu, inflater);
}
The RecyclerView
takes care of adding, removing, and re-ordering animations!
This simple AndroidStudio project features a RecyclerView
. take a look at the commits:
You need two columns of the same type, one on each table, to JOIN on. Whether they're primary and foreign keys or not doesn't matter.
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2)
{
if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)
return false;
for ( int i = 0; i < tbl1.Rows.Count; i++)
{
for ( int c = 0; c < tbl1.Columns.Count; c++)
{
if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c]))
return false;
}
}
return true;
}
Then solution will be the following.
HTML
<div class="parent">
<div class="child"></div>
</div>
CSS
.parent{
width: 960px;
margin: auto;
height: 100vh
}
.child{
position: absolute;
width: 100vw
}
Java is 'Big-endian' as noted above. That means that the MSB of an int is on the left if you examine memory (on an Intel CPU at least). The sign bit is also in the MSB for all Java integer types.
Reading a 4 byte unsigned integer from a binary file stored by a 'Little-endian' system takes a bit of adaptation in Java. DataInputStream's readInt() expects Big-endian format.
Here's an example that reads a four byte unsigned value (as displayed by HexEdit as 01 00 00 00) into an integer with a value of 1:
// Declare an array of 4 shorts to hold the four unsigned bytes
short[] tempShort = new short[4];
for (int b = 0; b < 4; b++) {
tempShort[b] = (short)dIStream.readUnsignedByte();
}
int curVal = convToInt(tempShort);
// Pass an array of four shorts which convert from LSB first
public int convToInt(short[] sb)
{
int answer = sb[0];
answer += sb[1] << 8;
answer += sb[2] << 16;
answer += sb[3] << 24;
return answer;
}
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
There are may ways of getting day, month and year in java.
You may use any-
Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);
Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1 = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);
LocalDateTime ldt1 = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy3 = ldt1.format(format1);
System.out.println("Formatted Date 3: " + mmddyyyy3);
LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);
LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy5 = ldt3.format(format2);
System.out.println("Formatted Date 5: " + mmddyyyy5);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3 = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);
Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4 = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);
Date date4 = new Date();
int day5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);
Date date5 = new Date();
int day6 = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6 = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);
System.out.println("Formatted Date 9: " + mmddyyyy9);
If you set a default schema for your DB Connection then Select will run in readonly mode until you set explicitly your schema
USE mydb;
SELECT * FROM mytable
this will also run in edit mode:
SELECT * FROM mydb.mytable
(MySql 5.2.42 / MacOsX)
I hope this helps.
If you've already installed Android Studio --
Add the following lines to the end of ~/.bashrc
or ~/.zshrc
(if using Oh My ZSH):
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Restart Terminal and you're good to go.
ID's have the functionality to work as links to particular sections within a webpage. a keyword after # tag will take you to a particular section of the webpage. e.g "http://exampleurl.com#chapter5" in the address bar will take you there when you have a "section5" id wrapped around the chapter 5 section of the page.
The value of PYTHONHASHSEED might be used to initialize the hash values.
Try:
PYTHONHASHSEED python -c 'print(hash('http://stackoverflow.com'))'
Non of these worked for me... when I converted the timestamp back it's 4 years off.
This worked perfectly: =(A2-DATE(1970,1,1))*86400
Credit goes to: Filip Czaja http://fczaja.blogspot.ca
Original Post: http://fczaja.blogspot.ca/2011/06/convert-excel-date-into-timestamp.html
I haven't personally checked, but hadoop-yarn-container-virtual-memory-understanding-and-solving-container-is-running-beyond-virtual-memory-limits-errors sounds very reasonable
I solved the issue by changing yarn.nodemanager.vmem-pmem-ratio
to a higher value , and I would agree that:
Another less recommended solution is to disable the virtual memory check by setting yarn.nodemanager.vmem-check-enabled to false.
Just drag images to the iPhone simulator.
I prefer using Hamcrest because it gives much better output in case of a failure
Assert.assertThat(listUnderTest,
IsIterableContainingInOrder.contains(expectedList.toArray()));
Instead of reporting
expected true, got false
it will report
expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."
IsIterableContainingInOrder.contain
According to the Javadoc:
Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items
So the listUnderTest
must have the same number of elements and each element must match the expected values in order.
Object.entries()
function:
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3"_x000D_
};_x000D_
_x000D_
for (var i in Object.entries(p)){_x000D_
var key = Object.entries(p)[i][0];_x000D_
var value = Object.entries(p)[i][1];_x000D_
console.log('key['+i+']='+key+' '+'value['+i+']='+value);_x000D_
}
_x000D_
None of that solved my problem. but what I did was if click on the pom.xml, there is a tab at the bottom named dependencies. in this tab it is split into 2 section, one called dependencies and one called dependency management. select every thing in the dependency section and click add to be under the dependency management control. close and reopen your project.
Use TimeSpan.Parse
to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx
You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:
body{
min-width:1000px; /* Suppose you want minimum width of 1000px */
width: auto !important; /* Firefox will set width as auto */
width:1000px; /* As IE6 ignores !important it will set width as 1000px; */
}
Or:
body{
min-width:1000px; // Suppose you want minimum width of 1000px
_width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}
For this and other kind of client detections I suggest this js library: http://hictech.github.io/navJs/tester/index.html
For your specific answer use:
navJS.isIOS() || navJS.isAndroid()
I believe this is what you are looking for:
Indexers (C# Programming Guide)
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get => arr[i];
set => arr[i] = value;
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection =
new SampleCollection<string>();
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.
Then i use COM Dataport Emulator to recieve from COM4.
Then i open COM3 with the app im developping (c#) and send data to COM3.
The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).
So with this 2 great programs i managed to emulate Serial RS-232 comunication.
Hope it helps.
Both programs are free!!!!!
First of all you can look here for a list of the various operations the individual iterator types need to support.
Next, when you have made your iterator class you need to either specialize std::iterator_traits
for it and provide some necessary typedef
s (like iterator_category
or value_type
) or alternatively derive it from std::iterator
, which defines the needed typedef
s for you and can therefore be used with the default std::iterator_traits
.
disclaimer: I know some people don't like cplusplus.com
that much, but they provide some really useful information on this.
I don't think this is possible (at least not without using some internals). And I don't think you would gain much by optimizing this.
Again, all of the answers above missed the point badly. The OP wanted to convert a pointer value to a int value, instead, most the answers, one way or the other, tried to wrongly convert the content of arg points to to a int value. And, most of these will not even work on gcc4.
The correct answer is, if one does not mind losing data precision,
int x = *((int*)(&arg));
This works on GCC4.
The best way is, if one can, do not do such casting, instead, if the same memory address has to be shared for pointer and int (e.g. for saving RAM), use union, and make sure, if the mem address is treated as an int only if you know it was last set as an int.
To match either / or end of content, use (/|\z)
This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).
To put that with an updated version of what you had:
/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)
Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+?
) rather than matching anything and everything ( .*
)
With C++11, you can write:
#include <string> // to use std::string, std::to_string() and "+" operator acting on strings
int i = 4;
std::string text = "Player ";
text += std::to_string(i);
There is likely whitespace outside of your php tags.
First register a receiver in your manifest.xml file:
<receiver android:name="com.mileagelog.service.Broadcast_PowerUp" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
and then write a broadcast for this receiver like:
public class Broadcast_PowerUp extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "Service_PowerUp Started",
Toast.LENGTH_LONG).show();
} else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
Toast.makeText(context, "Service_PowerUp Stoped", Toast.LENGTH_LONG)
.show();
}
}
}
select2
has the placeholder
parameter. Use that one
$("#state").select2({
placeholder: "Choose a Country"
});
I had the same problem as you do and I could solve it by following @CarlosRojas instructions with a little difference. Instead of create a new firewall rule I edited the default-allow-internal
one to accept traffic from anywhere since creating new rules didn't make any difference.
If its just about detecting whether or not you're dealing with an Object
, I could think of
Object.getPrototypeOf( obj ) === Object.prototype
However, this would probably fail for non-object primitive values. Actually there is nothing wrong with invoking .toString()
to retreive the [[cclass]] property. You can even create a nice syntax like
var type = Function.prototype.call.bind( Object.prototype.toString );
and then use it like
if( type( obj ) === '[object Object]' ) { }
It might not be the fastest operation but I don't think the performance leak there is too big.
Try to have the function body before the function call in your JavaScript file.
The answers here do an excellent job in defining both monoids and monads, however, they still don't seem to answer the question:
And on a less important note, is this true and if so could you give an explanation (hopefully one that can be understood by someone who doesn't have much Haskell experience)?
The crux of the matter that is missing here, is the different notion of "monoid", the so-called categorification more precisely -- the one of monoid in a monoidal category. Sadly Mac Lane's book itself makes it very confusing:
All told, a monad in
X
is just a monoid in the category of endofunctors ofX
, with product×
replaced by composition of endofunctors and unit set by the identity endofunctor.
Why is this confusing? Because it does not define what is "monoid in the category of endofunctors" of X
. Instead, this sentence suggests taking a monoid inside the set of all endofunctors together with the functor composition as binary operation and the identity functor as a monoidal unit. Which works perfectly fine and turns into a monoid any subset of endofunctors that contains the identity functor and is closed under functor composition.
Yet this is not the correct interpretation, which the book fails to make clear at that stage. A Monad f
is a fixed endofunctor, not a subset of endofunctors closed under composition. A common construction is to use f
to generate a monoid by taking the set of all k
-fold compositions f^k = f(f(...))
of f
with itself, including k=0
that corresponds to the identity f^0 = id
. And now the set S
of all these powers for all k>=0
is indeed a monoid "with product × replaced by composition of endofunctors and unit set by the identity endofunctor".
And yet:
S
can be defined for any functor f
or even literally for any self-map of X
. It is the monoid generated by f
.S
given by the functor composition and the identity functor has nothing do with f
being or not being a monad.And to make things more confusing, the definition of "monoid in monoidal category" comes later in the book as you can see from the table of contents. And yet understanding this notion is absolutely critical to understanding the connection with monads.
Going to Chapter VII on Monoids (which comes later than Chapter VI on Monads), we find the definition of the so-called strict monoidal category as triple (B, *, e)
, where B
is a category, *: B x B-> B
a bifunctor (functor with respect to each component with other component fixed) and e
is a unit object in B
, satisfying the associativity and unit laws:
(a * b) * c = a * (b * c)
a * e = e * a = a
for any objects a,b,c
of B
, and the same identities for any morphisms a,b,c
with e
replaced by id_e
, the identity morphism of e
. It is now instructive to observe that in our case of interest, where B
is the category of endofunctors of X
with natural transformations as morphisms, *
the functor composition and e
the identity functor, all these laws are satisfied, as can be directly verified.
What comes after in the book is the definition of the "relaxed" monoidal category, where the laws only hold modulo some fixed natural transformations satisfying so-called coherence relations, which is however not important for our cases of the endofunctor categories.
Finally, in section 3 "Monoids" of Chapter VII, the actual definition is given:
A monoid
c
in a monoidal category(B, *, e)
is an object ofB
with two arrows (morphisms)
mu: c * c -> c
nu: e -> c
making 3 diagrams commutative. Recall that in our case, these are morphisms in the category of endofunctors, which are natural transformations corresponding to precisely join
and return
for a monad. The connection becomes even clearer when we make the composition *
more explicit, replacing c * c
by c^2
, where c
is our monad.
Finally, notice that the 3 commutative diagrams (in the definition of a monoid in monoidal category) are written for general (non-strict) monoidal categories, while in our case all natural transformations arising as part of the monoidal category are actually identities. That will make the diagrams exactly the same as the ones in the definition of a monad, making the correspondence complete.
In summary, any monad is by definition an endofunctor, hence an object in the category of endofunctors, where the monadic join
and return
operators satisfy the definition of a monoid in that particular (strict) monoidal category. Vice versa, any monoid in the monoidal category of endofunctors is by definition a triple (c, mu, nu)
consisting of an object and two arrows, e.g. natural transformations in our case, satisfying the same laws as a monad.
Finally, note the key difference between the (classical) monoids and the more general monoids in monoidal categories. The two arrows mu
and nu
above are not anymore a binary operation and a unit in a set. Instead, you have one fixed endofunctor c
. The functor composition *
and the identity functor alone do not provide the complete structure needed for the monad, despite that confusing remark in the book.
Another approach would be to compare with the standard monoid C
of all self-maps of a set A
, where the binary operation is the composition, that can be seen to map the standard cartesian product C x C
into C
. Passing to the categorified monoid, we are replacing the cartesian product x
with the functor composition *
, and the binary operation gets replaced with the natural transformation mu
from
c * c
to c
, that is a collection of the join
operators
join: c(c(T))->c(T)
for every object T
(type in programming). And the identity elements in classical monoids, which can be identified with images of maps from a fixed one-point-set, get replaced with the collection of the return
operators
return: T->c(T)
But now there are no more cartesian products, so no pairs of elements and thus no binary operations.
You could always do it recursively like so:
void freeList(struct node* currentNode)
{
if(currentNode->next) freeList(currentNode->next);
free(currentNode);
}
No, browsers don't provide this formatting option.
You could probably fake it with some checkboxes with <label>
s, and JS to turn it into a fly out menu.
This following program can handle large numbers ( number of digits greater than 20 )
package com.isEven.java;
import java.util.Scanner;
public class isEvenValuate{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String digit = in.next();
int y = Character.getNumericValue(digit.charAt(digit.length()-1));
boolean isEven = (y&1)==0;
if(isEven)
System.out.println("Even");
else
System.out.println("Odd");
}
}
Here is the output ::
122873215981652362153862153872138721637272
Even
Because of the GDPR it makes no sense to use the iframe, you should rather use the object tag with the embed tag and also use the embed link.
<object width="100%" height="333">
<param name="movie" value="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw">
<embed src="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw" width="100%" height="333">
</object>
_x000D_
You should also activate the extended data protection mode function to receive the no cookie url.
type="application/x-shockwave-flash"
flash does not have to be used
Nocookie, however, means that data is still being transmitted, namely the thumbnail that is loaded from YouTube. But at least data is no longer passed on to advertising networks (as example DoubleClick). And no user data is stored on your website by youtube.
On Apple platforms (iOS/macOS/tvOS/watchOS), the limit may be a 2 GB long URL scheme, as seen by this comment in the source code of Swift:
// Make sure the URL string isn't too long. // We're limiting it to 2GB for backwards compatibility with 32-bit executables using NS/CFURL if ( (urlStringLength > 0) && (urlStringLength <= INT_MAX) ) { ...
On iOS, I've tested and confirmed that even a 300+ MB long URL is accepted. You can try such a long URL like this in Objective-C:
NSString *path = [@"a:" stringByPaddingToLength:314572800 withString:@"a" startingAtIndex:0];
NSString *js = [NSString stringWithFormat:@"window.location.href = \"%@\";", path];
[self.webView stringByEvaluatingJavaScriptFromString:js];
And catch if it succeed with:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"length: %@", @(request.URL.absoluteString.length));
return YES;
}
Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?
Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.
If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:
sudo add-apt-repository ppa:jonathonf/python-3.6 # (only for 16.04 LTS)
Then, run the following (this works out-of-the-box on 16.10 and 17.04):
sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3
# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python
When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1
(or a more recent version of Python 3.6):
python --version # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version
Besides the answers already mentioned, here is an explanation of why you have some random characters at the end:
You are opening the file in r+
mode, not w
mode. The key difference is that w
mode clears the contents of the file as soon as you open it, whereas r+
doesn't.
This means that if your file content is "123456789" and you write "www" to it, you get "www456789". It overwrites the characters with the new input, but leaves any remaining input untouched.
You can clear a section of the file contents by using truncate(<startPosition>)
, but you are probably best off saving the updated file content to a string first, then doing truncate(0)
and writing it all at once.
Or you can use my library :D
Using concept of unique hash keys :
my @array = ("a","b","c","b","a","d","c","a","d");
my %hash = map { $_ => 1 } @array;
my @unique = keys %hash;
print "@unique","\n";
Output: a c b d
My humble take on the subject, a generalization of Alex Martelli's answer, with start() and stop() control:
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
Usage:
from time import sleep
def hello(name):
print "Hello %s!" % name
print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
sleep(5) # your long-running job goes here...
finally:
rt.stop() # better in a try/finally block to make sure the program ends!
Features:
start()
and stop()
are safe to call multiple times even if the timer has already started/stoppedinterval
anytime, it will be effective after next run. Same for args
, kwargs
and even function
!Opening XCode and accepting the license fixes the issue.
If you are working with Android-studio 1.3, Follow the below steps -
Go to File - Project Structure
Under modules- app-Properties tab, choose Source Compatibility -1.8 and
Target Compatibility - 1.8.
And you are good to go.
To match the title of this question, the value of the id
attribute is:
var myId = $(this).attr('id');
alert( myId );
BUT, of course, the element must already have the id element defined, as:
<option id="opt7" class='select_continent' value='7'>Antarctica</option>
In the OP post, this was not the case.
Note that plain js is faster (in this case):
var myId = this.id
alert( myId );
That is, if you are just storing the returned text into a variable as in the above example. No need for jQuery's wonderfulness here.
a little more generic answer of jelde015 (credit to him of course)
for updating the loading bar manually will be:
import sys
from math import *
def loadingBar(i, N, size):
percent = float(i) / float(N)
sys.stdout.write("\r"
+ str(int(i)).rjust(3, '0')
+"/"
+str(int(N)).rjust(3, '0')
+ ' ['
+ '='*ceil(percent*size)
+ ' '*floor((1-percent)*size)
+ ']')
and calling it by:
loadingBar(7, 220, 40)
will result:
007/220 [= ]
just call it whenever you want with the current i
value.
set the size
as the number of chars the bar should be
2,147,483,647 bytes, since the value is a signed integer (Int32). That's probably more than you'll need.
You can use the native JS slice method:
<div v-for="item in shoppingItems.slice(0,10)">
The slice() method returns the selected elements in an array, as a new array object.
Based on tip in the migration guide: https://vuejs.org/v2/guide/migration.html#Replacing-the-limitBy-Filter
You can also take a look at x-ray: https://github.com/lapwinglabs/x-ray
I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:
<partial name="_My_Partial" model="Model.MyInfo" />
When I faced with a similar problem, I finished with the following code:
public bool IsFileLocked(string filePath)
{
try
{
using (File.Open(filePath, FileMode.Open)){}
}
catch (IOException e)
{
var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
return errorCode == 32 || errorCode == 33;
}
return false;
}
On Java 14 you can do this
List<String> strings = Arrays.asList("one", "two", "three");
From here download this video so we have the same video file for the test. Make sure to have that mp4 file in the same directory of your python code. Then also make sure to run the python interpreter from the same directory.
Then modify the code, ditch waitKey
that's wasting time also without a window it cannot capture the keyboard events. Also we print the success
value to make sure it's reading the frames successfully.
import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
while success:
cv2.imwrite("frame%d.jpg" % count, image) # save frame as JPEG file
success,image = vidcap.read()
print('Read a new frame: ', success)
count += 1
How does that go?
Try like this,
>>> s = set([1,2,3])
>>> s = list(s)
>>> s
[1, 2, 3]
>>> str = ', '.join(str(e) for e in s)
>>> str = 'set(%s)' % str
>>> str
'set(1, 2, 3)'
Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.
SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29';
it helps , you can convert the values as DATE
before comparing.
Open the /etc/mysql/mysql.conf.d/mysqld.cnf
file and comment the
following line:
#bind-address = 127.0.0.1
war - web archive. It is used to deploy web applications according to the servlet standard. It is a jar file containing a special directory called WEB-INF and several files and directories inside it (web.xml, lib, classes) as well as all the HTML, JSP, images, CSS, JavaScript and other resources of the web application
ear - enterprise archive. It is used to deploy enterprise application containing EJBs, web applications, and 3rd party libraries. It is also a jar file, it has a special directory called APP-INF that contains the application.xml file, and it contains jar and war files.
I put together start to finish code of a hypothetical experiment with ten measurement replicated three times. Just for fun with the help of other stackoverflowers. Thank you... Obviously loops are an option as apply
can be used but I like to see what happens.
#Create fake data
x <-rep(1:10, each =3)
y <- rnorm(30, mean=4,sd=1)
#Loop to get standard deviation from data
sd.y = NULL
for(i in 1:10){
sd.y[i] <- sd(y[(1+(i-1)*3):(3+(i-1)*3)])
}
sd.y<-rep(sd.y,each = 3)
#Loop to get mean from data
mean.y = NULL
for(i in 1:10){
mean.y[i] <- mean(y[(1+(i-1)*3):(3+(i-1)*3)])
}
mean.y<-rep(mean.y,each = 3)
#Put together the data to view it so far
data <- cbind(x, y, mean.y, sd.y)
#Make an empty matrix to fill with shrunk data
data.1 = matrix(data = NA, nrow=10, ncol = 4)
colnames(data.1) <- c("X","Y","MEAN","SD")
#Loop to put data into shrunk format
for(i in 1:10){
data.1[i,] <- data[(1+(i-1)*3),]
}
#Create atomic vectors for arrows
x <- data.1[,1]
mean.exp <- data.1[,3]
sd.exp <- data.1[,4]
#Plot the data
plot(x, mean.exp, ylim = range(c(mean.exp-sd.exp,mean.exp+sd.exp)))
abline(h = 4)
arrows(x, mean.exp-sd.exp, x, mean.exp+sd.exp, length=0.05, angle=90, code=3)
Use the overloads that take the controller name too...
return RedirectToAction("Index", "MyController");
and
@Html.ActionLink("Link Name","Index", "MyController", null, null)
Maybe you need 'User-Agent':
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36')]
response = opener.open('http://google.com')
htmlData = response.read()
f = open('file.txt','w')
f.write(htmlData )
f.close()
See jQuery's post
function.
I would create a button, and set an onClickListener
($('#button').on('click', function(){});
), and send the data in the function.
Also, see the preventDefault
function, of jQuery!
Purpose of these interfaces from oracle documentation :
Runnable interface should be implemented by any class whose instances are intended to be executed by a Thread
. The class must define a method of no arguments called run
.
Callable: A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.
The Callable
interface is similar to Runnable
, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable
, however, does not return a result and cannot throw a checked exception.
Other differences:
You can pass Runnable
to create a Thread. But you can't create new Thread by passing Callable
as parameter. You can pass Callable only to ExecutorService
instances.
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Use Runnable
for fire and forget calls. Use Callable
to verify the result.
Callable
can be passed to invokeAll method unlike Runnable
. Methods invokeAny
and invokeAll
perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete
Trivial difference : method name to be implemented => run()
for Runnable
and call()
for Callable
.
Why do you consider regex the best tool for this? If your purpose is to detect whether an illegal character is present in a string, testing each character in a loop will be both simpler and more efficient than constructing a regex.
This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.
It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg
. FigureCanvasQTAgg
and NavigationToolbar2QT
are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure
, Navigation
and a single button that draws some random data. I've added comments to explain things.
import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import random
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = Figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QtGui.QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
ax.clear()
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
Edit:
Updated to reflect comments and API changes.
NavigationToolbar2QTAgg
changed with NavigationToolbar2QT
Figure
instead of pyplot
ax.hold(False)
with ax.clear()
create a new database with same name copy the .frm .ibd files into xampp/mysql/data/[databasename]/
you will need ibdata file as well which is found inside
xampp/mysql/data/ copy the previous ibdata1 file paste in the paste the file and replace it with the existing ibdata file
[caution: you may loose the contents of the database which are newly created in the new ibdata file]
This is the natural javascript option
var myArray = ['1','2',3,4]_x000D_
_x000D_
myArray.forEach(function(value){_x000D_
console.log(value);_x000D_
});
_x000D_
However it won't work if you're using await inside the forEach loop because forEach is not asynchronous. you'll be forced to use the second answer or some other equivalent:
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
console.log(item);_x000D_
}
_x000D_
Or you could create an asyncForEach explained here:
https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
Then tell read.table not to use row.names
:
systems <- read.table("http://getfile.pl?test.csv",
header=TRUE, sep=",", row.names=NULL)
and now your rows will simply be numbered.
Also look at read.csv
which is a wrapper for read.table
which already sets the sep=','
and header=TRUE
arguments so that your call simplifies to
systems <- read.csv("http://getfile.pl?test.csv", row.names=NULL)
Use the method that accepts a Comparator
when you want to sort in something other than natural order.
I find letter identifiers to be more readable and more indicative of parsed type:
1 - 7f / 10
1 - 7 / 10f
or:
1 - 7d / 10
1 - 7 / 10d
try this:
.test {
position:absolute;
background:blue;
width:200px;
height:200px;
top:40px;
transition:left 1s linear;
left: 0;
}
Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.
if(!(borrar() === false))
or
if(borrar() === true)
The correct form, based on the original syntax, and correctly normalized is:
def gaussian(x, mu, sig):
return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)
Here's a simple way.
/**
* Add css to the document
* @param {string} css
*/
function addCssToDocument(css){
var style = document.createElement('style')
style.innerText = css
document.head.appendChild(style)
}
Another alternative might be
Array.from(document.querySelectorAll("a")).map(x => x.href)
With your $$(
its even shorter
Array.from($$("a")).map(x => x.href)
On Fedora 19, it looks like the answer is /var/log/messages
. Although check /etc/rsyslog.conf
if it has been changed.
if(isset($_SESSION))
{}
else
{}
From the designer, you can set the onClick
property of the listItem to a method defined with a single parameter. I have an example method defined below. The method getAdapterPosition will give you the index of the selected listItem.
public void exampleOnClickMethod(View view){
myRecyclerView.getChildViewHolder(view).getAdapterPosition());
}
For information on setting up a RecyclerView, see the documentation here: https://developer.android.com/guide/topics/ui/layout/recyclerview
A solution that nobody mentioned is use white-space: nowrap
for the table and add overflow-x
to the wrapper.
(http://jsfiddle.net/xc7jLuyx/11/)
CSS
.wrapper { overflow-x: auto; }
.wrapper table { white-space: nowrap }
HTML
<div class="wrapper">
<table></table>
</div>
This is an ideal scenario if you don't want rows with multiple lines.
To add break lines you need to use <br/>
.
Parse Querystring into a NameValueCollection. Remove an item. And use the toString to convert it back to a querystring.
using System.Collections.Specialized;
NameValueCollection filteredQueryString = System.Web.HttpUtility.ParseQueryString(Request.QueryString.ToString());
filteredQueryString.Remove("appKey");
var queryString = '?'+ filteredQueryString.ToString();
Chrome now supports loading HAR files. Open Chrome, Press F12, Click on the Network Tab. Drag and drop the .har file DONE !
Use
sudo lsof -i:5000
This will give you a list of processes using the port if any. Once the list of processes is given, use the id on the PID column to terminate the process use
kill 379 #use the provided PID
I have seen some solutions here worth noting, as Omer Eldan posted. but here follows. ASP C#
using System.Data;
using System.Web.UI.HtmlControls;
public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
Table tbl = new Table();
TableRow tr = null;
TableCell cell = null;
int rows = dt.Rows.Count;
int cols = dt.Columns.Count;
if (includeHeaders)
{
TableHeaderRow htr = new TableHeaderRow();
TableHeaderCell hcell = null;
for (int i = 0; i < cols; i++)
{
hcell = new TableHeaderCell();
hcell.Text = dt.Columns[i].ColumnName.ToString();
htr.Cells.Add(hcell);
}
tbl.Rows.Add(htr);
}
for (int j = 0; j < rows; j++)
{
tr = new TableRow();
for (int k = 0; k < cols; k++)
{
cell = new TableCell();
cell.Text = dt.Rows[j][k].ToString();
tr.Cells.Add(cell);
}
tbl.Rows.Add(tr);
}
return tbl;
}
why this solution? Because you can easily just add this to a panel ie:
panel.Controls.Add(DataTableToHTMLTable(dtExample,true));
Second question , why do you have one column datatables and not just array's? Are you sure that these DataTables are uniform, because if the data is jagged then it's no use. If You really have to join these DataTables, there is many examples of Linq operations, or just use (beware though of same name columns as this will conflict in both linq operations and this solution if not handled):
public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
int dt2ColsCount = dt2.Columns.Count;
int dt1lRowsCount = dt1.Rows.Count;
DataColumn column;
for (int i = 0; i < dt2ColsCount; i++)
{
column = new DataColumn();
string colName = dt2.Columns[i].ColumnName;
System.Type colType = dt2.Columns[i].DataType;
column.ColumnName = colName;
column.DataType = colType;
dt1.Columns.Add(column);
for (int j = 0; j < dt1lRowsCount; j++)
{
dt1.Rows[j][colName] = dt2.Rows[j][colName];
}
}
return dt1;
}
and your solution would look something like:
panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));
interpret the rest, and have fun.
I am using React-Native 0.40 and below code works for me both on IOS and Android.
(Android-only) Sets the elevation of a view, using Android's underlying elevation API. This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.
class MainApp extends Component {
render() {
return (
<View style={styles.container}>
<View elevation={5} style={styles.buttonContainer}>
<Text style={styles.textStyle}>Shadow Applied</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF'
},
textStyle: {
color: '#FFFFFF'
},
buttonContainer: {
backgroundColor: '#2E9298',
borderRadius: 10,
padding: 10,
shadowColor: '#000000',
shadowOffset: {
width: 0,
height: 3
},
shadowRadius: 5,
shadowOpacity: 1.0
}
})
Tested on iPhone.
Edit
Comment from @ James. Thanks.
Note: For those on android, the backgroundColor is critical. I was using View as a container for another element and couldn't get a shadow until I specified a background color.
You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.
The System.exit(0)
will terminates the currently running Java Virtual Machine.
create procedure usp_find_string(@string as varchar(1000))
as
begin
declare @mincounter as int
declare @maxcounter as int
declare @stmtquery as varchar(1000)
set @stmtquery=''
create table #tmp(tablename varchar(128),columnname varchar(128),rowid int identity)
create table #tablelist(tablename varchar(128),columnname varchar(128))
declare @tmp table(name varchar(128))
declare @tablename as varchar(128)
declare @columnname as varchar(128)
insert into #tmp(tablename,columnname)
select a.name,b.name as columnname from sysobjects a
inner join syscolumns b on a.name=object_name(b.id)
where a.type='u'
and b.xtype in(select xtype from systypes
where name='text' or name='ntext' or name='varchar' or name='nvarchar' or name='char' or name='nchar')
order by a.name
select @maxcounter=max(rowid),@mincounter=min(rowid) from #tmp
while(@mincounter <= @maxcounter )
begin
select @tablename=tablename, @columnname=columnname from #tmp where rowid=@mincounter
set @stmtquery ='select top 1 ' + '[' +@columnname+']' + ' from ' + '['+@tablename+']' + ' where ' + '['+@columnname+']' + ' like ' + '''%' + @string + '%'''
insert into @tmp(name) exec(@stmtquery)
if @@rowcount >0
insert into #tablelist values(@tablename,@columnname)
set @mincounter=@mincounter +1
end
select * from #tablelist
end
You can also wrap your <script>
like this and it will get executed:
<your target node>.innerHTML = '<iframe srcdoc="<script>alert(top.document.title);</script>"></iframe>';
Please note: The scope inside srcdoc
refers to the iframe, so you have to use top
like in the example above to access the parent document.
Here's the simplest solution with a clear selector:
function select_option(i) {
return $('span#span_id select option[value="' + i + '"]').html();
}
If you are using a form in the modal then you can use
$("#form_id").trigger("reset");
SessionFactory
vs. EntityManagerFactory
As I explained in the Hibernate User Guide, the Hibernate SessionFactory
extends the JPA EntityManagerFactory
, as illustrated by the following diagram:
So, the SessionFactory
is also a JPA EntityManagerFactory
.
Both the SessionFactory
and the EntityManagerFactory
contain the entity mapping metadata and allow you to create a Hibernate Session
or a EntityManager
.
Session
vs. EntityManager
Just like the SessionFactory
and EntityManagerFactory
, the Hibernate Session
extends the JPA EntityManager
. So, all methods defined by the EntityManager
are available in the Hibernate Session
.
The Session
and the `EntityManager translate entity state transitions into SQL statements, like SELECT, INSERT, UPDATE, and DELETE.
When bootstrapping a JPA or Hibernate application, you have two choices:
SessionFactory
via the BootstrapServiceRegistryBuilder
. If you're using Spring, the Hibernate bootstrap is done via the LocalSessionFactoryBean
, as illustrated by this GitHub example.EntityManagerFactory
via the Persistence
class or the EntityManagerFactoryBuilder
. If you're using Spring, the JPA bootstrap is done via the LocalContainerEntityManagerFactoryBean
, as illustrated by this GitHub example.Bootstrapping via JPA is to be preferred. That's because the JPA FlushModeType.AUTO
is a much better choice than the legacy FlushMode.AUTO
, which breaks read-your-writes consistency for native SQL queries.
Also, if you bootstrap via JPA, and you have injected the EntityManagerFactory
via the @PersistenceUnit
annotation:
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
You can easily get access to the underlying Sessionfactory
using the unwrap
method:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
The same can be done with the JPA EntityManager
. If you inject the EntityManager
via the @PersistenceContext
annotation:
@PersistenceContext
private EntityManager entityManager;
You can easily get access to the underlying Session
using the unwrap
method:
Session session = entityManager.unwrap(Session.class);
So, you should bootstrap via JPA, use the EntityManagerFactory
and EntityManager
, and only unwrap those to their associated Hibernate interfaces when you want to get access to some Hibernate-specific methods that are not available in JPA, like fetching the entity via its natural identifier.
Just add them in one line command 2>> error 1>> output
However, note that >>
is for appending if the file already has data. Whereas, >
will overwrite any existing data in the file.
So, command 2> error 1> output
if you do not want to append.
Just for completion's sake, you can write 1>
as just >
since the default file descriptor is the output. so 1>
and >
is the same thing.
So, command 2> error 1> output
becomes, command 2> error > output
I fixed this issue by setting a newer version of node as default in nvm i.e.:
nvm alias default 12.XX.X
Use itoa, as is shown here.
char buf[5];
// Convert 123 to string [buf]
itoa(123, buf, 10);
buf
will be a string array as you documented. You might need to increase the size of the buffer.
RUn the following query to find if you are running spfile or not:
SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type"
FROM sys.v_$parameter WHERE name = 'spfile';
If the result is "SPFILE", then use the following command:
alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor
if the result is "PFILE", then use the following command:
alter system set open_cursors = 1000 ;
You can read about SPFILE vs PFILE here,
Use decode
:
print(curses.version.decode())
# 2.2
How I solved "Failed cleaning build dir for cryptography"
(I came here from google to result for this error.)
note: using a virtualenv
my file /etc/apt/sources.list
wasn't correctly configured for my debian 8.
I wanted to install paramiko. paramiko needs cryptography.
I got these errors:
first with pip install cryptography
:
(...)
----------------------------------------
Failed cleaning build dir for cryptography
Failed to build cryptography
(...)
----------------------------------------
Command "/home/myuser/pyenvs/testo/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-HXWKAO/cryptography/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-WjqY6V-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/myuser/pyenvs/testo/include/site/python2.7/cryptography" failed with error code 1 in /tmp/pip-build-HXWKAO/cryptography/
and then with sudo apt-get install build-essential
:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
build-essential : Depends: libc6-dev but it is not going to be installed > or
libc-dev
Depends: gcc (>= 4:4.4.3) but it is not going to be installed
Depends: g++ (>= 4:4.4.3) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
(Not exactly the same errors as OP but I'm here to help eventually)
After testing almost every command from every posts I end up going on
https://wiki.debian.org/SourcesList
and copy pasted my adequate config in the file /etc/apt/sources.list
then:
sudo aptitude update
and then
sudo apt-get install build-essential libssl-dev libffi-dev python-dev
and then
pip install cryptography
hth
Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:
>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0
# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)
Note that different timezones have impact on results, e.g. my current TZ/DST returns:
>>> time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h
therefore one should consider normalizing to UTC by using UTC versions of the functions.
Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.
References:
Map.prototype.map = function(callback) {
const output = new Map()
this.forEach((element, key)=>{
output.set(key, callback(element, key))
})
return output
}
const myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]])
// no longer wishful thinking
const newMap = myMap.map((value, key) => value + 1)
console.info(myMap, newMap)
Depends on your religious fervor in avoiding editing prototypes, but, I find this lets me keep it intuitive.
You have to specify the name of the custom view and its related model in Controller Action method.
public ActionResult About()
{
return View("NameOfViewYouWantToReturn",Model);
}
Also you can use 'os.popen'. Example:
import os
command = os.popen('ls -al')
print(command.read())
print(command.close())
Output:
total 16
drwxr-xr-x 2 root root 4096 ago 13 21:53 .
drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
-rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
-rw-r--r-- 1 root root 77 ago 13 21:53 test.py
None
The most simple way of doing this is to use an ArrayList<Integer>
and use the add(int, T)
method.
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
// Now, we will insert the number
list.add(4, 87);
Solutions:
Solution A:
com.oreilly.servlet.MultipartRequest
Solution B:
org.apache.commons.fileupload.MultipartStream
Solution C:
Solution D:
Use Struts. Struts 1.1 handles this automatically.
Simple and easy!
get_queried_object_id()
Ahah! Cade is on the money.
An artifact in TOAD prints \r\n
as two placeholder 'blob' characters, but prints a single \r
also as two placeholders. The 1st step toward a solution is to use ..
REPLACE( col_name, CHR(13) || CHR(10) )
.. but I opted for the slightly more robust ..
REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) )
.. which catches offending characters in any order. My many thanks to Cade.
M.
As GvS said, but I also find it useful to use strongly typed views so that I can write something like
@Html.Partial(MVC.Student.Index(), model)
without magic strings.
Alternatively, you can get pip-Win which is an all-in-one installer for pip and virtualenv
on Windows and its GUI.
vertical-align
is only supposed to work on elements that are rendered as inline
. <span>
is rendered as inline by default, but not all elements are. The paragraph block element, <p>
, is rendered as a block by default. Table render types (e.g. table-cell
) will allow you to use vertical-align as well.
Some browsers may allow you to use the vertical-align
CSS property on items such as the paragraph block, but they are not supposed to. Text denoted as a paragraph should be filled with written-language content or the mark-up is incorrect and should be using one of a number of other options instead.
I hope this helps!
The functionality of map
and filter
was intentionally changed to return iterators, and reduce was removed from being a built-in and placed in functools.reduce
.
So, for filter
and map
, you can wrap them with list()
to see the results like you did before.
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> list(filter(f, range(2, 25)))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> import functools
>>> def add(x,y): return x+y
...
>>> functools.reduce(add, range(1, 11))
55
>>>
The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions. Example:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> [i for i in range(2, 25) if f(i)]
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> [cube(i) for i in range(1, 11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>
They say that for loops are 99 percent of the time easier to read than reduce, but I'd just stick with functools.reduce
.
Edit: The 99 percent figure is pulled directly from the What’s New In Python 3.0 page authored by Guido van Rossum.
Okay, the .NET 2.0 answers:
If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)
If you do need to clone the values, you can use something like this:
public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
(Dictionary<TKey, TValue> original) where TValue : ICloneable
{
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
original.Comparer);
foreach (KeyValuePair<TKey, TValue> entry in original)
{
ret.Add(entry.Key, (TValue) entry.Value.Clone());
}
return ret;
}
That relies on TValue.Clone()
being a suitably deep clone as well, of course.
Just set the body as the following
var reqBody = "username="+username+"&password="+password+"&grant_type=password";
then
fetch('url', {
method: 'POST',
headers: {
//'Authorization': 'Bearer token',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: reqBody
}).then((response) => response.json())
.then((responseData) => {
console.log(JSON.stringify(responseData));
}).catch(err=>{console.log(err)})
In Laravel 5.4
The easiest way I found, by exporting them to your resources/views/vendor
directory using the vendor:publish
command
php artisan vendor:publish --tag=laravel-pagination
and than go to resources\views\vendor\pagination\default.blade.php
and do your customization there.
Full documentation about this can be found here
You can include JQuery using any of the following:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
- http://code.jquery.com/jquery-latest.min.js (never use this link on production server)
Your code placement can look something like this
```
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('input[type=radio]').change(function() {
$('input[type=radio]').each(function(index) {
$(this).closest('tr').removeClass('selected');
});
$(this).closest('tr').addClass('selected');
});
});
</script>
```
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.
isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.
Follow these steps:
Create a new branch:
git branch newfeature
Checkout new branch: (this will not reset your work.)
git checkout newfeature
Now commit your work on this new branch:
git commit -s
Using above steps will keep your original branch clean and you dont have to do any 'git reset --hard'.
The best one by far is
bool(re.search('ba[rzd]', 'foobarrrr'))
Returns True
I am on Laravel 7.25 and I don't know if it supports on previous versions or not but Its pretty good.
public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)
Showing/Getting the user ID and the total number of posts by them left joining two tables users and posts.
return DB::table('users')
->joinSub('select user_id,count(id) noOfPosts from posts group by user_id', 'totalPosts', 'users.id', '=', 'totalPosts.user_id', 'left')
->select('users.name', 'totalPosts.noOfPosts')
->get();
If you don't wanna mention 'left' for leftjoin then you can use another prebuilt function
public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
{
return $this->joinSub($query, $as, $first, $operator, $second, 'left');
}
And yeah, it actually calls the same function but it passes the join type itself. You can apply the same logic for other joins i.e. righJoinSub(...) etc.
IE8/9 render the non-breaking hyphen mentioned in CanSpice's answer longer than a typical hyphen. It is the length of an en-dash instead of a typical hyphen. This display difference was a deal breaker for me.
As I could not use the CSS answer specified by Deb I instead opted to use no break tags.
<nobr>e-mail</nobr>
In addition I found a specific scenario that caused IE8/9 to break on a hyphen.
IE renders it like this.
The following code reproduces the problem pictured above. I had to use a meta tag to force rendering to IE9 as IE10 has fixed the issue. No fiddle because it does not support meta tags.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta charset="utf-8"/>
<style>
body { padding: 20px; }
div { width: 300px; border: 1px solid gray; }
</style>
</head>
<body>
<div>
<p>If there is a - and words are separated by the whitespace code &nbsp; then IE will wrap on the dash.</p>
</div>
</body>
</html>
ivmage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);
}
});`