text:
Q: 'Move and size with cells' is Greyed Out I added a form control checkbox using the developer tab, but the Move and size with cells option is greyed out.

I cannot find any information relating to Excel 2010 or greater that explains how to activate this option.
How can I enable this option?

A: It is not a mistake, you have to treat that as an object, go to Format Shape, select the button with the right button and in Properties, you'll get the option.

A: Right-click on the checkbox and go to the Format menu (top center)
Click on the small arrow available near the size option. this will open the panel on the right side. Click on properties and there you have this option to move and size with cells.
hope this helps.


text:
Q: Problem detected by xampp, tomcat not running Am actually new to xampp, but whenever I launch the xampp control panel I get this error. Please I really need help here.
This is the error:
Problem detected!
Port 8080 in use by "C:/xampp/apache/bin/httpd.exe"!
Tomcat will not start without the configured port free!
You need to uninstall /disable/configure the blocking applicantion or reconfigure tomcat and the control panel to listen on a different port.
Please am confused here,  any help?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel nested conditional formatting with indirect references I am working on a MS Excel 2010 spreadsheet where the users want to have some combined conditional formatting.
Individually the functions I want to apply are working correctly, i.e this condition formula works:
= INDIRECT( ADDRESS( IF( ISEVEN( ROW() ), ROW() - 1, ROW() ), 22) ) = "6 Monthly"

As does this:
= OR( COLUMN() = 25, COLUMN() = 28)

But combining the formulae fails to apply any format. No error is returned, but the highlighted area is unaffected on applying the condition:
AND( INDIRECT(ADDRESS(IF(ISEVEN(ROW()), ROW() - 1, ROW()), 22)) = "3 Monthly", OR( COLUMN() = 25, COLUMN() = 28) )

If I want the cells where both conditions are met to be highlighted, what should I enter as the formula?

A: This works for me:
=(INDIRECT(ADDRESS(IF(ISEVEN(ROW()),ROW()-1,ROW()),22))="3 Monthly")*(OR(COLUMN()=25, COLUMN()=28))

A: Your conditional formatting formulas seem overly complex to me
Select Y11:Y48 and then hold down CTRL key and also select AB11:AB48 and apply the conditional formatting formula
=$V11="3 Monthly"
Format as required
That will highlight the column Y and AB cells in every row where col V = "3 Monthly" - isn't that the requirement?

A: Use IF:
=IF(INDIRECT(ADDRESS(IF(ISEVEN(ROW()),ROW()-1, ROW()),22))="3 Monthly",OR(COLUMN()=25,COLUMN()=28),0)

Hope this helps.


text:
Q: How to handle serialization changes in .NET 2.0 .NET 2.0 introduced VTS (Version Tolerant Serialization,
http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx )
A simple test project reveals that the default behavior in 2.0 is to not throw a serialization exception if a field is added to a class, then an attempt is made to deserialize an instance of that class from a binary serialization of a class instance that didn't have the new field.
The default behavior in 1.1 is to throw a serialization exception if a field present in the class is missing in the binary serialized bits.
Besides breaking backwards compatibility (code relying on the exceptions being thrown doesn't work anymore), there's a bigger problem: there is no obvious way to emulate the 1.1 behaviour in 2.0.
How do I emulate the 'throw exception on missing/extra fields' 1.1 behavior in 2.0?
Many thanks,
Miron

A: In general, people want to be able to at least deserialize old data, regardless of changes to the class design. Unfortunately, BinaryFormatter (being field based) is very brittle here - even switching to automatically implemented properties can break things.
Personally, I would be designing around data-contracts or similar structures that are not implementation specific, and are extensible. For binary, protobuf-net has a lot of uses in this area.
If you really want to emulate the 1.1 behaviour - implement ISerializable by hand and throw the exception (or not) yourself.

A: Only fields that have the OptionalFieldAttribute attribute applied to them should ignore the missing information during deserialization. Simply removing that attribute should yield an exception, and result in the same behaviour as in .NET Framework 1.1.
Update:
The culprit must be the AssemblyFormat property of the BinaryFormatter class, which is FormatterAssemblyStyle.Full by default in 1.1, but which is FormatterAssemblyStyle.Simple by default in 2.0.
In fact, setting this to FormatterAssemblyStyle.Simple in 1.1 will yield the same behaviour as in 2.0: no exception is thrown. At last in .NET 2.0 you have the OptionalFieldAttribute to be more finegrained.
So set this property to FormatterAssemblyStyle.Full, and see what it does.
See also here.


text:
Q: need to search data using part of composite row key in cassandra I am new to Cassandra and just playing around with it. I have created a Column family having composite key and composite column. Following is the script for same:
create column family TestCompositeKey with key_validation_class='CompositeType(UTF8Type, TimeUUIDType)' and comparator='CompositeType(UTF8Type, UTF8Type, UTF8Type, UTF8Type)' and default_validation_class='UTF8Type';

After inserting data in the column family using Hector following is the view I am getting on CLI:
RowKey: AB:e9a87550-c84b-11e2-8236-180373b60c1a
=> (column=0007:TAR:PUB:BD_2013_01_11_0125094813, value=TESTSEARCH, timestamp=1369823914277000)

Now I want to search for data just by 'AB' given in row key as second part of key will be dynamic. It works fine when I give complete row key. Please tell me how can this be done. I am supplying search criteria on column too along with specifying key.
Thanks
Harish Kumar

A: You can't do this (efficiently, at least): to lookup by row key you need the whole key.  In general, using TimeUUIDs as row keys should be avoided, unless you have some other table acting as an index to retrieve TimeUUIDs for a query.
If you want to lookup just by the first component of the key you should move the second component to the column composite and just have a single component as the row key.  The definition would be
create column family TestCompositeKey with key_validation_class='UTF8Type' and comparator='CompositeType(TimeUUIDType, UTF8Type, UTF8Type, UTF8Type, UTF8Type)' and default_validation_class='UTF8Type';

If you used the CQL3 definition:
CREATE TABLE TestCompositeKey (
    a varchar,
    b timeuuid varchar,
    c varchar,
    d varchar,
    e varchar,
    f varchar,
    PRIMARY KEY (a, b, c, d, e, f)
);

you would get essentially the same schema as I described.  The row key (partition key in CQL language) is a, and the column names are a composite of b:c:d:e:f.


text:
Q: How do I make this procedure generate random times (HH:MM:SS) but with the current date? I need this procedure to generate 10M random timestamps but it has to use the current date each time it is called, how do i do this? I know that there's a CURRENT_TIMESTAMP() function, but I'm not sure how to implement it.
DELIMITER $$
CREATE PROCEDURE producer()

    BEGIN
        DECLARE a INT DEFAULT 0;
        WHILE a < 10000000 DO
            INSERT INTO CaseLog (`TIMESTAMP_IN`)
            VALUES (FROM_UNIXTIME(UNIX_TIMESTAMP('2021-09-22 00:00:00')+FLOOR(RAND()*86399))
            );
            SET a = a+1;
        END WHILE;
    END$$
DELIMITER ;

A: Use CURRENT_DATE() to get today's date, and use that instead of the hard-coded date.
DELIMITER $$
CREATE PROCEDURE producer()

    BEGIN
        DECLARE today_timestamp INT;
        SET today_timestamp = UNIX_TIMESTAMP(CURRENT_DATE());
        DECLARE a INT DEFAULT 0;
        WHILE a < 10000000 DO
            INSERT INTO CaseLog (`TIMESTAMP_IN`)
            VALUES (FROM_UNIXTIME(today_timestamp+FLOOR(RAND()*86400)));
            SET a = a+1;
        END WHILE;
    END$$
DELIMITER ;

Also, you should multiply RAND() by 86400, not 86399. The result of RAND() is always less than 1.0, so you don't have to worry that it will return 86400.


text:
Q: How to export SQL Server database structure into text format
Possible Duplicate:
How can I automate the "generate scripts" task in SQL Server Management Studio 2008?

I need to export structure of my SQL Server database into a .sql script(s) without management studio.
UPDATED

A: Try out Tasks -> Generate scripts menu in SQL Management Studio

A: In SQL Management Studio:

*

*Right click on Database entry

*In menu select Task -> Generate Scripts

*Specify what exacly you want to generate (schema only, +functions, +stored procedures,..)


text:
Q: Why is .git/hooks sometimes missing in cloned repos? I have several (Git for Windows 2.6.2 64-bit) repos that I created and started using the same way:

*

*Run git init --bare <repoName>.git in Git Bash.

*Clone the new repo using SourceTree.

*Add and commit initial files (through SourceTree or EGit).

*Blah, blah, blah....

In trying to add a common post-commit hook to these cloned repos, I noticed that only some of them had a .git/hooks directory.  Why?
I dug for questions/answers regarding missing .git/hook directories and did not find anything on SO or more broadly.  Git documentation mentions that repo initialization ensures the (.git/hooks/) .sample files are executable by default; but I really could not find anything that seemed to explain why my cloned repos sometimes contain .git/hooks and sometimes do not.
Can anyone shed some light on the cause and effect at play here?  Thanks.

A: The defined hooks in a git repository are always local to this repository. They are no part of the git history and are not transferred when cloning, fetching or pushing.
Thus, just by cloning an existing repo with hooks, the clones repo will have none of the upstream hooks. You would have to add them manually to the cloned repository.
This question explains some options to help you achieve this.

A: I'm posting this a few years later.
This does seem like a SourceTree thing (as theorized by Jason above). More specifically if one uses the Embedded Git from SourceTree. If I use System Git (I'm on a Mac), then the hooks directory is created and populated with samples. Cloning via command-line yields the same result. When using the Embedded Git, then there is no hooks directory.
Screenshot from the git options in Preferences where you can select between the two.

A: As git hooks are not transferred while cloning, etc. thus a lot of times the hooks are defined in a separate directory (outside of .git directory which is not cloned or transferred).
This is mostly the case with team projects and open source repos. Thus they may have some scripts (for example in their Makefile) which is removing the local .git/hooks and adding some other directory containing the hooks (for example .githooks in root of repo).
This is possible because you can easily configure git to set the core.hooksPath configuration variable to your managed hooks directory for example:
git config core.hooksPath .githooks


text:
Q: create a database MonetDB I have a problem with the creation of a new database.
After that I started MonetDB Server, I insert this command:
mserver5 --dbpath="C:\database1"
But the server give me this error:
!SintaxException:parseError:mserver5 --dbpath="C:\database1"
!SintaxException:parseError: ^';' expected
What should i do to resolve this problem?
Thanks

A: What MonetDB version are you using on what platform?
Presumably Windows and this error message is indicative of a broken installation, potentially caused by moving files/folders around directly on your machine, such that the expected location for server initialisation files can not be found.


text:
Q: How my NPM front end library (bundled) can detect if used in development mode or production mode? I am author for an NPM library of browser web components and I wish to alert users that a new version has been released. Library is developed in VueJs.
Since it is not a cli, I cannot use the update-notifier package as is since the lib code is not executed at installation or build - at least could not find any hook to do this.
So I am trying to detect if my users are executing my library in their development environment or in their production environment.
If they are in development I will look for new version and print a message in their console panel.
What I have done is to use the process.env.NODE_ENV in my library, but when bundled with webpack it get replaced by "production", so my user will always have a code with production...
How can I get their process.env.NODE_ENV?
If I construct code that bypass webpack (such as an eval("process.env.NODE_ENV") it wont work because the process object does not exists at run time in the browser.
Also, I cannot rely on Angular isDevMode() since my users may well be using another framework or no framework at all (pure html).
Any idea ?


text:
Q: I want to get the artifact version deployed by Jenkins I run maven deploy as a step (using maven build step) and the artifact is deployed with a timestamp.
I now want to create a docker image which has the deployed artifact and the docker image is tagged with the artifact timestamp. It is a very common scenario where the tag of docker image has to be same as the artifact is contains.
I have already read a couple of posts

*

*Jenkins maven deploy jar to nexus - artifact naming

*Jenkins - How can i pass parameters from the Upstream to Downstream

*Sonatype Nexus REST Api fetch latest build version
Where [3] gives me the list of snapshot-versions from the server in an xml, which has to be parsed.

*

*Since I'm pushing the artifact in the jenkins job, is it possible to know the full
artifact name in the build instead of getting it from the server.

*Is there an API/any other way, which can give the name of the latest
artifact instead of artifact XML

A: In a Maven based Jenkins Jobs the environment variables POM_GROUPID, POM_ARTIFACTID and POM_VERSION are exported.
Get this Variable via ${ENV,var="POM_VERSION"} (or similar)
Build your tag name like you want with the information above.
See: https://blog.codecentric.de/en/2014/07/accessing-maven-project-properties-jenkins-build-jobs/

Jenkins exposes general maven project properties as environment variables. Of corse this only works in maven build jobs, but not in freestyle jobs that execute maven goals.
[...]
The following table shows a full list of how maven project properties are mapped to Jenkins environment variables:
maven project property - Jenkins environment variable
project.displayName - POM_DISPLAYNAME
project.version - POM_VERSION
project.groupId - POM_GROUPID
project.artifactId - POM_ARTIFACTID
project.packaging - POM_PACKAGING
project.relativePath - POM_RELATIVEPATH

A: The -SNAPSHOT part of all files (attached on an Maven deployment 'task') will be replaced by the timestamped version at deploy:deploy phase.
1) create Docker image file
Extend the artifact POM with docker-maven-plugin (provided by spotify at https://github.com/spotify/docker-maven-plugin) .

[...]
You can also bind the build goal to the package phase, so the container will be built when you run just mvn package.
[...]

<plugin>
  <groupId>com.spotify</groupId>
  <artifactId>docker-maven-plugin</artifactId>
  <version>0.2.11</version>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>build</goal>
      </goals>
      <configuration>
        <imageName>${project.build.finalName}</imageName>
        <baseImage>java</baseImage>
        <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
        <!-- copy the service's jar file from target into the root directory of the image -->
        <resources>
           <resource>
             <targetPath>/</targetPath>
             <directory>${project.build.directory}</directory>
             <include>${project.build.finalName}.jar</include>
           </resource>
        </resources>
      </configuration>
    </execution>
  </executions>
</plugin>

The Docker image name will be defined at <imageName /> and use the artifact file name (${project.build.finalName}).

imageName: Built image will be given this name.

More information about the build goal: mvn com.spotify:docker-maven-plugin:help -Ddetail=true -Dgoal=build or https://github.com/spotify/docker-maven-plugin
2) attach Docker image file on Maven deploy task
Attach - if docker-maven-plugin doesn't do it for you - the Docker image file with the build-helper-maven-plugin (http://www.mojohaus.org/build-helper-maven-plugin/usage.html).
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.9.1</version>
    <executions>
      <execution>
        <id>attach-artifacts</id>
        <phase>package</phase>
        <goals>
          <goal>attach-artifact</goal>
        </goals>
        <configuration>
          <artifacts>
            <artifact>
              <file>${project.build.finalName}</file>
              <type>...</type>
              <classifier>docker</classifier>
            </artifact>
            ...
          </artifacts>
        </configuration>
      </execution>
    </executions>
  </plugin>

After these steps the artifact files itself and the Docker image artifact are deployed to Maven repository with identical version strings.


text:
Q: Updating firebase in my gradle app module ruined my app. Going back to previous versions does not work Before any changes my gradle looked like this:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.google.firebase:firebase-core:10.0.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.google.firebase:firebase-database:10.0.1'
    compile 'com.google.android.gms:play-services-auth:10.0.1'

    compile 'com.firebaseui:firebase-ui-auth:1.0.1'
}
apply plugin: 'com.google.gms.google-services'

and
buildscript {
    repositories {
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and everything was working fine. Then I updated all of the com/google... dependencies to 10.2.0 version and firebaseui to 1.2.0 as the table here says https://github.com/firebase/FirebaseUI-Android#compatibility-with-firebase--google-play-services-libraries
Then I got some errors on mFirebaseAuth = FirebaseAuth.getInstance() line (sorry but can't remember what exactly) so I changed back all of the versions to 10.0.1 and 1.0.1 and I'm still getting error and my application crashes on start (this error is different than the previous one).
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mnm135.emil.showsmanager, PID: 3837
                  java.lang.NoSuchMethodError: No static method zzdz(Ljava/lang/String;)Z in class Lcom/google/android/gms/common/util/zzw; or its super classes (declaration of 'com.google.android.gms.common.util.zzw' appears in /data/app/com.mnm135.emil.showsmanager-1/base.apk)
                      at com.google.firebase.FirebaseOptions.<init>(Unknown Source)
                      at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                      at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                      at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                      at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                      at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                      at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                      at android.app.ActivityThread.installProvider(ActivityThread.java:5811)
                      at android.app.ActivityThread.installContentProviders(ActivityThread.java:5403)
                      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5342)
                      at android.app.ActivityThread.-wrap2(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I tried Invalidate caches/restart, clean and rerun. Even rebooting my pc. Nothing seems to work.
Any ideas?
Edit:
I tried aaroncio's solution, removed apply plugin: 'com.google.gms.google-services' and I'm getting different error:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mnm135.emil.showsmanager, PID: 5157
                  java.lang.NoSuchMethodError: No static method zzzq()Ljava/lang/String; in class Lcom/google/android/gms/common/util/zzu; or its super classes (declaration of 'com.google.android.gms.common.util.zzu' appears in /data/app/com.mnm135.emil.showsmanager-2/base.apk)
                      at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
                      at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
                      at com.mnm135.emil.showsmanager.base.LoginActivity.onCreate(LoginActivity.java:34)
                      at android.app.Activity.performCreate(Activity.java:6662)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Line mentioned in comment is mFirebaseAuth = FirebaseAuth.getInstance();

A: I solved it removing the line about firebase-authentication in the build-gradle file:
compile 'com.google.firebase:firebase-auth:10.2.1'

I removed the imports about authentication also, I was just making some experiments with firebase auth so its not important in this case, but to others may not be ideal solution.

A: It looks like something changed with the last version of Google Services, I had a similar problem and solved it deleting the following line in gradle:
apply plugin: 'com.google.gms.google-services'


text:
Q: JavaScript: How to push to an array inside an object that was created inside an arrow function So how do I push to the CONSUPTION array? Using THIS is not working and ia have no clue on how to make the ORDER work.
const createMenu = (menu) => ({
        fetchMenu: () => menu,
        consumption: [1,2],
        order: (string) => {
          this.consumption.push(string);
        },
        pay: () => {
          let cont = 0
          const cardapio = { ...menu.food, ...menu.drink}
          for (let itens of this.consumption){
            cont += cardapio[itens];
          };
          return cont;
        },
      });

A: Change the order arrow function to a regular function, it's not a good idea to use it in an object.
The reason for that is because that In regular functions the this keyword represented the object that called the function.
Unlike regular functions, arrow functions do not have their own this. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

const createMenu = (menu) => ({
        fetchMenu: function(){ return menu},
        consumption: [1,2],
        order: function(string)  {
          this.consumption.push(string);
        },
        pay: function() {
          let cont = 0
          const cardapio = { ...menu.food, ...menu.drink}
          for (let itens of this.consumption){
            cont += cardapio[itens];
          };
          return cont;
        },
      });

      const menu = createMenu();
      console.log(menu.consumption);
      menu.order(3);
      console.log(menu.consumption);

More about this in arrow function could be found here


text:
Q: When upscaling pandas dataframe, don't fill beyond time period of each row I run into undesired behaviour when upscaling a dataframe using Python's pandas library.
Example
Let's start with monthly data:
carMonthly = pd.DataFrame(data={'avSpeed': [40.3, 23.4], 'dist': [100, 150]},
                       index=pd.PeriodIndex(['2019-02', '2019-05'], freq='M'))

         avSpeed  dist
2019-02     40.3   100
2019-05     23.4   150

Notive how I'm using a PeriodIndex with monthly frequency.
Wanted outcome
Now, I want to rescale this set to daily values, the following way:

*

*the avSpeed values must be copied over to each of the days of that particular month;

*the dist values must be divided over the number of days in each month (28 for the first row, 31 for the second).

So, my preferred outcome is:
            avSpeed      dist
2019-02-01     40.3  3.571428
2019-02-02     40.3  3.571428
...
2019-02-27     40.3  3.571428
2019-02-28     40.3  3.571428  #until end of February
2019-05-01     23.4  4.838710
2019-05-02     23.4  4.838710
...
2019-05-30     23.4  4.838710
2019-05-31     23.4  4.838710

Notice how March and April are not present. If that's not possible, and the resulting resampling will always include March and April, my second-best outcome is that all rows for those months contain NaN-values.
What does not work
For those interested in what I've tried:
carDaily = pd.DataFrame()
carDaily['avSpeed'] = carMonthly['avSpeed'].resample('D').ffill()
tempSeries = carMonthly['dist'].resample('D').first()
carDaily['dist'] = tempSeries.groupby(tempSeries.notna().cumsum())\
    .apply(lambda x: x/len(x.index)).ffill()

            avSpeed      dist
2019-02-01     40.3  1.123596
2019-02-02     40.3  1.123596
...
2019-04-29     40.3  1.123596
2019-04-30     40.3  1.123596  #until end of April
2019-05-01     23.4  4.838710
2019-05-02     23.4  4.838710
...
2019-05-30     23.4  4.838710
2019-05-31     23.4  4.838710

This is unwanted, as the data for February is stretched all the way till the end of April. Because the original dataset has a monthly frequency, and each row in the carMonthly dataset covers a time period of a month, I would want the copying (of avSpeed) or dividing (of dist) to be limited to those rows in the carDaily dataset that actually lie within the month their data is coming from, as shown under "preferred outcome".
I know why it isn't working: the resampled Series have NaN values for all rows (including March and April) except 2019-02-01 and 2019-05-01, and at that point it's not possible to find out, what the original start_time and end_time of the months were. I just don't know, how to make it work :)
PS: The solution for the dist column is taken from this question.

Edit: solution
With this answer below, I'm now using this code, which allows me to build up the new dataframe column-by-column:
tempDf = carMonthly.groupby(level=0).apply(lambda x : x.resample('D').ffill())
il = tempDf.index.labels[0]
divBy = [sum(il==i) for i in il]

carDaily = pd.DataFrame()
carDaily['avSpeed'] = tempDf['avSpeed']
carDaily['dist'] = tempDf['dist'] / divBy
carDaily.reset_index(level=0,drop=True,inplace=True)

*

*What I like about this solution, is that I only need to calculate the divBy list once (il = FrozenNDArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype='int8')).

*It still works if I upsample from months to hours or from years to months.

*Depends only on pandas as external library.

A: You should resample with in the groupby
s=carMonthly.groupby(level=0).apply(lambda x : x.resample('D').ffill())
s['dist']/=s.groupby(level=0)['avSpeed'].transform('count').values
s.reset_index(level=0,drop=True,inplace=True)


text:
Q: ImportError: cannot import name 'YamlModel' from 'pydantic_yaml' I am working at blender script, where I want to use YAML. So I try to import it:
from pydantic import BaseModel
from pydantic_yaml import YamlModel

But when I run my script, this error will occure:
ImportError: cannot import name 'YamlModel' from 'pydantic_yaml' (C:\Program Files\Blender Foundation\Blender 3.0\3.0\python\lib\site-packages\pydantic_yaml\__init__.py)

I have installed pydantic and pydantic_yaml on both Pythons (Blender one and the common one), if they wouldn't be installed, there would be different error. I tried googling, but google had very few results for this problem. Also, when I open that __init__.py file, there is clearly YamlModel. Thank you for any kind of help.

A: I found the same error and it is related how pydantic-yaml got installed.
There is a bug in the package. you need to install optional dependencies as well (so called extras).
pip install pedantic-yaml[pyyaml,ruamel]

or manually install pyyaml ruamel please make sure that that Taumel version is <=0.18


text:
Q: Is evince-gtk protected by apparmor? The 14.10 software center offers evince and a version called evince-gtk with fewer GNOME dependencies.
In /etc/apparmor.d there is an apparmor profile for evince: /etc/apparmor.d/usr.bin.evince. My question is this: will this profile also protect evince-gtk?

A: The evince-gtk package installs its executable as /usr/bin/evince, so assuming the AppArmor profile is written conventionally, I think the answer you're looking for is yes.
Just to be clear, though, AppArmor isn't protecting evince. It's protecting you and your system from evince.


text:
Q: SAS count a sequence of equal numbers I wish to get last number in a sequence of equal numbers. For example, I have the following dataset:

X
1
1
0
0
0
1
1
0

Given that sequence of numbers I need extract the last number of a sequence of "ones" until appear a 0. That is what I want:

X Seq
1 1
1 2
1 3
0 1
0 2
0 3
1 1
1 2
0 1
1 1
1 2
1 3
0 1

I need create a new dataset with the numbers in bold, that is:

Seq1
3
2
3

Thanks for any advice.

A: Use a proc summary with notsorted option here:
data math;
input x;
datalines;
1
1
1
0
0
0
1
1
0
1
0
1
1
1
1
0
1
;
run;

proc summary data=math;
by x notsorted;
class x;
output Out=z;
run;

data z (drop=_type_ x);
set z (rename=(_FREQ_=COUNT));
where _type_=1 and x=1;/*if you are looking for other number then 1, replace it here*/
run;
proc print data=z noobs;
run;

result is:

A: You can create group variables using a lag and then keep the last observation of each group you have created:
data temp;
   input x $;
   datalines;
    1
    1
    1
    0
    0
    0
    1
    1
    0
    1
    1
    1
    0
    ;
run;

data temp2;
    set temp;
    retain flag;
    if lag(x) > x then flag = _n_;
    if x = 0 then delete;
run;

data temp3 (keep = seq1);
    set temp2;
    seq1 + 1;
    by flag;
    if first.flag then seq1 = 1;
    if last.flag then save = 1;
    if missing(save) then delete;
run;

A: Here's a solution using only one data step with a retain statement.
data have;
  input x @@;
  output;
  datalines;
1 1 1 0 0 0 1 1 0 1 0 1 1 1 1 0 1
;

data want(keep = count);
  set have end = last;
  retain x_previous . count .;

  if x = 0 then do;
    if x_previous = 1 then do;
      output;
      count = 0;
    end;
  end;

  else if x = 1 then count + 1;

  if last = 1 and count > 0 then output;

  x_previous = x;
run;

Results
count
-----
3
2
1
4
1

A: One more option - use the NOTSORTED BY group option.
Data want;
Set have;
 By x NOTSORTED;

 Retain count;

 If first.x then count=1;
 Else count+1;

 If last.x then output;

 Keep count;
 Run;


text:
Q: JSF behind Apache with SSL - h:commandLink with and without f:ajax [Edit] - Thanks for the comments.  I've tried to shape my question accordingly and I've added some additional information based on the suggestions offered.
I have a JSF web application running on JBoss AS7 that I front with Apache on SSL (port 443).  Apache and JBoss are running on the same machine and communicate "in the clear" over HTTP with reverse proxy forwarding rules.  With this setup, I have observed that clicking on any link created via the JSF tag <h:commandLink> (i.e. without <f:ajax> and where there is always a genuine backing bean action method that, after performing some business logic, returns an outcome with the ?faces-redirect=true suffix) will see the page redirect fail because the https scheme is dropped and replaced with http.
If I replace all instances of <h:commandLink> with <h:commandLink><f:ajax/></h:commandLink>, this redirection problem goes away - i.e. the https scheme is preserved in the resulting redirected URL.
Could anyone explain to me what I'm observing and what the "under-the-hood" difference between the non-ajax form submit and ajax submit might be in this case?
Additional Information:
My Apache reverse proxy rules:
ProxyRequests Off
ProxyPreserveHost On

<Proxy *>
Order Allow,Deny
Allow from all
</Proxy>

ProxyPass / http://localhost:8080/ timeout=1800
ProxyPassReverse / http://localhost:8080/

The web console in Firefox shows the difference between the ajax form submit and non-ajax form submit HTTP requests as:
Ajax submit via <h:commandLink><f:ajax/></h:commandLink>
I see a GET request to the expected page on https (I can't yet post screen shots)
Non-ajax submit via <h:commandLink/>
The non-ajax version first POSTs back to the same page (which is expected) on https with a 302 status code 'Moved Temporarily' and then redirects to the target page from the action method on http.
Location in HTTP header for POST before failed GET redirect on http
Here's a screen shot.  The location value for the POST shows as the URL of the GET request, on http and not https:

I guess I've gotten slightly "under-the-hood" at this point.  Since the <f:ajax> approach achieves the desired result, I am happy leaving this alone.  It seems there are at least a few other JSF posts related to this same sort of thing (here's the single URL I'm allowed to post):
JSF redirects from HTTPS to HTTP
Maybe the ajax-based approach is required to preserve the scheme in the URL originating from the client?
Thanks,
-Andy


text:
Q: Help with applying thales theorem Given: $MN||AB$ And $MO:AO = 3 : 5$ Find $CN:NA$ Here is drawing:

I'm sure I have to apply the basic proportional theorem, however I don't see how. The answer is $3:2$

A: Using that $\triangle{NOM}$ and $\triangle{BOA}$ are similar and that $\triangle{CNM}$ and $\triangle{CAB}$ are similar, we have
$$CN : CA=NM : AB=MO : AO=3 : 5$$
The result follows from this.

A: Let $\frac{CN}{NA} = \frac{CM}{MB} = \frac ab$. Then we have: $\frac{CB}{MB} = \frac{a+b}{b}$. Now using Menelaus Theorem on $\triangle MAC$ and line $N-O-B$ we obtain:
$$\frac{AN}{CN} \times \frac{CB}{MB} \times \frac{MO}{AO} = 1$$
Substituting the given values we get that $\frac ab = \frac 32$


text:
Q: Stop send value to next function I have this working code:
/* Include files */
#include <iostream>
#include <string>
#include <limits>

using namespace std;

void fnMainMenu(char s);

/******************************************************************************
* Function: fnUpdateSalary
* Description: Update employee salary
******************************************************************************/
void fnUpdateSalary()
{
    int choice = 0;
    char data = 'a';
    incorrect_input: // goto teleport exit :)
    cout<<"\n\t=======================";
    cout<<"\n\tWelcome\n";
    cout<<"\t=======================\n\n";
    cout<<"1. Update employee salary\n";
    cout<<"2. Main menu\n";
    cout<<"3. Exit system\n";
    cout<<"\n >> ";

    cin>>choice;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(),'\n');

    switch(choice){
        case 1 :
            //fnUpdateSalary();
            break;
        case 2 :
            fnMainMenu(data);
            break;
        case 3 :
            exit(1);
            break;
        default :
        cout<<"Input not recognized. Please enter the correct input.\n";

    }
}

void fnLog()
{
 char data = 'b';
fnMainMenu(data); // call Main Menu and I want to pass "hello"
}

/******************************************************************************
* Function: fnMainMenu
* Description: Menu for the customer
******************************************************************************/
void fnMainMenu(char s)
{
     cout << s;

if (s == 'a')
{ cout << "a = admin";
}
else
{cout << "\n\nb not admin";
}

    //system("cls");
    int chooice = 0;

    cout<<"\n\t=======================";
    cout<<"\n\tWelcome\n";
    cout<<"\t=======================\n\n";
    cout<<"1. Manage employee\n";
    cout<<"2. Search employee\n";
    cout<<"3. Employee report\n";
    cout<<"4. Reset password\n";
    cout<<"5. Exit system\n";
    cout<<"\n >> ";
int numbers = 2;
    cin>>chooice;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(),'\n');

    switch(chooice){
        case 1 :
            fnUpdateSalary();
            break;
        case 4 :
        //  fnChangePassword();
            break;
        default : exit(1);

    }
}

/******************************************************************************
* Function: main
* Description: The main calling function
******************************************************************************/
int main()
{

    fnLog();
    return 0;
}

fnLog() send b to fnMainMenu(). When I am at fnUpdateSalary() I want to go to fnMainMenu() again. My question is, is there anyway from fnUpdateSalary() or whatever function available to call fnMainMenu() without declaring variable data again? I was hoping I could just use fnMainMenu(); instead of
char data = 'r'; fnMainMenu(data);

I get this error error C2660: 'fnMainMenu' : function does not take 0 arguments if I just called fnMainMenu();
I hope my question make sense. Thanks in advance.

A: The parameter doesn't seem to serve a real purpose anyway. Passing b into the main menu function certainly achieves nothing. If you just want to distinguish between admin and non-admin access, change the type and usage of the argument:
void fnMainMenu(bool is_admin) {
    if (is_admin)
        cout << "Admin\n";
    else
        cout << "Not admin\n";
}

And call it like this:
fnMainMenu(true);
// Or, alternatively:
fnMainMenu(false);

That's it. Incidentally, you don't need (and shouldn't!) declare a variable to pass as the argument here. Just pass the value directly, like I've done above.
Also, why are your function names prefixed by fn? Don't do this, it's not good practice. Just use proper names that explain well what the functions do.

A: Since you're writing C++ code and data seems to be relatively long-lived with respect to the application logic, it would perhaps make sense to regroup these functions into a class.
data could be a data member of this class, and fnUpdateSalary, fnLog, fnMainMenu methods.
class Application {
public:
  Application ()
  : data ('b') // default value
  { }

  void fnLog() {
    data = 'b';
    fnMainMenu ();
  }

  void fnMainMenu() {
    if (data == 'a')
      cout << "a = admin";
    else
      cout << "\n\nb not admin";

    // ...
    fnUpdateSalary ();
    // ...
  }

  void fnUpdateSalary() {
    // ...
    fnMainMenu ();
    // ...
  }

private:
  char data;
};

int main () {
  Application app;
  app.fnLog ();
}

A: If I fully understand what you are doing, you need a combination of two things. Firstly, a static variable in fnMainMenu and secondly a default parameter:
fnMainMenu(char s = '\0')
{
  static char c;
  if(s != '\0') c = s;
  ...
  ...
}

The "static" keyword means that the character will be preserved across function calls. The default parameter means that s will be assigned a null termination character unless you explicitly pass another value.


text:
Q: Copy files with MsBuild I have a solution with two projects. One of them is a simple project that doesn't depend on any special assemblies to build. However, the application is allowed to launch an external executable (that I also own -- this is the second project of my solution). When I build the project, I would like the executable (+ dependencies such as app.config) of the external project to be copied under the target directory of my project.
How can I achieve this with MsBuild? My first idea was to add a reference to the executable (even though I don't need it to build) to copy the file. This seem a bit hacky to me.
Thanks!
P.S. Another question: Let's say that I can tell MsBuild to copy the executable. What if the executable isn't build? Can I force it to build?

A: In your case you should make your MSBuild script replace your solution and declare the desired dependency there:
<Project DefaultTargets="Executable_A">
    <Target Name="Executable_A" DependsOnTargets="Executable_B">
        <MSBuild Projects="Executable_A.proj" Targets="Build" />
    </Target>

    <Target Name="Executable_B">
        <MSBuild Projects="Executable_B.proj" Targets="Build">
            <Output TaskParameter="TargetOutputs" ItemName="AssembliesBuilt" />
        </MSBuild>
        <Copy SourceFiles="@(AssembliesBuilt)" DestinationFolder="C:\My_Target_Path\" SkipUnchangedFiles="true" />
    </Target>
</Project>

... and you can instruct the target of your second project to copy its output to the desired location. You could even instruct your first project to store its output path into a variable to use when copying the output of your second project (DestinationFolder).

A: Have you looked the MSBuild Copy Task: Copy Task ?

A: If you will be satisfied with @Filburt answer I can suggest to improve this solution.
If you'll take a look how default Build target works:
 <Target
    Name="Build"
    Condition=" '$(_InvalidConfigurationWarning)' != 'true' "
    DependsOnTargets="$(BuildDependsOn)"
    Returns="$(TargetPath)" />

You'll see that the only output from build or rebuild target is $(TargetPath).
$(TargetPath) is a full path to the built assembly. To change this behaviour you can hack build process. But it will be match simpler to define your own target in project B:
<Target
    Name="BuildWithConfig"
    DependsOnTargets="Clean;Build"
    Returns="$(TargetPath);$(TargetPath).config" />

In A project just define AfterBuild target:
<Target Name="AfterBuild">
    <MSBuild Projects="Executable_B.proj" Targets="BuildWithConfig">
        <Output TaskParameter="TargetOutputs" ItemName="AssembliesBuilt" />
    </MSBuild>
    <Copy SourceFiles="@(AssembliesBuilt)" DestinationFolder="$(OutDir)\SubDirForB" SkipUnchangedFiles="true" />
</Target>

This solution doesn't require to create custom build script. You will get the result directly in VS.


text:
Q: Duplicate_Rule_Atomic or non Atomic I have a question on duplicate rule.I am loading a list of account records in to my salesforce org using jitterbit and to eliminte the insertion of duplicate records I have a duplicate rule enabled on my account object.
My question is if i have 100 records, if duplicate is found at 50 th record, is it possible to elimate the duplicate and continue to insert the remaining 50 records using duplicate rule?
if not please suggest me a sol to achieve this funtionality

A: I think it mostly depends on Jitterbit of How it handle the error records and Not with duplicate rules.
Normal data loader when face error with few records they skip those records and insert the other records in the system. So Jitterbit might also provide similar solution( I have never used it before so not quite sure here.).
The thing which might give you some trouble here is
As per Duplicate Rule docs:

If you're saving multiple records at the same time and your duplicate
  rules are set to Block or Alert, records within the same save aren't
  compared to each other; they are only compared with records already in
  Salesforce.

So if there are multiple records in same chunk then you won't get any error or warning in that case.


text:
Q: incorrect syntax near System.Data.DataRowViev I have DatagridView that is connected with combobox control. combobox is used to filter data from a table. combobox and data in  Datagridview are from the same table. i look out for error but a couldn't find. it says:
incorrect syntax near System.Data.DataRowViev
and I click on the ok button and  then other error:
the connection wasn't closed. the connection's current state is open.
please help
        private void VraboteniPoOpstini_Load(object sender, EventArgs e)
       {

            try
            {
                con.Open();
                ad = new System.Data.SqlClient.SqlDataAdapter("Select * from tbl_PersonalniPodatoci ", con);
                ds = new DataSet();

                ad.Fill(ds, "tbl_PersonalniPodatoci");
                dt = ds.Tables["tbl_PersonalniPodatoci"];
                con.Close();

                //fill combobox
                cbOpstini.DataSource = dt;
                cbOpstini.DisplayMember = "Opstina";
                cbOpstini.ValueMember = "Sifra";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ГРЕШКА", MessageBoxButtons.OK);
            }

        }

        private void cbOpstini_SelectedIndexChanged(object sender, EventArgs e)
        {
            string izberiOpstina = cbOpstini.SelectedValue.ToString();
            string sSql;
            try
            {
                con.Open();
                //datagridview
                sSql = "Select  Sifra, Prezime, Ime, Opstina From tbl_PersonalniPodatoci Where Opstina'" + izberiOpstina + "' Order by Sifra";
                ad = new System.Data.SqlClient.SqlDataAdapter(sSql, con);
                SqlCommandBuilder cb = new SqlCommandBuilder(ad);
                DataTable dt = new DataTable();
                ad.Fill(dt);

                con.Close();

                // fill datagridview
                grdOpstini.DataSource= dt;

            }
            catch (Exception ex )
            {
                MessageBox.Show(ex.Message, "ГРЕШКА", MessageBoxButtons.OK);
            }

        }

A: As Henk already said - you need to take more care for your connections, how you open and close them. Also: if you use the SqlDataAdapter, there's really no need for you to manually open the connection and close it again - the data adapter will do this automatically for you.
And also: in the first example, you only need a single data table, yet you create a data set and then extract the table from it - that's totally unnecessary overhead.
Try something like this:
private void VraboteniPoOpstini_Load(object sender, EventArgs e)
{
   try
   {
       // add a "using System.Data.SqlClient" to your file, to make this simpler
       ad = new SqlDataAdapter("Select * from tbl_PersonalniPodatoci ", con);

       DataTable dt = new DataTable();
       ad.Fill(dt);

       //fill combobox
       cbOpstini.DataSource = dt;
       cbOpstini.DisplayMember = "Opstina";
       cbOpstini.ValueMember = "Sifra";
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message, "ГРЕШКА", MessageBoxButtons.OK);
   }
}

You can do a similar approach (use DataTable right away, no need to open and close SqlConnection when using SqlDataAdapter etc.) for your second query.


text:
Q: EF/Code First Migration - implicit table mappings? I am using a code first migration approach to creating new tables in an existing database, and I'd like to know if this is auto-creating a property-to-field mapping somewhere in the project.
For example: the "Category" table pre-existed in the database. It was created directly in SQL, and my MCV project has a CategoryMap.cs file that explicitly maps the Category entity properties to the Category table fields:
CategoryMap.cs
this.ToTable("Category", "ctt");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.ClientId).HasColumnName("ClientId");
this.Property(t => t.CategoryTypeId).HasColumnName("CategoryTypeId");
etc.

The db context class explicitly points to this mapping in the OnModelCreating method:
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Configurations.Add(new CategoryMap());
etc.

With this set-up, I can save data to the Category table, as long as I keep the mapping pieces in place.
On the other hand, I've created a new table using the code first approach:
1) Create a "MyTable" entity class
2) Add this code to my context class:
public DbSet<MyTable> MyTable { get; set; }

3) Run the add-migration and update-database commands
That created a "MyTable" table in the database schema, and I can save data to this table, despite the fact that there is no mapping file, and no explicit mapping code in the OnModelCreating method of my db context class.
Now, if I comment out the "modelBuilder.Configurations.Add(new CategoryMap());" line of code in the context class, I can't save data to that table any more; I get a "table 'Category' not found" error message when I try to do db.SaveChanges().
So I guess my question is this: when I created "MyTable" using the add-migration and update-database commands, did a class-to-table map get auto-generated somewhere behind the scenes? If so, can I access it and view it?

A: There are no auto generated mappings as such but a number of mapping conventions that get applied if there are no specific mappings. For example if you have no explicit table mapping then by convention it will map to a table that matches the class name.
So for a class Category it will by convention map to a table called Category.
This is also true of properties so Property(t => t.Id).HasColumnName("Id"); doesn't actually do anything as the property will have that mapping by convention. You only need explicit mappings when you go outside the conventions. So if you wanted to map you property Id to a column called Category_id then you would need a column mapping  Property(t => t.Id).HasColumnName("Category_id");
Read this MSDN article for more info on the default conventions.


text:
Q: initialization of data types in a std vector OK I am currently building a matrix using the std vectors that is meant to have a cell or bacteries on them. Because of this I made a "dead" class to be mother of cell and bacteries. So in the matrix a case that does not have either of them would be dead.
But when I try to build the matrix, by somthing like:  world[x][y] = new cell()/world[x][y] = new bacterie();  it will not compile.
so my question is, how can I initialize it?
this is my code, its on spanish sorry.
matrizB[fila-1][columna-1] =  new BacteriaM();

matrizB its a
vector<vector <dead>> matrizB(n);

and BacteriaM is a class that inherits from dead; n is defined by the user.
(sorry for bad grammar and programing, i'm new to programing)

A: In order to use polymorphism, your matrix element must be a pointer.
vector<vector <dead*>> matrizB(n);

You will have to be careful to manage the memory of the elements. It might be worth looking at smart pointers (std::shared_ptr or std::unique_ptr -- whichever is more correct).
Hope this helps.

A: The main issue that you are having is the new operator. I am assuming you are not accustomed to C++ when it comes to creating objects. The new operator for C++ does not simply create an object, but a pointer to an object. So, you can go matrix[x][y] = cell() or change to a vector< vector < dead* > > and follow what @Duthomhas says with selecting smart pointers. That way you can better manage memory especially when you are dealing with a vector of vectors.
Note: Watch out for cell() constructors! C++ will get confused and think you are declaring a function...


text:
Q: Add column name to array I have this array:
[
    [
        "302260",
        "302250",
        "302248",
    ],
    [
        "Bruce Willis",
        "Jackie Chan",
        "Gary Oldman",
    ],
]

I need insert multiple this values, I found this answer: How to insert multiple rows from a single query using eloquent/fluent, but I don't know how I can add column name to my array, to make it look like this:
[
    [
        "user_id" => "302260",
        "user_id" => "302250",
        "user_id" => "302248",
    ],
    [
        "name" => "Bruce Willis",
        "name" => "Jackie Chan",
        "name" => "Gary Oldman",
    ]
]

I can't use array_map, because I have different values in the key: 1, 2, 3

A: An array key needs to be unique within an array. e.g. you can't have multiple keys called user_id within a single array. What you can do instead is have an array in the following format:
Array
(
    [1] => Array
        (
            [user_id] => 1
            [name] => User1
        )

    [2] => Array
        (
            [user_id] => 2
            [name] => User2
        )
)

That's also what the answer you're linking to describes.
The php code for the above array looks like this:
$users = array(
  1 => array("user_id" => 1, "name" => "User1"),
  2 => array("user_id" => 2, "name" => "User2"),
);


text:
Q: How to build sound card drivers? I downloaded the drivers for my sound card (XFiDrv_Linux_Public_US_1.00.tar.gz) from a website. The readme file says:

Quick install
In terminal,

*

*Goto source directory

*Execute make command as root
make
make install

I'm not sure what it means. What exactly do I need to do?


text:
Q: ImageIO Exception I am getting the following error:
javax.imageio.IIOException: Can't read input file!
Resource not found: C:\icon.gif
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at connector.SystemTrayCreator.createImage(SystemTrayCreator.java:98)
at connector.SystemTrayCreator.create(SystemTrayCreator.java:36)
at connector.Start.main(Start.java:14)
Exception in thread "main" java.lang.IllegalArgumentException: creating TrayIcon with     null Image
at java.awt.TrayIcon.<init>(TrayIcon.java:168)
at connector.SystemTrayCreator.create(SystemTrayCreator.java:36)
at connector.Start.main(Start.java:14)
Java Result: 1

Out of the following code:
final TrayIcon trayIcon =
            new TrayIcon(createImage("C:\\icon.gif", "Tray icon"));

with
protected static Image createImage(String path, String description) {
    Image image = null;

    try {
        File f = new File(path);
        image = ImageIO.read(f);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (image == null) {
        Debugger.showMessage("Resource not found: " + path);
        return null;
    } else {
        return (new ImageIcon(image, description)).getImage();
    }
}

I am quite sure that the path is correct. Also, the names match.
Anyone knows what's wrong?

A: Your code seems fine. Two things currently occur to me as theoretically possible problems:

*

*A file permission problem. Maybe place the file somewhere else than the drive root and check explicitly its permissions. You may call canRead() directly from your code -- that's what ImageIO.read does. It must return true.

*There could be some whitespace at the end of your path argument. Use trim() to eliminate that possibility.


text:
Q: Screen blinking on moving cursor from one monitor to another I have a dual monitor setup at work and when moving the cursor from one monitor to the other the screen blinks and sometimes gets completely black.
I've recorded a video to better show the problem:
https://vid.me/vgEE
I just upgraded to Ubuntu 16.04 (clean install). This wasn't happening in 15.10.

A: Hello i had the same problem but solved it by installing latest upstream kernel from here. At this link you can find installing instruction. Right now i use 4.6.0rc4 and it works well.

A: This is a bug.
The issue is fixed in 4.4.0.38 kernel.


text:
Q: Es posible trabajar código en el servidor desde XAMPP ¿Es posible vincular el host donde esta mi proyecto con mi editor de codigo?; es decir, existe alguna manera en la que trabajando desde mi XAMPP en Visual studio, Sublime, etc pueda guardar los archivos y al mismo tiempo estos se actualicen en el servidor donde tengo alojado el proyecto?

A: En el caso de Sublime Text existe un plugin llamado SFTP para tener un FTP persistente, con él se puede editar directamente en el hosting, pero ya no tendría sentido que tengas Xampp pues lo editado estará en tu hosting.
Deberías explicar para qué deseas realizar ese tipo de conexión.
Al utilizar GitHub, por ejemplo, las pruebas las realizas en tu equipo con Xampp (por ejemplo) y luego se suben directamente al repositorio de GitHub. Pero algo así no conozco para un hosting.

A: @aguevara33, Si se puede realizar la instalación y ocupar con Xampp o Apache Server por ejemplo, pero de todas maneras tendrías que instalar el modulo mod_wsgi. Pero debes tener en cuenta que en la documentación oficial de Django advierten que no es seguro poner los proyectos en la carpeta xampp/htdocs como se hace con los Frameworks de Php por ejemplo.

En la sección 3.1.2 de la documentación que se puede descargar en formato PDF explican como instalar Django con Apache y mod_wsgi

Esta información la puedes encontrar en la pagina oficial de Djangohttps://docs.djangoproject.com/en/3.0/topics/install/

Saludos


text:
Q: Differences between ipython %run and promt I've the following simple erroneous code
from numpy import random, sqrt
points = random.randn(20,3);
points = points / sqrt(sum(points**2,1))

In ipython (with %autoreload 2) if I copy and paste it into the terminal I get a ValueError as one would expect. If I save this as a file and use %run then it runs without error (it shouldn't).
What's going on here?

A: I just figured it out, but I had written the question and it might be useful to someone else.
It is a difference between the numpy sum and the native sum. Changing the first line to
from numpy import random, sqrt, sum

fixes it as %run uses the native version by default (at least with my settings). The native run does not take an axis parameter, but does not throw an error either, because it is a start parameter, which is in effect just an offset to the sum. So,
>>> sum([1,2,3],10000)
10006

for the native version. And "axis out of bounds" for the numpy one.


text:
Q: big calendar react Can we have multiple color on different dates of Month? big calendar react Can we have multiple color on different dates of Month?
Suppose: Every Date on month will have different color according to its events.

A: The dayPropGetter does allow you to set styling in the month view, according to date, but it does not have access to other calendar props (like events)
Method signature:
(date: Date) => { className?: string, style?: Object }

Usage:
const dayPropGetter = (date) => {
  // build some className from the `date` and/or
  // build some style definition from the `date` data
  return { className, style }
}

<Calendar dayPropGetter={dayPropGetter} />

So, if you wanted to highlight every Wednesday, or weekend days, or 'today' in some manner, you could use this to do that.


text:
Q: Python Telethon (Telegram) keeps erroring out with "too many requests" I am lookign for some advice on the Telethon python library which gave me some pain lately. This is could be a commercial opportunity, so if you are vary experienced particularly in Telethon, please do not hesitate to get in touch.
So, the code I wrote worked fine at first. I used several tg accounts (numbers) to message users and had a large time delay between each two messages. However, a few days ago I started getting "too many requests" error after several weeks of successful operation (I had to replace some phone numbers along the way but nothing dramatic). And, this error didn't go away since. I tried using VPN to avoid my old IP, I tried creating new API credentials from a different phone number and/or different IP address, I tried creating brand new tg accounts. Nothing worked. Even the brand new accounts are shut off as "too many requests" and get banned immediately after. I tried recreating and running the whole process on a different person's machine to make sure I took everything into account. No progress.
So, does anyone know if telegram has simply dropped telethon access for messaging or am I missing something really important here. Thanks! Your help will be massively appreciated.

A: Send messages in a telegram to an unknown user - the limit is 50 messages per day.
When the limit exceeds, it will throw a "Too many requests" error


text:
Q: Magento admin event after invoice save I'm trying to add some functionaltiy after generating invoice by magento store owner for orders. I'm using the following code
<sales_order_invoice_save_after>
    <observers>
        <sales_order_invoice_save_after_handler>
            <type>model</type>
            <class>invoice/observer</class>
            <method>saveinvoiceno</method>
        </sales_order_invoice_save_after_handler>
    </observers>
</sales_order_invoice_save_after>

Issue
Above code is also working PayPal payment, but i want to execute it for admin only.
Any suggestion or help?
Thank you in advance.

A: If it should be for admin only, you have to put it inside adminhtml node:
<?xml version="1.0"?>
<config>
    <modules>
        ...
    </modules>
    <global>
        ...
    </global>
    <adminhtml>
        <events>
            <sales_order_invoice_save_after>
                <observers>
                    <sales_order_invoice_save_after_handler>
                        <type>model</type>
                        <class>invoice/observer</class>
                        <method>saveinvoiceno</method>
                    </sales_order_invoice_save_after_handler>
                </observers>
            </sales_order_invoice_save_after>
        </events>
    </adminhtml>
</config>


text:
Q: Can't install pylibmc by pip I'm trying to install pylibmc on mac.
mac env is osx el capitan 10.11.2.
I tried pip install pylibmc. but I received following error.
I already installed list below.

*

*brew install libmemcached

*Command Line Tools

*export CFLAGS=-Qunused-arguments  @shell

*export CPPFLAGS=-Qunused-arguments  @shell

How can I install pylibmc??
Installing collected packages: pylibmc
Running setup.py install for pylibmc
Complete output from command /Users/username/.virtualenvs/django-proj/bin/python2.7 -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-goDKgm/pylibmc/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-wxC5F1-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/username/.virtualenvs/django-proj/bin/../include/site/python2.7/pylibmc:
running install
running build
running build_py
creating build
creating build/lib.macosx-10.11-x86_64-2.7
creating build/lib.macosx-10.11-x86_64-2.7/pylibmc
copying pylibmc/__init__.py -> build/lib.macosx-10.11-x86_64-2.7/pylibmc
copying pylibmc/__main__.py -> build/lib.macosx-10.11-x86_64-2.7/pylibmc
copying pylibmc/client.py -> build/lib.macosx-10.11-x86_64-2.7/pylibmc
copying pylibmc/consts.py -> build/lib.macosx-10.11-x86_64-2.7/pylibmc
copying pylibmc/pools.py -> build/lib.macosx-10.11-x86_64-2.7/pylibmc
copying pylibmc/test.py -> build/lib.macosx-10.11-x86_64-2.7/pylibmc
running build_ext
building '_pylibmc' extension
creating build/temp.macosx-10.11-x86_64-2.7
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DUSE_ZLIB -I/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _pylibmcmodule.c -o build/temp.macosx-10.11-x86_64-2.7/_pylibmcmodule.o -fno-strict-aliasing
In file included from _pylibmcmodule.c:34:
./_pylibmcmodule.h:42:10: fatal error: 'libmemcached/memcached.h' file not found
#include <libmemcached/memcached.h>
         ^
1 error generated.
error: command 'clang' failed with exit status 1

A: first you need to install
brew install libmemcached

than install python package by this command
pip install pylibmc --install-option="--with-libmemcached=/usr/local/Cellar/libmemcached/1.0.18/"

A: Install dev package:
sudo apt-get install libmemcached-dev
sudo apt-get install zlib1g-dev

then install with pip the python package :
pip install pylibmc

Check documentation for requirements

A: three steps including automatically start memcached server when restarting computers

*

*brew install libmemcached

*pip install pylibmc

*ln -s /usr/local/Cellar/memcached/1.4.24/homebrew.mxcl.memcached.plist ~/Library/LaunchAgents/  (note: you need to modify the version no to your own one, here is 1.4.24)

*launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.memcached.plist  (note: if you do not want auto-start memacached server later, you can use unload command)

A: Update to @Atul's accepted answer above -- first you need to install
brew install libmemcached
then check version installed with
ls /usr/local/Cellar/libmemcached
(As of today 1.0.18_2 is the latest)
Now install python package by substituting above version in this command
pip install pylibmc --install-option="--with libmemcached=/usr/local/Cellar/libmemcached/<version>"
e.g.
pip install pylibmc --install-option="--with libmemcached=/usr/local/Cellar/libmemcached/1.0.18_2/"


text:
Q: How do I link Intel MKL and libdl with gold linker? I'm having a problem linking Intel MKL and libdl using the gold linker on CentOS:
When I run this script:
#!/bin/bash

MKL_INC=$MKL_INSTALL_DIR/include
MKL_LIB=$MKL_INSTALL_DIR/lib

. /opt/rh/devtoolset-6/enable

cat > t.c << end_mkltest

#include <dlfcn.h>
#include "mkl_service.h"

int main() {
    dlerror();              /* use libdl */
    mkl_set_num_threads(1); /* use mkl   */
}

end_mkltest

gcc -I$MKL_INC -c t.c -o t.o
gcc -L$MKL_LIB -fuse-ld=gold t.o -lmkl_rt -ldl

I get:
libmkl_rt.so: error: undefined reference to 'calloc'
libmkl_rt.so: error: undefined reference to 'realloc'
libmkl_rt.so: error: undefined reference to 'malloc'
libmkl_rt.so: error: undefined reference to 'free'

We're using:
CentOS 7.3
devtoolset-6
mkl-2017.2.174.tar.bz2

Any ideas?

A: This should work.  Can you post the linker command shown by this command?
gcc -v -L$MKL_LIB -fuse-ld=gold t.o -lmkl_rt -ldl

(Sorry, can't post this as a comment due to lack of reputation.)


text:
Q: Is there a way to enable syntax highlighting on dyplr/tidyverse commands? I am currently using dplyr on RStudio and I often find it difficult to read my code.
For example, in the following code block, all my dplyr functions have normal white highlighting:

I would like things like summarise and mutate to appear pink or something like that, that way I can easily see what commands I use.
I have the same issue with ggplot which is also part of tidyverse. Sometimes the graphs and figures I make can get quite chunky and I have trouble following what I wrote.
Thanks


text:
Q: Telerik-mvc menu: align an individual element to the right? In an asp.net-mvc-3 project, I'm going to be using Telerik Extensions.
Right now, I'm looking at their Menu ( http://demos.telerik.com/aspnet-mvc/menu ), and wondering if one could align the last item to the far right of the bar, but leaving the rest stacked to the right.
The documentation of Menu explains how to reverse the alignment of the whole Menu, but neither it nor the MenuItem show any obvious way to control their layout.
Is this possible?
Many thanks!

A: You could add a CssClass to the last menu item and style it to to the right.
Check the .HtmlAttributes object of the menu item api.
ci.Add().Text("Categories")
  .Url(Url.Action("Categories", "ProductCategories"))
  .HtmlAttributes(new { @class="last"});


text:
Q: Using Compute module in "Google Cloud Client Library for Python" I am looking at using google cloud python SDKs to manage my resources. I am not able to find compute module in the python SDK.
Python Doc here: https://googlecloudplatform.github.io/google-cloud-python/latest/
However compute module is available in Node.js SDK.
Node.js Doc here: https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-cloud/0.56.0/compute
Can I get information if this module(compute) is available in python?
If not is this being planned and when can I expect it.

A: The google-cloud-python project you link to is hand-crafted pythonic libraries for GCP APIs. There is not yet one for Compute.
Instead you will have to use the auto-generated Python client library. See https://cloud.google.com/compute/docs/tutorials/python-guide for an example.


text:
Q: Bundling Javascript into a GWT app I'm writing an app in GWT (mapfaire.com) which uses the Google Maps API, and I'd like to use the utilities library. Writing a JSNI wrapper for the libraries isn't a problem, but how do I ensure the compiler 'bakes' the JS into the app itself, rather than downloading them separately via a module script include?

A: You could define a ClientBundle for your JavaScript resources like this:
public interface JsResources extends ClientBundle {
    final JsResources INSTANCE = GWT.create(JsResources.class);

    @Source("myAwesomeJavaScript.js")
    TextResource myAwesomeJavaScript();
}

and include it in your app with the ScriptInjector:
ScriptInjector
    .fromString( JsResources.INSTANCE.myAwesomeJavaScript().getText() )
    .inject();

A: In gwt 2.4 added ScriptInjector
http://gwt-code-reviews.appspot.com/1451818/
   ScriptInjector.fromUrl("http://example.com/foo.js").setCallback(
     new Callback<Void, Exception>() {
        public void onFailure(Exception reason) {
          Window.alert("Script load failed.");
        }
        public void onSuccess(Void result) {
          Window.alert("Script load success.");
        }
     }).inject();

A: If the license allows you to do so, then you could copy and paste the entire JS code of the library into a JSNI method.
You can also use a TextResource like this:
public static interface Resources extends ClientBundle {
    @Source("some.js")
    TextResource someJs();
}

public void onModuleLoad() {
    final Resources resources = GWT.create(Resources.class);
    eval(resources.someJs().getText());
}

private static native void eval(String s) /*-{
    eval(s);
}-*/;

The text of "some.js" will be interned directly into the resulting application. There won't be any separate download.

A: Is the gwt-maps-utility project useful for your needs?


text:
Q: setar valor pela função success ajax jquery Na função success não estou conseguindo setar um valor de uma div com o conteúdo da variável data
$(document).on("click", ".js-busca-previsao-chegada", function(event) {
    event.preventDefault();
    var familia = $(this).attr("js-familia");
    var esferico = $(this).attr("js-esferico");
    var cilindrico = $(this).attr("js-cilindrico");
    $
        .ajax({
            async: false,
            type: "GET",
            url: "/buscaprevisaochegada",
            dataType: 'json',
            data: {
                "familia": familia,
                "esferico": esferico,
                "cilindrico": cilindrico

            },
            success: function(data) {
                $("#js-tooltip-previsao").text(data);
            }
        });
});


text:
Q: Floating point inaccuracies breaks idempotence in weird ways I was wondering how bad floating point inaccuracies can get when normalizing vectors, specifically a 3D one. Normalizing once should give the same value as normalizing twice, but, as expected, floating point inaccuracies don't guarantee us that. So I decided to test some other things: if you normalize indefinitely, will it always "converge" to a value that normalizes to itself? The answer is no. For example, a few seconds testing and I found a value that loops between 2: -0.60445204839058564 -0.54547899327834748 -0.58059485795902943 and -0.60445204839058575 -0.54547899327834759 -0.58059485795902954. Some "converge" after 3, 5 steps. Here's my boring code:
#include <iostream>
#include <numeric>
#include <random>

using namespace std;

struct Point
{
    double x, y, z;
    bool operator==(const Point& o) const
    {
        return
            x == o.x &&
            y == o.y &&
            z == o.z;
    }
};

auto square(auto x)
{
    return x * x;
}

Point normalize(const Point& p)
{
    auto l = sqrt(square(p.x) + square(p.y) + square(p.z));
    return { p.x / l, p.y / l, p.z / l };
}

std::mt19937 mt(24);
std::uniform_real_distribution d(-1., 1.);

int main()
{
    while (true)
    {
        auto
            x = d(mt),
            y = d(mt),
            z = d(mt);

        Point p{ x, y, z };

        auto
            n1 = normalize(p),
            n2 = normalize(normalize(p));
        int cnt = 1;
        while (n1 != n2)
        {
            n1 = n2;
            cnt++;
            n2 = normalize(n2);
            auto len = square(n2.x) + square(n2.y) + square(n2.z);
            if (len != 1.)
            {
                __debugbreak();
            }
        }
        if (cnt != 2)
        {
            cout << x << ' ' << y << ' ' << z
                << " took " << cnt << '\n';
        }
    }
}

So I have a few curiosities:

*

*What inputs create the longest loop/cycle and never converge?

*What inputs take longest to converge?

*After normalizing once, what input gives the maximum error from a length of 1?


text:
Q: Server delay on system command in C I have two programs, one acting as a server and one acting as a client. They are supposed to act like you are connecting to remote system using ssh. The client sends a command and the server executes the command and prints the output to the server. Although my code does exactly that, there is a delay on the output after the first command. For example if the client sents date, the server will return the date. If the client sends date again it will print message was received but not the output. On the third input from client, the second date will be executed and print on the client Here is the message:date and so on. Any ideas would be really apreciated.
Server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <fcntl.h>
#define MAX_PINS 1
void error(const char *msg){
     perror(msg);
     exit(1);
}

void exec_comm(int sock,int nerror,char buff[]){
     dup2(sock,1);
     dup2(nerror,2);
     if(system(buff)==-1){
          printf("command not found\n");
     }
}
int main(int argc, char *argv[]){
  int sockfd, newsockfd, portno, pid;
  socklen_t clilen;
  char buffer[256];
  char* comm[20],*cbuff;
  struct sockaddr_in serv_addr, cli_addr;
  int n,i,done=0,correct=0;
  char str[INET_ADDRSTRLEN];
  char* args,*pins[MAX_PINS]={"1234"},pin[10];
  FILE* fd;
  int nerror;
     if (argc < 2){
       fprintf(stderr, "No port provided\n");
       exit(1);
     }
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0)
     error("ERROR opening socket");
     memset((char *) &serv_addr, 0, sizeof(serv_addr));
     portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd,(struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
     error("ERROR on binding");

          listen(sockfd, 5);
          clilen = sizeof(cli_addr);
          newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
          if (newsockfd < 0)
          error("ERROR on accept");
          if (inet_ntop(AF_INET, &cli_addr.sin_addr, str, INET_ADDRSTRLEN) == NULL) {
          fprintf(stderr, "Could not convert byte to address\n");
          exit(1);
          }
          fprintf(stdout, "The client address is :%s\n", str);
while(1){
               bzero(buffer, 256);
               n = read(newsockfd, buffer, 255);
               sscanf(buffer,"%s\n",buffer);
               printf("The message that was read was:\t%s\n",buffer);
               if (n < 0) error("ERROR reading from socket");
               fprintf(fd,"%s\n",buffer);
               if(strcmp(buffer,"exit\n")==0||strcmp(buffer,"exit")==0){
                    printf("Exiting...\n");
                    done=1;
                    break;
               }
               exec_comm(newsockfd,nerror,buffer);
               printf("Here is the message: %s\n", buffer);
               n = write(newsockfd, "message received", 17);
               if (n < 0) error("ERROR writing to socket");
          }

     fclose(fd);
     close(newsockfd);
     close(sockfd);
     return 0;
}

Client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg){
     perror(msg);
     exit(0);
}

int main(int argc, char *argv[]){
     int sockfd, portno, n;
     struct sockaddr_in serv_addr;
     struct hostent *server;
     char buffer[256];
     if (argc < 3){
          fprintf(stderr, "usage %s hostname port\n", argv[0]);
          exit(0);
     }
     portno = atoi(argv[2]);
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0)
     error("ERROR opening socket");
     server = gethostbyname(argv[1]);
     if (server == NULL){
          fprintf(stderr, "ERROR, no such host\n");
          exit(0);
     }
     bzero((char *) &serv_addr, sizeof(serv_addr));
     serv_addr.sin_family = AF_INET;
     bcopy((char *)server->h_addr,
     (char *)&serv_addr.sin_addr.s_addr,server->h_length);
     serv_addr.sin_port = htons(portno);
     if (connect(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
     error("ERROR connecting");
     n = write(sockfd, stdin, sizeof(int));
     if (n < 0)
     error("ERROR writing to socket");
     do{
          printf("Please enter the message: ");

          bzero(buffer, 256);
          fgets(buffer, 255, stdin);
          if(strcmp(buffer,"exit\n")==0||strcmp(buffer,"exit")==0){
               printf("Exiting...\n");
               n = write(sockfd, buffer, strlen(buffer));
               if (n < 0)
               error("ERROR writing to socket");
               close(sockfd);
               break;
          }
          n = write(sockfd, buffer, strlen(buffer));
          if (n < 0)
          error("ERROR writing to socket");
          bzero(buffer, 256);
          n = read(sockfd, buffer, 255);
          if (n < 0)
          error("ERROR reading from socket");
          printf("%s\n", buffer);
     }while(1);

     return 0;
}

A: n = write(sockfd, buffer, strlen(buffer));

That's your problem right here. Calls to write do not result in individual distinguishable messages, one message per call. They result in a single homogenous stream (that's the "stream" in SOCK_STREAM) of bytes with no delimiters.
You have newlines that separate commands, which is nice and all, but read has no idea about newlines. It will just wait until the buffer is full, or enough time has passed, or whatever. You have no control over it.
You basically have 2 ways to fix this.

*

*Read character by character (pass the length of 1) and stop as soon as you see a newline. Accumulate the characters in a buffer, then execute it.

*Send the length of each message before the message itself, in a fixed-length record, so that the server can safely read the length and then use it to read the message itself.


text:
Q: Casting "with" Interface interface I{}
class A implements I{}
class B{}

First:
I[] arr = new A[10];
arr[0] = (I) new B(); // will produce ClassCastException at runtime

Second:
wherein if I use concrete class
I[] arr = new A[10];
arr[0] = (A) new B(); // will produce compile-time error

What's the difference if in my first example,(I) new B(), the java compiler should produce compile-error as well?
Isn't it that the java compiler should be able to distinguish that it is also an "inconvertible type"? Especially when the new operator comes immediately?
Is there any instance/chance that it will be possible that creating that new instance of B could produce a
convertible type of type I?
I know at some point, that the Java compiler should not immediately say that it is a compiler error, like when you do this:
I i = (I) getContent(); // wherein getContent() will return a type of Object

Edit:
Let me clarify this question why it is not a possible duplicate of this: Cast reference of known type to an interface outside of type's hierarchy
The intention of this question is not because I am not aware of what will be the result of or what is something wrong with something, etc.
I just want to know a "more detailed explanation in a technical way" of why does the JVM behave that way or why does Java came up with that kind of decision of not making that kind of scenario a compile-time error.
As what we all know, it is always better to find "problematic code" at compile-time rather than at run-time.
Another thing, the answer I am looking for was found here on this thread not on those "duplicates?".

A: The difference in this situation is obviously that I is an interface, which could be implemented. This means, that even though B has nothing to do with I, there could be a subclass of B, that implements the interface I. Will illustrate this with an example:
interface I{}
class A implements I{}
class B{}
class C extends B implements I{}

I[] arr = new A[10]; // valid, cause A implements I
B b = new C(); // Valid because C is a subclass of B
arr[0] = (I) b; // This won't produce ClassCastException at runtime, because b
                // contains an object at runtime, which implements I
arr[0] = (I) new B(); // This will compile but will result in a ClassCastException
                      // at runtime, cause B does not implement I

It's important to distinguish the difference between static and dynamic types. In this case the static type of the variable b is B, but it has the dynamic type (the runtime type) C, where new B() does also have the static type B, but the dynamic type is also B. And as in some cases a cast from B to I won't result in exceptions (as in this scenario), the compiler allows such casts but only to an interface type.
Now take a look at the following scenario:
I[] arr = new A[10];
B b = new C(); // Valid because C is a subclass of B
A a1 = (A) b; // compile time error
A a2 = (A) new B(); // compile time error

Is it possible that a subclass of B will ever extend A and B at the same time? The answer is NO, cause you are limited to only one super class to extend in Java (where in some other OO languages this is not the case), therefore the compiler forbids it, cause there are no possible scenarios, where this will work.

A: The rules for what casts are compile-time legal only take into account the static types.
When the Java compiler analyzes the expression (I) new B(), it sees that the static type of the expression new B() is B. We can tell that new B() can't possibly be an instance of I, but the compile-time analysis rules can't tell that the object isn't actually an instance of a subclass of B that implements I.
Thus, the compiler has to let it through. Depending on how sophisticated the compiler is, it might detect the oddity and issue some sort of warning, but in the same way 1/0 isn't a compile-time error, this can't be a compile-time error.

A: You can cast any object to the desired var, only if you cast it to the var type:
interface I{}
class A implements I{}
class B{}

I var = (I) object; // This is always possible in compile-time, no matter the object type, because object is casted to the var type, I
I var = (A) object; // Not possible in compile-time because of the difference of types

The runtime exception comes when the object cannot be casted, but you can't know it until runtime.
A object = new A();
I var = (I) object;
B anotherObject = new B();
var = (I) anotherObject;

Both of the above will work in compile-time, but only the first one will do it in runtime, because of the implementation of the I interface.

A: Class inheritance is single inheritance, no future descendant can introduce a new base class, e.g. in your example, no descendent of B can ever be cast to A. But it can introduce a new interface, i.e. a descendent of B could support I.
It's a failing of the compiler that it can't solve your simple case, but it's not a case you would ever see in the wild. Create and cast in one line that is.
Example of why the compiler can't detect this in a more complex case using your classes
void method(B b){
  I i = (I) b;
}

class C extends B implements I{} // a descendent of B that introduces support for I

method(new A()); //still compile time error
method(new B()); //runtime exception
method(new C()); //works

A: I tried four cases:

*

*Casting a class to another class.

*Casting a class to an interface.

*Casting an interface to a class.

*Casting an interface to another interface.

Compile-time error only happens in the first case.
static interface I {}
static interface J {}

static class A {}
static class B {}

Object o = (B) new A();       // compile-time error
Object o = (I) new A();       // runtime error
Object o = (B) ((I) new A()); // runtime error
Object o = (J) ((I) new A()); // runtime error

My guess is that this happens because determining whether the cast will succeed or not relatively easier in the first case, compared to the other three cases. The main reason is that a class can only extend one class, which allows the compiler to reason whether the cast will succeed or not. See these examples:
Suppose, in addition to the above classes and interfaces, I add new class:
static class C extends B implements I, J {}

Example of code that casts a class to an interface (last line):
C c = new C();
B b = (B) c;
I i = (I) b; // This is ok.

Example of code that casts an interface to a class (last line):
C c = new C();
I i = (I) c;
B b = (B) i; // This is ok.

Example of code that casts an interface to another interface (last line):
C c = new C();
I i = (I) c;
J j = (J) i; // This is ok.


text:
Q: ASP.NET Core how to upload image to SQL Server database? I am trying to do a simple app to register users to a database with name, surname, profile photo etc. then edit or delete them. I am planning to upload the image as IFileForm, then convert it to varbinary for SQL Server. But I am having a problem on how to implement uploading the image. The code works for other members. Any help would be appreciated.
My user model class for API
public partial class User
{
    public string UserId { get; set; };
    public string UserName { get; set; };
    public string UserSurname { get; set; };
    public string UserBirthdate { get; set; };
    public byte[] UserPicture { get; set; };
}

Post method for my API
public async Task<ActionResult<User>> PostUser(User user)
{
    _context.UserTable1s.Add(user);

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (UserExists(user.UserId))
        {
             return Conflict();
        }
        else
        {
            throw;
        }
    }

    return CreatedAtAction("GetUser", new { id = user.UserId }, user);
}

My user model for Web App
public class User
{
    public string UserId { get; set; }
    public string UserName { get; set; }
    public string UserSurname { get; set; }
    public string UserBirthdate { get; set; }
    public IFormFile UserPicture { get; set; }
}

Post method for Web App to consume API
public async Task<IActionResult> AddUser(User user)
{
    User receivedUser = new User();

    using (var httpClient = new HttpClient())
    {
        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }

    return View(receivedUser);
}

And finally the view for AddUser. Removed the code for other members because too long.

        <form asp-action="AddUser" enctype="multipart/form-data">

            /*some more code here for other members*/

                User Picture
                <input asp-for="UserPicture" type="file" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

EDIT:
I managed to make it work after editing vega_gf's answer a little. I am pretty sure it is not the most optimal way but it works for now.
My AddUser method now:
public async Task<IActionResult> AddUser(User user, [FromForm]IFormFile imgfile)
{
    User receivedUser = new User();
    using (var httpClient = new HttpClient())
    {
            if (imgfile != null)
            {
                using var dataStream = new MemoryStream();
                await imgfile.CopyToAsync(dataStream);
                byte[] imageBytes = dataStream.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                user.UserPicture = base64String;
            }

        StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("https://localhost:7252/api/Users", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            receivedUser = JsonConvert.DeserializeObject<User>(apiResponse);
        }
    }
    return View(receivedUser);
}

Added an IFormFile imgfile property to my model and used it in view like this:

                User Picture
                <input asp-for="imgfile" type="file" class="form-control" />

A: First I would change image type to string(optional)
Then on your AddUser method you add this
[BindProperty]
public IFormFile ImageFile { get; set; }
public string Msg { get; set; }
public static readonly List<string> ImageExtensions = new() { ".JPG", ".BMP", ".PNG" }; //to restrict file extensions

if (HttpContext.Request.Form.Files.Count > 0)// check if the user uploded something
{
     ImageFile = HttpContext.Request.Form.Files.GetFile("file_Main");
     if (ImageFile != null)
     {
          var extension = Path.GetExtension(ImageFile.FileName);//get file name
          if (ImageExtensions.Contains(extension.ToUpperInvariant()))
          {
              using var dataStream = new MemoryStream();
              await ImageFile.CopyToAsync(dataStream);
              byte[] imageBytes = dataStream.ToArray(); // you can save this to your byte array variable and remove the 2 lines below
              string base64String = Convert.ToBase64String(imageBytes);
              User.UserPicture = base64String; // to save the image as base64String
              }
              else
              {
                  Msg = "image format must be in JPG, BMP or PNG"; //Custom error message
                  return Page();
              }
          }
      }
}

on your view just add this
@if (Model.User.UserPicture != null)
{
     model.User.UserPicture)" height="40" width="40">
}


text:
Q: How to get market cap of a coin using the CoinGecko C# API? I narrowed it down to:
ICoinGeckoClient CGClient = CoinGeckoClient.Instance;
var result2 = CGClient.CoinsClient.GetAllCoinsData ();

but I have to provide some arguments to GetAllCoinsData, but they don't make a lot of sense to me and I couldn't find any mention of this function or the original CoinGecko function seems to be a web based API. So not sure how I can pass a symbol, etc and get the coin data back to get the market cap data.
Any ideas on how to achieve this?

A: It seems you should use
        Task<CoinFullDataById> GetAllCoinDataWithId(string id);

Using the propper id.
There is a id/symbol list at: https://docs.google.com/spreadsheets/d/1wTTuxXt8n9q7C4NDXqQpI3wpKu1_5bGVmP9Xz0XGSyU/edit#gid=0
You can also download the code and check the comments/tests at: https://github.com/tosunthex/CoinGecko
        /// <summary>
    /// List all coins with data (name, price, market, developer, community, etc) - paginated by 50
    /// </summary>
    /// <returns></returns>
    Task<IReadOnlyList<CoinFullData>> GetAllCoinsData();

    /// <summary>
    /// List all coins with data (name, price, market, developer, community, etc) - paginated by 50
    /// </summary>
    /// <param name="order">order by</param>
    /// <param name="perPage">Total results per page</param>
    /// <param name="page">Page through results</param>
    /// <param name="localization">Set to false to exclude localized languages in response</param>
    /// <param name="sparkline">Include sparkline 7 days data (true/false) [default: false]</param>
    /// <returns></returns>
    Task<IReadOnlyList<CoinFullData>> GetAllCoinsData(string order, int? perPage, int? page, string localization,
        bool? sparkline);


text:
Q: Integral Continuation $\Gamma(z)=\int_{0}^{1} e^{-t} t^{z-1} dt +\int_{1}^{\infty} e^{-t} t^{z-1}dt$ I am trying to obtain an analytical continuation for $\Gamma(z)$ into the region of the complex plane characterized by $\Re(z) \leq 0$ but am stuck.
Starting from the integral definition of $\Gamma(z)$ which is valid for $\Re(z) \geq 0$, re-write
\begin{equation}
\Gamma(z)=\int_{0}^{1} e^{-t} t^{z-1} dt +\int_{1}^{\infty} e^{-t} t^{z-1}dt \equiv f_1(z)+f_2(z).
\end{equation}
We first show that $f_2(z)$ is holomorphic in the entire complex plane by writing
$$
f_2(z)=\int_{1}^{\infty} e^{-t} t^{-1} e^{z\ln t}dt=\int_{1}^{\infty} \frac{e^{-t}}{t} e^{i\Im(z)\ln t} t^{\Re(z)}dt
$$
where I used $z=\Re(z)+i\Im(z)$ and $\exp{(z\ln t)}=\exp[{\ln t(\Re(z)+i\Im(z))}].$  Now we take the magnitude of $f_2(z)$ to obtain
$$
\big|f_2(z)\big|=\bigg| \int_{1}^{\infty} \frac{e^{-t}}{t} e^{i\Im(z)\ln t} t^{\Re(z)}dt\bigg|\leq \int_{1}^{\infty} e^{-t} t^{\Re(z)-1}dt
$$
and we can see that this converges uniformly $\forall \ z.$  Thus we conclude that $f_2(z)$ is a holomorphic $\forall \ z$ and it is an entire function.  I am stuck here though, how to deal with the $f_1$ now?  Thanks

A: Where the integral is defined, we can integrate by parts:
$$\begin{align}
\int_0^1 e^{-t} t^{z-1}\,dt &= \frac{e^{-t}t^z}{z}\Biggr\rvert_0^1 + \frac{1}{z}\int_0^1 e^{-t} t^z\,dt\\
&= \frac{1}{ez} + \frac{1}{z}\int_0^1 e^{-t}t^z\,dt.
\end{align}$$
The integral now is defined for $\Re z > -1$, and for $\Re z > 0$, we have the missing part of $\Gamma$, so
$$\Gamma(z) = \frac{1}{ez} + \frac{1}{z}\int_0^1 e^{-t} t^z\,dt + \int_1^\infty e^{-t} t^{z-1}\,dt$$
is valid for $\Re z > -1$. Integrate by parts more often, and you get a representation valid for $\Re z > -k$.


text:
Q: Cálculos desfases horarios en python Hoy me ha surgido un problema que realmente no sé por dónde meterle mano. Espero que podáis ayudarme.
Tengo una serie de datos de los cuales me gustaría calcular el desfase de tiempo que existe entre una primera columna donde registro la aplicación de agua y la siguiente columna que recoge como sale el agua de mi sistema.
Yo entiendo que lo lógico sería crear un bucle que recorriese la primera columna hasta que cumpla la condición de que se aplique agua (en mi caso sería que fuese mayor que 0) y ver en la segunda columna a partir de ese dato cuando se registra la primera variación del flujo.
Para que sea más entendible, os pongo un ejemplo del tipo de datos que puedo tener (en imagen y en texto sin formato para que podáis disponer de dichos datos):

Measurement time  Entrada     Salida
22/09/2021 7:10   0   1
22/09/2021 7:15   0   1
22/09/2021 7:20   0   1
22/09/2021 7:25   0   1
22/09/2021 7:30   0   1
22/09/2021 7:35   0   1
22/09/2021 7:40   0   1
22/09/2021 7:45   0   1
22/09/2021 7:50   0   1
22/09/2021 7:55   0   1
22/09/2021 8:00   1   1
22/09/2021 8:05   83  1
22/09/2021 8:10   84  1
22/09/2021 8:15   84  1
22/09/2021 8:20   83  1
22/09/2021 8:25   83  1
22/09/2021 8:30   83  1
22/09/2021 8:35   80  1
22/09/2021 8:40   80  1
22/09/2021 8:45   82  1
22/09/2021 8:50   82  1
22/09/2021 8:55   82  1
22/09/2021 9:00   82  1
22/09/2021 9:05   82  2
22/09/2021 9:10   82  3
22/09/2021 9:15   83  3
22/09/2021 9:20   82  3
22/09/2021 9:25   82  3
22/09/2021 9:30   81  3
22/09/2021 9:35   3   3
22/09/2021 9:40   0   3
22/09/2021 9:45   0   3
22/09/2021 9:50   0   3
22/09/2021 9:55   0   3

Como podréis observar, Tengo una columna como índice que es el tiempo, la columna entrada donde se ve cuando se aplica el caudal de agua y la tercera que registra el caudal de salida de agua del sistema.
Lo único que se realizar es importar los ficheros excel (que son varios) y los he unido atendiendo a la única columna en común que tienen todos, es decir, Measurement Time. Una vez aquí ya no se qué realizar o si hay alguna función que sea lo más sencillo de aplicar.
El código que pretendía utilizar es:
union['Diferencias salida']=abs(union['salida'].diff(1))

for i in len(union):
    if union[i, 'entrada'] > 0:

        hora1= union[i, 'Measurement time'] for j in len(union):

    if union[j, 'Diferencias salida'] > 2:

        hora2= union[j, 'Measurement time']

   Diferenciahoras = hora2-hora1

Donde "union" corresponde al DataFrame que estoy utilizando y el resto de valores corresponden con las columnas del ejemplo utilizado.
¿Cómo podría realizar el bucle para que pueda obtener la información acerca del desfase entre la aplicación y la salida? ¿Alguien podría aconsejarme?
Muchas gracias.

A: Buen día,
Para calcular la diferencia entre dos fechas con hora puedes hacer lo siguiente
from datetime import datetime
antes = datetime(2012, 3, 5, 23, 8, 15)        # Fecha aleatoria en el pasado
ahora  = datetime.now()                        # Fecha de este momento
diferencia = ahora - antes                     # Diferencia
diferencia_en_s = diferencia.total_seconds()   # Diferencia total en segundos
print(diferencia)                              # Diferencia en días, HH:mm:ss

En este ejemplo se muestra como puedes obtener la diferencia entre dos fechas con hora. Podrías cargar las fechas y hora en las variables "antes" y "ahora" al recorrer tu bucle.